Creating the SocketOpener Class to Send and Receive Messages


The SocketOpener.java file creates a socket with the Jabber server to send and receive messages between end users. Listing 3-5 shows the contents of the SocketOpener.java file:

Listing 3-5: The SocketOpener.java File

start example
 /*Imports required swing package classes.*/ import javax.swing.*; import javax.swing.JTextPane; import javax.swing.text.*; /*Import required awt package classes.*/ import java.awt.*; import java.awt.event.*; /*Import required io and net package classes.*/ import java.io.*; import java.net.*; /*Import required util package classes.*/ import java.util.*; import java.lang.*; /* class SocketOpener - This class is used for socket opening.  Constructor: SocketOpener - This constructor accept host name and IP. Methods: openSocket - open the socket getErrorString - get the error string send by server writemessage-used to write the message in the textpane. */ public class SocketOpener {    /*Declare the int variables.*/    private int openerport;    /* Declare objects of Socket classes.*/    static private Socket socket;    static MutableAttributeSet sendernameattrib, nameattribut, informationattrib, welcomenameattrib;    static Document contentmodel;    /*Declare objects of Stream classes.*/    static PrintWriter out = null;    static BufferedReader in = null;     /*Declare boolean variable.*/    private  static boolean isConnected=false;    /*Declare objects of Hasmap and vector class.*/    Vector nicknamevector=new Vector();    HashMap temphashmap=new HashMap();    /*Declare objects of GroupChat class.*/    static GroupChat gc;    /*Declare objects of RoomInformation class.*/    static RoomInformation socketroomgui;    /*Declare objects of ChatRoom class.*/    static ChatRoom socketchatmgui;    /*Declare objects of MainGUI class.*/    static MainGUI socketmaingui;    /*Declare objects of LoginGUI class.*/    static LoginGUI logingui;    /*Declare the string variable*/    static String errortype="";    private String openerhost;    String roomname="";    String firstname="";    String lastname="";    String emailid="";    String resource="Home";    String temproomname="";    Color textcolor;    String nickname="";    String servererror="";    /* function to open socket*/    public  SocketOpener openSocket(String hostip, int portnumber, int timeinsec)    {       sendernameattrib=new SimpleAttributeSet();       StyleConstants.setFontFamily(sendernameattrib, "Verdana");       StyleConstants.setForeground(sendernameattrib, Color.black);       welcomenameattrib=new SimpleAttributeSet();       StyleConstants.setFontFamily(welcomenameattrib, "Verdana");       StyleConstants.setForeground(welcomenameattrib, Color.blue);       nameattribut=new SimpleAttributeSet();       StyleConstants.setFontFamily(nameattribut,"Verdana");       StyleConstants.setForeground(nameattribut, Color.red);       informationattrib=new SimpleAttributeSet();       StyleConstants.setFontFamily(informationattrib, "Verdana");       StyleConstants.setItalic(informationattrib,true);       StyleConstants.setForeground(informationattrib, Color.red);       socketope();       try       {          out = new PrintWriter(socket.getOutputStream(), true);          in = new BufferedReader(new InputStreamReader(socket.getInputStream()));       }       catch(Exception exception)       {          JOptionPane.showMessageDialog(logingui, "Server not found", "Server not found", JOptionPane.ERROR_MESSAGE);          socketmaingui.servererror="Server error";       }       return getSocketClass();    }    /*Function to initialize the Socket class*/    public  void socketope()    {       try       {          socket=new Socket(openerhost, openerport);       }       catch(IOException ie)       {       }    }    /*Constructor for SocketOpener class*/    public SocketOpener(String host, int port)    {       socket=null;       openerhost=host;       openerport=port;    }    /*    Function returns the object of SocketOpener class    */    public SocketOpener getSocketClass()    {       return this;    }    /*Function to write a message*/    public void writemessage(String messagebody, MutableAttributeSet attribut)    {       try       {          gc.writeintotextfield(messagebody, attribut);       }       catch(Exception ble)       {       }    }    /* Function returns the error string send by server*/    public static String getErrorString(String codeid)    {       if (codeid=="'401'")       {          errortype="minor";          return "You have sent malformed syntax which can't be understood by server.";       }       if (codeid=="'404'")       {          errortype="major";          return "No Server exists.";       }       if (codeid=="'405'")       {          errortype="minor";          return "You have no right to send this command.";       }       if (codeid=="'409'")       {          errortype="major";          return "A user with this jabber id is already exist. Please choose another user id.";       }       if (codeid=="'403'")       {          errortype="auth";          return "Invalid password";       }       return "";    }    public void sendername(String tagentity)    {       String sendername="";       String newuserid="";       tagentity=tagentity.trim();       if (tagentity.startsWith("message"))       {          if (tagentity.indexOf("from=")>0&&tagentity.indexOf("from=")+6,tagentity.indexOf("\n"+sendername,nameattribut);          }       }       if (tagentity.startsWith("message"))       {          if (tagentity.indexOf("from=")>0&&tagentity.indexOf("to=")>0)          {             sendername=tagentity.substring(tagentity.indexOf("from=")+6,tagentity.indexOf("to="));             if(!nickname.trim().equalsIgnoreCase(sendername.trim()))             {                 gc.writeintotextfield("\n"+sendername.substring(sendername.indexOf("/")+1,                 sendername.indexOf("'"))+":",nameattribut);             }             else             {                 gc.writeintotextfield("\n"+sendername.substring(sendername.indexOf("/")+1,                 sendername.indexOf("'"))+": ",sendernameattrib);             }          }       }       if (tagentity.startsWith("presence"))       {          if (tagentity.indexOf("from=")>0&&tagentity.indexOf("to=")>0)          {             nickname=tagentity.substring(tagentity.indexOf("from=")+6, tagentity.indexOf("to=")-1);             if (tagentity.indexOf("type='unavailable'")>0||tagentity.indexOf("type=\"unavailable\"")>0)             {                gc.removeuser(nickname.substring(nickname.indexOf("/")+1, nickname.indexOf("'")));                String nickname1="\n"+nickname.substring(nickname.indexOf("/")+1,                nickname.indexOf("'"))+"  has left the room";                gc.writeintotextfield(nickname1, informationattrib);             }             else             {             if (gc!=null)             {                gc.addNewUser(nickname.substring(nickname.indexOf("/")+1,nickname.indexOf("'")));                String nickname1="\n"+nickname.substring(nickname.indexOf("/")+1,                nickname.indexOf("'"))+"  has joined the room";                gc.writeintotextfield(nickname1, informationattrib);             }             else             {                nicknamevector.add(nickname.substring(nickname.indexOf("/")+1,nickname.indexOf("'")));             }          }       }    }    if (tagentity.startsWith("item"))    {       if (tagentity.indexOf("jid")<0&&(tagentity.indexOf("affiliation='none'")>0)       &&(tagentity.indexOf("role='participant'")>0))       {          if (socketmaingui!=null)          {             temproomname=socketmaingui.getRoomName();             nickname=socketmaingui.getNickName();          }          if (socketchatmgui!=null)          {             temproomname=socketchatmgui.getRoomName();             nickname=socketchatmgui.getNickName();             gc=new GroupChat(temproomname,nickname,openerhost);             socketchatmgui.hide();             gc.setUserName(logingui.getUserName());             for (int i=0;i<nicknamevector.size();i++)             {                gc.addNewUser((String)nicknamevector.get(i));             }             gc.hashmap.putAll(temphashmap);             roomname=temproomname;             gc.writeintotextfield("Welcome to " +roomname+ "  room ", welcomenameattrib);          }          if (temproomname.equals("Regional")||temproomname.equals("Culture")||          temproomname.equals("Sports")||temproomname.equals("Education")||          temproomname.equals("Science")||temproomname.equals("Software"))          {             if (gc==null)             {             gc=new GroupChat(temproomname, nickname, openerhost);             gc.setUserName(logingui.getUserName());             for (int i=0;i<nicknamevector.size();i++)             {                gc.addNewUser((String)nicknamevector.get(i));             }             gc.hashmap.putAll(temphashmap);             roomname=temproomname;             gc.writeintotextfield("Welcome to " +roomname+ " room ", welcomenameattrib);          }          else          {             if (!gc.isVisible())             {                gc.clearPane();                gc.writeintotextfield("Welcome to " +roomname+ " room ", welcomenameattrib);                gc.setVisible(true);             }          }       }        if(temproomname.equals("Regional")||temproomname.equals("Culture")||        temproomname.equals("Sports")||temproomname.equals("Education")||        temproomname.equals("Science")||        temproomname.equals("Software"))       {       }       else       {          temphashmap.clear();          nicknamevector.clear();          if (socketchatmgui==null)          {             JOptionPane.showMessageDialog(null, "Room already exists.");          }       }       return;    }    if (tagentity.indexOf("jaffiliation=")>0)    {       newuserid=tagentity.substring(tagentity.indexOf("jaffiliation=")-2);       if(newuserid.equals(logingui.getUserName()+"@"+logingui.getServarName().trim()+"/Home"))       {          if (tagentity.indexOf("affiliation='owner'")>0||tagentity.indexOf          ("affiliation=\"owner\"")>0)          {             if (socketroomgui!=null)             {                socketroomgui.hide();                roomname=socketroomgui.getRoomName().trim();                nickname=socketroomgui.getNickName().trim();             }             else             {             try             {                roomname=socketmaingui.getRoomName().trim();                nickname=socketmaingui.getNickName().trim();             }             catch(Exception e)             {                JOptionPane.showMessageDialog(socketroomgui, "Room does not  exist");                return;             }          }          gc=new GroupChat(roomname,nickname,openerhost);          gc.setUserName(logingui.getUserName());          for (int i=0;i<nicknamevector.size();i++)          {             gc.addNewUser((String)nicknamevector.get(i));          }          gc.hashmap.putAll(temphashmap);          gc.writeintotextfield("Welcome to " +roomname+ "  room", welcomenameattrib);          }          else          {             if (roomname.equals("Regional")||roomname.equals("Culture")||roomname.equals             ("Sports")||roomname.equals("Education")||roomname.equals("Science")             ||roomname.equals("Software"))             {                gc=new GroupChat(roomname, nickname, openerhost);                gc.setUserName(logingui.getUserName());             }             else             {                if (gc!=null)                {                if (gc.isVisible())                {                   gc.hide();                   JOptionPane.showMessageDialog(null, "Room is already exist");                   return;                }             }          }          if (!socketroomgui.isVisible())          {             socketroomgui.setVisible(true);          }       }    }    if (tagentity.indexOf("role='none'")>0||tagentity.indexOf("role=\"none\"")>0)    {       if (!newuserid.equals(""))       {          gc.removeUserinHash(nickname,newuserid);       }    }    else    {       if (!newuserid.equals(""))       {          if (gc!=null)          {             gc.addNewUserinHash(nickname,newuserid);          }          else          {             temphashmap.put(nickname,newuserid);          }       }    } } } } /* Function to set the object of RoomInformation and MainGUI class */ public static void setRoomPointer(RoomInformation room,MainGUI maingui) {    socketroomgui=room;    socketmaingui=maingui; } /* Function to set the object of ChatRoom and MainGUI class */ public static void setChatPointer(ChatRoom chatroom,MainGUI maingui) {    socketchatmgui=chatroom;    socketmaingui=maingui; } /*Function to set the object of MainGUI class*/ public static void setMainPointer(MainGUI maingui) {    socketmaingui=maingui; } /*Function to set the object of LoginGUI class*/ public static void setLogin(LoginGUI lgui) {    logingui=lgui; } /*Function to check xml error*/ public static String checkForError(String tagentity) {    String error="";    String codeid="";    if (tagentity.indexOf("error")>0)    {    if (tagentity.indexOf("from=")>0)    {       codeid=tagentity.substring(tagentity.indexOf("type="));       return "Invalid password.";    }    return "No user exists for this user ID."; } if (tagentity.indexOf("result")>0) {    if(!socketmaingui.isVisible()) {    socketmaingui.setVisible(true);    logingui.setVisible(false); } } return error; } /*Function to read the message from socket*/ public void runinput() {    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 ((char)i=='<')             {                starttag=true;                starttagsing=1;                tagentity="";             }             else             {                if ((char)i=='/'&& starttag==true &&starttagsing==1 )                {                   starttag=false;                   endtag=true;                   if (!messagebody.trim().equals(""))                   {                      writemessage(messagebody,sendernameattrib);                   }                   startwritting=false;                   messagebody="";                   vactorindex=vactorindex-1;                   if (vactorindex>=0)                   tagvactor.removeElementAt(vactorindex);                }                else                {                starttagsing=0;                if((char)i=='>')                {                   if (starttag)                   {                      sendername(tagentity);                      errorstring=checkForError(tagentity);                      if (errorstring.equals("Invalid password."))                      {                         JOptionPane.showMessageDialog(logingui, "Invalid password", "Invalid                         password",JOptionPane.ERROR_MESSAGE);                         return;                      }                      if (!errorstring.equals(""))                      {                         String username=logingui.getUserName();                         String password=logingui.getPassword();                         String servarn=logingui.getServarName();                         String registrationstring="<iq type=\"set\" to=\""+username+"@"+servarn+"\"                         id=\"1001\">";                         registrationstring=registrationstring+"<query                         xmlns=\"jabber:iq:register\">";                         registrationstring=registrationstring+"<username>"+username+                         "</username>";registrationstring=registrationstring+"<password>                         "+password+"</password>";                          registrationstring=registrationstring+"<first>                          "+firstname+"</first>";                         registrationstring=registrationstring+"<last>"+lastname+"</last>";                         registrationstring=registrationstring+"<email>"+emailid+"</email>";                         registrationstring=registrationstring+" </query> ";                         registrationstring=registrationstring+"</iq>";                         String authentication="<iq type=\"set\" id=\"1301\">";                         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>";                         if(errortype=="auth")                         {                            errororwarning="Error";                         }                         if(errortype=="major")                         {                            errororwarning="Error";                            JOptionPane.showMessageDialog(null, errorstring, errororwarning,                            JOptionPane.PLAIN_MESSAGE);                            sendXMLToJabber(registrationstring);                            sendXMLToJabber(authentication);                            if (socketmaingui!=null)                            {                               socketmaingui.hide();                            }                         }                         else                         {                            errororwarning="Warning";                            sendXMLToJabber(registrationstring);                            sendXMLToJabber(authentication);                            if (socketmaingui!=null)                            {                               socketmaingui.hide();                            }                         }                      }                      startwritting=true;                      tagvactor.insertElementAt(tagentity,vactorindex);                      vactorindex=vactorindex+1;                      starttag=false;                   }                }                else                {                   if (startwritting==true&&tagentity.trim().equals("body"))                   {                      messagebody=messagebody+(char)i;                      messagebody=messagebody.trim();                   }                   if (starttag)                   {                      tagentity=tagentity+(char)i;                   }                }             }          }       }    }    catch(IOException ie)    {       JOptionPane.showMessageDialog(socketchatmgui, "Room not found", "Room not       found", JOptionPane.ERROR_MESSAGE);       return;    } } isConnected=false; } /*Function to send xml to server*/ public static void sendXMLToJabber(String outputmessage) {    out.println(outputmessage);    out.flush(); } /*Function to set the object of GroupChat class*/ public static void setgc(GroupChat groupchat) {    gc=groupchat; } } 
end example

Download this listing.

In the above code, the constructor of the SocketOpener class takes host and port as input parameters. The host string retrieves the name of the Jabber server and the port integer retrieves the port number to open the socket with the Jabber server.

The methods defined in Listing 3-5 are:

  • openSocket(): Opens the socket to send and receive messages.

  • getErrorString(): Retrieves the error string sent by the Jabber server.

  • writemessage(): Writes the text message in the text area of the Group Chat window.

  • sendXMLToJabber(): Sends an XML (eXtensible Markup Language) message to the Jabber server.

  • setgc(): Sets the object of the GroupChat class.

  • runinput(): Listens for the server response sent by the Jabber server.

  • checkForError(): Checks whether or not the input string contains an error message.

  • setLogin(): Sets the object of the LoginGUI class.

  • setChatPointer(): Sets the objects of the ChatRoom and MainGUI classes.

  • setRoomPointer(): Sets the objects of the RoomInformation and MainGUI classes.

  • sendername(): Retrieves the sender’s name from the input message received from the Jabber server.

  • getErrorString(): Retrieves the message sent by the Jabber server.

  • socketope(): Initializes the Socket class to invoke the methods of the Socket class.




Developing Applications Using Jabber
Developing Applications Using Jabber
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 68

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net