The SocketClass.java file opens the socket to send and receive messages between end users with the help of a Jabber server. Listing 7-6 shows the contents of the SocketClass.java file:
Listing 7-6: The SocketClass.java File
/*Imports required java.util classes*/ import java.util.*; /*Imports required java.io classes*/ import java.io.*; /*Imports required java.net classes*/ import java.net.*; /*Imports required javax.swing classes*/ import javax.swing.*; /*Imports required DefaultMutableTreeNode class*/ import javax.swing.tree.DefaultMutableTreeNode; /* class SocketClass - This class is used for reading the input messages and writing output messages. Methods: isConnected: This method returns a boolean value. isWaitingForAuth: This method returns a boolean value. socketoOpenClass: This method returns a boolean value. setUserLoginHandler: This method sets handler to the object of UserLogin class. checkForRoster: This method calls another method of ContactList class. getUserInfo: This method returns a boolean value. setUserInfo: This method sets value of nouserexists variable. sendRosterRequest: This method creates a Jabber message string for Roster and passes this string into sendXMLToJabber method. getUserName: This method returns user name. getServerName: This method returns the server name. setWaitForAuth: This method sets a boolean value for waitforauth. sendXMLToJabber: This method sends XML message string for the jabber server. checkForError: This method checks whether input message contains a error code or not. sendername: This method extracts sender name from input message. setUserNameAndPassword: This method stores the user name and password of the logged in end user. sendSessionStartMessage: This method creates a Jabber message string for starting a jabber session and passes this string into sendXMLToJabber method. sendAuthorized: This method creates a Jabber message string for user authentication and passes this string into sendXMLToJabber method. sendRegistration: This method creates a Jabber message string for user registration and passes this string into sendXMLToJabber method. openPort: This method creates an object of SocketOpener class and class openSocket method of this class. */ class SocketClass implements Runnable { boolean isConnected=false; /*Declares the object of Vector class.*/ Vector tagvactor; /*Declares the object of PrintWriter class.*/ PrintWriter out = null; /*Declares the object of BufferedReader class.*/ BufferedReader in = null; /*Declares and initializes the object of Vector class.*/ String servername; int portno; int wait; Socket clientsocket; /*Declares the object of Thread class.*/ Thread inputmessagethread; /*Declares the object of String class.*/ String errortype; String resource="Home"; String username=""; String password=""; String auth=""; String sendername=""; String recevername=""; String vcardString=""; boolean waitforreg=false; boolean waitforauth=false; boolean waitForResult=false; boolean rosterflag=false; boolean nouserexists=false; boolean endofvcard=false; /*Declares the object of UserLogin class.*/ UserLogin userloginhandler; /*Declares the object of ContactList class.*/ ContactList contactlist; /*Declares the object of UserInfo class.*/ UserInfo ui; public SocketClass() {} /* isConnected: This method returns a boolean value. Parameter: N/A Return Value: boolean */ public boolean isConnected() { return isConnected; } /* isWaitingForAuth: This method returns a boolean value. Parameter: N/A Return Value: boolean */ public boolean isWaitingForAuth() { return waitforauth; } /* socketoOpenClass: This method returns a boolean value Parameter: ipaddress - object of String class, portno, wait Return Value: boolean */ public void socketoOpenClass(String ipaddress, int portno, int wait) { this.servername=ipaddress; this.portno=portno; this.wait=wait; openPort(servername,portno,wait); if (clientsocket!=null) { isConnected=true; try { /*Initializes the object of PrintWriter class.*/ out = new PrintWriter(clientsocket.getOutputStream(), true); /*Initializes the object of BufferedReader class.*/ in = new BufferedReader(new InputStreamReader(clientsocket.getInputStream())); } catch(Exception e) { e.printStackTrace(); } /*Initializes the object of Thread class.*/ inputmessagethread=new Thread(this); /*Calls start method of inputmessagethread.*/ inputmessagethread.start(); } } /* setUserLoginHandler: This method sets handler to the object of UserLogin class. Parameter: userlogin - object of UserLogin class Return Value: N/A */ public void setUserLoginHandler(UserLogin userlogin) { userloginhandler=userlogin; } public void run() { int i=0; String errororwarning=""; String errorstring=""; String inputstring=""; boolean starttag=false; boolean endtag=false; boolean startwritting=false; String messagebody=""; String tagentity=""; Vector tagvactor; tagvactor=new Vector(); int vactorindex=0; int starttagsing=0; while (true) { try { i=in.read(); if (i==-1) { break; } else { inputstring=inputstring+(char)i; if (endofvcard) { vcardString=vcardString+(char)i; } if ((char)i=='<') { starttag=true; starttagsing=1; tagentity=""; } else { if ((char)i=='/' && starttag==true ) { if (starttagsing==1) { starttag=false; endtag=true; if (!messagebody.trim().equals("")&&(!nouserexists)) { contactlist.writemessage(messagebody,sendername,recevername); } startwritting=false; messagebody=""; vactorindex=vactorindex-1; if (vactorindex>=0) tagvactor.removeElementAt(vactorindex); } tagentity=tagentity+(char)i; } else { starttagsing=0; if((char)i=='>') { if (starttag) { if (tagentity.endsWith("/")) { tagentity=tagentity.substring(0,tagentity.length()-1); } if (tagentity.equals("PREF")) { String nodename=((DefaultMutableTreeNode)contactlist.rostertree. getLastSelectedPathComponent()). toString(); String uid=(String)contactlist.hashnode.get(nodename); ui.setInfo(vcardString,nodename,uid); vcardString=""; } sendername(tagentity); errorstring=checkForError(tagentity); if (errorstring.equals("unauthorized")) { sendRegistration(); waitforreg=true; waitforauth=false; } if ((tagentity.indexOf("type='result'")>1)&&(waitforreg)&& (!errorstring.equals ("user exist"))) { sendAuthorized(); waitforauth=true; waitforreg=false; } if ((tagentity.indexOf("type='result'")>1)&&(waitforauth)) { waitforauth=false; } if (tagentity.indexOf("item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'")!=-1) { nouserexists=true; contactlist.removeFromRosterTree(sendername); } if (tagentity.indexOf("remote-server-not-found")!=-1) { nouserexists=true; contactlist.removeFromRosterTree(sendername); } if (rosterflag) { if (tagentity.indexOf("item")!=-1&&(!nouserexists)) { String[] splitedsendername=sendername.split("/"); String contactpersonname=tagentity.substring(tagentity.indexOf("name")+5, tagentity.indexOf("jid")).trim(); String jid=tagentity.substring(tagentity.indexOf("jid")+4,tagentity.length()); if (!jid.equals("'"+splitedsendername[0]+"'")) { contactlist.addToRosterTree(jid.trim(), contactpersonname.trim()); } } else { if (nouserexists) { contactlist.eraseText(sendername); JOptionPane.showMessageDialog(null, "No User exists with this jabber ID.", "Error",JOptionPane.PLAIN_MESSAGE); nouserexists=false; } } if (tagentity.indexOf("query")!=-1) { rosterflag=false; } } if (tagentity.indexOf("xmlns='vcard-temp'")>1&&(!endofvcard)) { endofvcard=true; } if ((tagentity.indexOf("type='result'")>1)&& (!waitforauth)&&(!waitforreg)) { waitForResult=true; } else { if (tagentity.indexOf("xmlns='jabber:iq:roster'") >1&&waitForResult) { rosterflag=true; waitForResult=false; } waitForResult=false; } if ((tagentity.indexOf("type='result'")>1)&&(!waitforauth)) { if (contactlist==null) { contactlist=new ContactList(this); sendRosterRequest(); userloginhandler.setVisible(false); } } if (errorstring.equals("user exixts")&&waitforreg) { JOptionPane.showMessageDialog(null, "A user with this user ID is already exists.Please enter other user ID.", errororwarning, JOptionPane.PLAIN_MESSAGE); } if (!errorstring.equals("")) { if (errortype=="major") { errororwarning="Error"; JOptionPane.showMessageDialog(null,errorstring, errororwarning, JOptionPane.PLAIN_MESSAGE); } else { errororwarning="Warning"; JOptionPane.showMessageDialog(null, errorstring, errororwarning, JOptionPane.PLAIN_MESSAGE); } } startwritting=true; tagvactor.insertElementAt(tagentity,vactorindex); vactorindex=vactorindex+1; starttag=false; } } else { if (startwritting==true&&tagentity.trim().equals("body")) { messagebody=messagebody+(char)i; } if (starttag) { tagentity=tagentity+(char)i; } } } } } } catch(IOException ie) { } } isConnected=false; } /* checkForRoster: This method calls another method of ContactList class. Parameter: uname - object of String class,nname - object of String class Return Value: boolean */ public boolean checkForRoster(String uname,String nname) { return contactlist.checkHash(uname,nname); } /* getUserInfo: This method returns a boolean value. Parameter: N/A Return Value: boolean */ public boolean getUserInfo() { return nouserexists; } /* setUserInfo: This method sets value of nouserexists variable. Parameter: flag Return Value: N/A */ public void setUserInfo(boolean flag) { nouserexists=flag; } /* sendRosterRequest: This method creates a Jabber message string for Roster and passes this string into sendXMLToJabber method. Parameter: N/A Return Value: N/A */ public void sendRosterRequest() { String rosterstring=""; rosterstring="<iq type=\"get\" id=\"1\">"; rosterstring=rosterstring+"<query xmlns=\"jabber:iq:roster\"/></iq>"; sendXMLToJabber(rosterstring); } /* getUserName: This method returns user name. Parameter: N/A Return Value: String */ public String getUserName() { return username; } /* getServerName: This method returns the server name. Parameter: N/A Return Value: String */ public String getServerName() { return servername; } /* setWaitForAuth: This method sets a boolean value for waitforauth. Parameter: flag - boolean Return Value: N/A */ public void setWaitForAuth(boolean flag) { waitforauth=flag; } /* sendXMLToJabber: This method sends XML message string for the jabber server. Parameter: outputmessage - object of String class Return Value: N/A */ public void sendXMLToJabber(String outputmessage) { if (outputmessage.indexOf("<vCard")!=-1) { ui=new UserInfo(); } String[] tokenizerstring=outputmessage.split("\n"); for (int i=0;i<tokenizerstring.length;i++ ) { try { out.println(tokenizerstring[i]); out.flush(); }catch(Exception e) { return; } out.flush(); } } /* checkForError: This method checks whether input message contains a error code or not. Parameter: tagentity - object of String class Return Value: String */ public String checkForError(String tagentity) { String error=""; String codeid=""; if (tagentity.equals("error code='403' type='auth'")) { sendRegistration(); } if ((tagentity.indexOf("code='401'")!=-1)||(tagentity.indexOf("code=\"401\"")!=-1)) { return "unauthorized"; } if ((tagentity.indexOf("code='409'")!=-1)||(tagentity.indexOf("code=\"409\"")!=-1)) { return "user exixts"; } return error; } /* sendername: This method extracts sender name from input message. Parameter: tagentity - object of String class Return Value: N/A */ public void sendername(String tagentity) { if (tagentity.startsWith("message")) { sendername=""; recevername=""; if (tagentity.indexOf("from=")>0&&tagentity.indexOf("to=")>0) { sendername=tagentity.substring(tagentity.indexOf("from=")+6,tagentity.indexOf("to=")-2); } if (tagentity.indexOf("to=")>0&&tagentity.indexOf("type=")>0) { recevername=tagentity.substring(tagentity.indexOf("to=")+4,tagentity.indexOf("type=")-2); } } } public void setUserNameAndPassword(String username,String password) { this.username=username; this.password=password; } /* sendSessionStartMessage: This method creates a Jabber message string for starting a jabber session and passes this string into sendXMLToJabber method. Parameter: N/A Return Value: N/A */ public void sendSessionStartMessage() { String sessionStratString; sessionStratString="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; sessionStratString=sessionStratString+"<stream:stream"; sessionStratString=sessionStratString+" to= \""+servername +"\""; sessionStratString=sessionStratString+" xmlns=\"jabber:client\""; sessionStratString=sessionStratString+" xmlns:stream=\"http://etherx.jabber.org/streams\">"; sendXMLToJabber(sessionStratString); } /* sendAuthorized: This method creates a Jabber message string for user authentication and passes this string into sendXMLToJabber method. Parameter: N/A Return Value: N/A */ public void sendAuthorized() { String authentication; authentication="<iq type=\"set\" id=\"1\">"; authentication=authentication+" <query xmlns=\"jabber:iq:auth\">"; authentication=authentication+"<username>"+username+"</username>"; authentication=authentication+"<password>"+password+"</password>"; authentication=authentication+"<resource>"+resource+"</resource>"; authentication=authentication+"</query> "; authentication=authentication+"</iq>"; sendXMLToJabber(authentication); } /* sendRegistration: This method creates a Jabber message string for user registration and passes this string into sendXMLToJabber method. Parameter: N/A Return Value: N/A */ public void sendRegistration() { String registrationstring; registrationstring="<iq type=\"set\" to=\""+username+"."+servername+"\" id=\"1\">"; registrationstring=registrationstring+"<query xmlns=\"jabber:iq:register\">"; registrationstring=registrationstring+"<username>"+username+"</username>"; registrationstring=registrationstring+"<password>"+password+"</password></ query></iq>"; sendXMLToJabber(registrationstring); } /* openPort: This method creates an object of SocketOpener class and class openSocket method of this class. Parameter: ipaddress - Object of String class, portno - int, timeinsec - int Return Value: N/A */ private void openPort(String ipaddress,int portno, int timeinsec) { String host; if (ipaddress.trim()=="") { System.out.println("No IP Address Specified."); } else { SocketOpener socketopener=new SocketOpener(); clientsocket=socketopener.openSocket(ipaddress, portno, timeinsec); } } } /* class SocketOpener - This class is used to create an object of socket class. Constructor: openSocket Methods: getSocket: This method returns a handler of the object of socket class. */ class SocketOpener { private Socket socket; public Socket openSocket(String hostip, int portnumber, int timeinsec) { try { socket=new Socket(hostip,portnumber); } catch(IOException ie) { System.out.println("Exception occurred while creating a socket : " +ie); } return getSocket(); } public SocketOpener() { } /* getSocket: This method returns a handler of the object of socket class. Parameter: N/A Return Value: Socket */ public Socket getSocket() { return socket; } }
Download this listing.
In the above code, the constructor of the SocketClass class creates a new instance of the SocketClass class. The object of the SocketClass class allows end users to invoke methods of the SocketClass class.
The methods defined in Listing 7-6 are:
isConnected(): Checks whether or not an end user is connected to the Jabber server.
isWaitingForAuth(): Checks whether or not an end user is authenticated with the Jabber server.
socketoOpenClass(): Checks whether or not a socket is open.
setUserLoginHandler(): Sets the handler to the object of the UserLogin class.
checkForRoster(): Calls the checkHash() method of the ContactList class.
getUserInfo: Checks whether or not information about an end user to be added to the contact list exists on the Jabber server.
setUserInfo(): Sets the status as true if the specified end user information does not exist on the Jabber server.
sendRosterRequest: Creates a message string and passes this message string to the sendXMLToJabber() method.
getUserName(): Retrieves the name of an end user.
getServerName(): Retrieves the name of the Jabber server.
setWaitForAuth(): Sets the status as true if an end user is authenticated by the Jabber server.
sendXMLToJabber(): Sends the message string to the Jabber server in XML format.
checkForError(): Checks whether or not the input string received from the Jabber server contains an error message.
sendername(): Retrieves the sender’s name from the input message received from the Jabber server.
setUserNameAndPassword(): Stores the user name and password of the logged on end user.
sendSessionStartMessage(): Creates a message string in the XML format for starting a Jabber session and passes this message string to the sendXMLToJabber() method.
sendAuthorized(): Creates a message string in XML format for user authentication and passes this message string to the sendXMLToJabber() method.
sendRegistration(): Creates a message string in XML format for user registration and passes this message string to the sendXMLToJabber() method.
openPort: Opens a client socket by using the IP address and port number of the Jabber server.
run(): Listens for the response sent by the Jabber server.