package ChatApp; import java.math.*; import java.awt.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CORBA.*; import java.applet.*; import java.awt.*; import java.awt.event.*; /** * MyChatApp is the application gui for the Chat Client. It handles gui update with incoming * and outgoing messages form the ChatServer. It communicates with the ChatRegistryServant to * register, unregister, send and receive messages. */ public class MyChatApp extends Frame implements ActionListener{ /** * Maximum fixed length of a client ID, for encryption/decruption purposes */ final private static int ID_MAX_LENGTH = 16; /** * Maximum message length. For encryption/decruption purposes * */ final private static int MESSAGE_MAX_LENGTH = 128; /** * The program arguments. Must include the -ORBInitialPort option and may * also include the -ORBInitialHost option is the Naming Service is running * on a remote machine * to run the client app type: * java -classpath .;; ChatApp.MyCHatApp -ORBInitialPort */ private static String[] programArgs = null; /** * Gui component */ private Button ivjConnectButton = new java.awt.Button(); /** * Gui component */ private TextField ivjConnectString = new java.awt.TextField("",ID_MAX_LENGTH); /** * Gui component */ private TextField ivjMessageString = new java.awt.TextField("",MESSAGE_MAX_LENGTH); /** * Gui component */ private Button ivjSendButton = new java.awt.Button(); /** * Gui component */ private List ivjChatList = new java.awt.List(); /** * The program arguments. Must include the -ORBInitialPort option and may * also include the -ORBInitialHost option is the Naming Service is running * on a remote machine * to run the client app type: * java -classpath .;; ChatApp.MyCHatApp -ORBInitialPort */ private java.lang.String[] programArguments; /** * Gui component */ private Choice usersList = new java.awt.Choice(); /** * Gui component */ private Label usersLabel = new java.awt.Label(); /** * Flag for indicating of the client is registered to the server */ private boolean isRegistered = false; /** * The ORB object to connect to the naming service */ private ORB orb; /** * The naming context that holds the client and server objects */ private NamingContext ncRef; /** * The ChatClientServant that is related to this gui */ private ChatClientServant chatClient; /** * A reference to the remote server object */ private ChatRegistry chatRegistry; /** * Application constructor. initializes components in applet * Fetchs the Naming Context from the ORB and initializes the ChatCLientServant */ public MyChatApp(){ super(); // create and initialize the ORB orb = ORB.init(programArgs, null); // get the root naming context try{ org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); ncRef = NamingContextHelper.narrow(objRef); }catch(Exception e) { e.printStackTrace(); System.out.println("Cannot find name service. Press Enter to terminate"); try{ System.in.read(); } catch(Exception E) { E.printStackTrace(); } System.exit(0); } chatClient = new ChatClientServant(this); ivjConnectString.setBounds(10, 30, 200, 25); ivjConnectButton.setBounds(230, 30, 80, 25); ivjConnectButton.setLabel("Connect"); ivjChatList.setBounds(10,60, 300, 130); ivjChatList.setEnabled(false); ivjChatList.setForeground(Color.blue); ivjMessageString.setBounds(10, 195, 230, 25); ivjMessageString.setEnabled(false); ivjSendButton.setBounds(250, 195, 60, 25); ivjSendButton.setEnabled(false); ivjSendButton.setLabel("Send"); usersLabel.setBounds(10, 225, 220, 25); usersLabel.setEnabled(false); usersLabel.setText("Select a user for private messaging"); usersList.setBounds(240, 225, 70, 25); usersList.setEnabled(false); usersList.add("All"); this.addWindowListener(new WindowAdapterInner()); } /** * Set the gui to registered/unregistered state */ public void setRegistered(boolean ok){ String buttonLabel = (ok ? "Disconnect" : "Connect"); ivjConnectButton.setLabel(buttonLabel); ivjSendButton.setEnabled(ok); ivjMessageString.setEnabled(ok); ivjChatList.setEnabled(ok); ivjConnectString.setEnabled(!ok); usersList.setEnabled(ok); usersLabel.setEnabled(ok); isRegistered=ok; } /** * Receives a broadcasted message from another registered client and updates the gui * This method is invoked by the related ChatClientServant */ public void printMessage(String message, String sender){ message = message.trim(); ivjChatList.add("\n"+sender+" says:\n "+message); } /** * Receives a private message from another registered client and updates the gui * This method is invoked by the related ChatClientServant */ public void printPrivateMessage(String message, String sender){ message = message.trim(); ivjChatList.add("\n"+sender+" says privately:\n "+message); } /** * Add another 'just registered' client to the uses list * This method is invoked by the related ChatClientServant */ public void addUser(String userName){ usersList.add(userName); } /** * remove a 'just unregistered' client to the uses list * This method is invoked by the related ChatClientServant */ public void removeUser(String userName){ usersList.remove(userName); } /** * Handles mouse events (mainly pressing buttons) * @param event java.awt.event.ActionEvent */ public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getSource() == ivjConnectButton) { if(!isRegistered) register(); else unregister(); } if (e.getSource() == ivjSendButton){ if(usersList.getSelectedItem().equals("All")) broadcastMessage(); else sendPrivateMessage(); } } /** * Broadcast a message to all other registered clients. * This method calls the broadcast method on the app related ChatClientServant object */ public void broadcastMessage(){ chatClient.broadcastMessage(ivjMessageString.getText(),ivjConnectString.getText() , chatRegistry); } /** * Sends a privatemessage to a selected registered client. * This method calls the sendPrivateMessage method on the app related ChatClientServant object */ public void sendPrivateMessage(){ chatClient.sendPrivateMessage( ivjMessageString.getText(), ivjConnectString.getText(), usersList.getSelectedItem(), chatRegistry); } /** * Register to the chat server. First get a hold on the remote ChatRegistry object * Then check on the naming service that there is no other registered client with the same ID. * Then invoke the register method on the app's related ChatClientServant */ public void register(){ String clientID = ivjConnectString.getText(); try { NameComponent nc = new NameComponent("ChatRegistry", ""); NameComponent path2[] = {nc}; chatRegistry = ChatRegistryHelper.narrow(ncRef.resolve(path2)); }catch (Exception e) { e.printStackTrace(); System.out.println("Server is not connected, inform client"); javax.swing.JOptionPane.showMessageDialog( this, "Chat Server is currently offline, please try again later", "Connection Error", javax.swing.JOptionPane.ERROR_MESSAGE); return; } try{ orb.connect(chatClient); System.out.println("client to register:***"+clientID+"***"); // 1. first check if an object already exists in the ORB registry: NameComponent nc = new NameComponent(clientID, ""); NameComponent path[] = {nc}; System.out.println("testing if client exisits"); ChatClient ref = ChatClientHelper.narrow(ncRef.resolve(path)); if(ref==null) System.out.println("Something is wrong here"); else { System.out.println("Client exists, show message"); javax.swing.JOptionPane.showMessageDialog( this, "User already exists, please suply a different name", "User Exists", javax.swing.JOptionPane.ERROR_MESSAGE); } } catch (Exception ex) { System.err.println("ERROR: " + ex); ex.printStackTrace(System.out); System.out.println("which means that the client does not exist in the ORB Registry"); try{ // 1. bind the Object Reference in Naming NameComponent nc = new NameComponent(clientID, ""); NameComponent path[] = {nc}; ncRef.rebind(path, chatClient); }catch(Exception e) {e.printStackTrace();} // 2. register the chatter to the server chatClient.registerToServer(ivjConnectString.getText(),chatRegistry); } } /** * Unregister from the server. First remove the client from the naming service. * Then invok the unregister method on the app's related ChatClientServant object */ public void unregister(){ try{ orb.connect(chatClient); // 1. unbind the Object Reference in Naming NameComponent nc = new NameComponent(ivjConnectString.getText(), ""); NameComponent path[] = {nc}; ncRef.unbind(path); // 3. unregister from the registry chatClient.unregisterFromServer(ivjConnectString.getText(), chatRegistry); }catch(Exception e) {e.printStackTrace(); } } /** * Return the list property value. * @return java.awt.List */ public java.awt.List getChatList() { return ivjChatList; } /** * Returns the program's arguments * Creation date: (5/11/2001 5:12:40 PM) * @return java.lang.String[] */ public String[] getProgramArguments() { return programArguments; } /** * Initializes the application. * */ public void init() { setName("MyChatApplet"); setLayout(null); add(ivjConnectButton, ivjConnectButton.getName()); add(ivjConnectString, ivjConnectString.getName()); add(ivjSendButton, ivjSendButton.getName()); add(ivjMessageString, ivjMessageString.getName()); add(ivjChatList, ivjChatList.getName()); add(usersList, usersList.getName()); add(usersLabel, usersLabel.getName()); ivjSendButton.addActionListener(this); ivjConnectButton.addActionListener(this); setSize(320,260); } /** * Starts the applet when it is run as an application * @param args an array of command-line arguments */ public static void main(java.lang.String[] args) { programArgs = args; MyChatApp app = new MyChatApp(); app.setResizable(false); app.setTitle("Chat Client"); app.setProgramArguments(args); app.init(); app.setVisible(true); app.requestFocus(); } /** * Sets the program's arguments * Creation date: (5/10/2001 9:47:37 PM) * @param args java.lang.String[] program's arguments */ public void setProgramArguments(String[] args) { programArguments=args; } class WindowAdapterInner extends java.awt.event.WindowAdapter { public void windowClosing(java.awt.event.WindowEvent event) { java.lang.Object object = event.getSource(); if (object == MyChatApp.this) { unregister(); System.exit(0); } } } }