Searching for the Airline Schedules


The SocketConector.java file reads the airlines.xml file to search for airline schedules that match an end user's query. The SocketConector class opens the socket to receive end user's query from the Jabber server and sends the matched airline schedules to the Jabber server. Listing 6-5 shows the contents of the SocketConnector.java file:

Listing 6-5: The SocketConnector.java File

start example
 /*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 swing classes*/ import javax.swing.*; /*Imports required List class*/ import java.util.List; /*Imports required Element class*/ import org.jdom.Element; /*Imports required Iterator class*/ import java.util.Iterator; /* class SocketConnector - This class is used for reading the input messages and writing output messages. Constructor: SocketConnector-This constructor calls openPort() method to open a client socket. Methods: openPort */ class SocketConnector implements Runnable { /*Declare object of Vector class.*/ public Vector tagvactor; /* Declare object of PrintWriter class.*/ PrintWriter out = null; /*Declare object of BufferedReader class.*/ BufferedReader in = null; /*Declare object of Socket class.*/ Socket clientsocket; /*Declare object of Thread class.*/ Thread inputmessagethread; /*Declare objects of String class.*/ String errortype; String ipaddress="localhost"; String resource="airlines"; String username="user10"; String password="user10"; String sendernamestring; int portno=5222; int wait=1000; public boolean isConnected; /* SocketConnector: This method call an openPort() method. Parameter: ipaddress - object of String class, portno, wait Return Value: boolean */ public SocketConnector(String ipaddress,int portno,int wait) {    this.ipaddress=ipaddress;    this.portno=portno;    this.wait=wait;    openPort(ipaddress,portno,wait);    if (clientsocket!=null)    {       isConnected=true;    }    else       {       System.err.println("Server not found.");       return;    }    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();    }    String sessionStratString;    String authentication;    String registrationstring;    sessionStratString="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";    sessionStratString=sessionStratString+" <stream:stream";    sessionStratString=sessionStratString+" to= \""+ipaddress +"\"";    sessionStratString=sessionStratString+"  xmlns=\"jabber:client\"";    sessionStratString=sessionStratString+" xmlns:stream=\"http://etherx.jabber.org/streams\">";    sendXMLToJabber(sessionStratString);    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>";    sendXMLToJabber(authentication);    /*    Initializes the object of Thread class.    */    inputmessagethread=new Thread(this);    /*    Calls start method of inputmessagethread.    */    inputmessagethread.start(); } public static void main(String args[]) {    SocketConnector socketconnector=new SocketConnector("localhost",5222,1000); } /* 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    {       clientsocket=SocketOpenerClass.openSocket(ipaddress,portno,timeinsec);    } } 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 ((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,sendernamestring);             }             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(""))                {                   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; try {    inputmessagethread.join(); } catch(Exception e) { } } /* writemessage: This method creates an object of XMLReader class, reads data from XML file, and send result to the client. Parameter: messagebody - Object of String class, sendername - Object of String class. Return Value: N/A */ public void writemessage(String messagebody,String sendername) { String[] spletedmessage=messagebody.split("#"); if (spletedmessage[1].indexOf("id")>=0) {    return; } String origin=spletedmessage[1].substring(7); String destination=spletedmessage[2].substring(12); String ddate=spletedmessage[3].substring(6); String rdate=spletedmessage[4].substring(6); String nationality=spletedmessage[5].substring(12); String typeofjurney=spletedmessage[6].substring(13); java.util.List flightdescriptionlist; XMLReader xmlreader=new XMLReader(); flightdescriptionlist=xmlreader.readFile("airlines.xml"); Iterator i = flightdescriptionlist.iterator(); String msgstr=""; String startmsgstr="@"; while (i.hasNext()) { Element dateelement; Element depdate=null; Element arrdate=null; Element eclass=null; Element gclass=null; Element eclassprice=null; Element gclassprice=null; Element arrtime=null; Element dtime=null; Element flightelement = (Element) i.next(); Element idelement=flightelement.getChild("id"); Element originelement=flightelement.getChild("origin"); Element flighnotelement=flightelement.getChild("flightno"); Element aircrafttypeelement=flightelement.getChild("aircrafttype"); Element noofstopelement=flightelement.getChild("noofstop"); Element destinationelement=flightelement.getChild("destination"); List executiveelement=flightelement.getChildren("class"); Iterator classiterator=executiveelement.iterator(); while (classiterator.hasNext()) {    Element classelement=(Element) classiterator.next();    eclass=classelement.getChild("executive");    gclass=classelement.getChild("economy");    eclassprice=classelement.getChild("executiveprice");    gclassprice=classelement.getChild("economyprice"); } Element economyelement=flightelement.getChild("economy"); List departurdatetimelist=flightelement.getChildren("departurdatetime"); List arrivaldatetimelist=flightelement.getChildren("arrivaldatetime"); Iterator idepartur=departurdatetimelist.iterator(); Iterator iarrivalarrival=arrivaldatetimelist.iterator(); while(idepartur.hasNext()) {    Element departuredateelement=(Element) idepartur.next();    depdate=departuredateelement.getChild("date");    dtime=departuredateelement.getChild("dtime"); } while(iarrivalarrival.hasNext()) {    Element arrivaldateelement=(Element) iarrivalarrival.next();    arrdate=arrivaldateelement.getChild("date");    arrtime=arrivaldateelement.getChild("atime"); } Element arrivaldateelement=flightelement.getChild("arrivaldatetime"); if (origin.equals(originelement.getTextTrim())&&destination.equals (destinationelement.getTextTrim())&&ddate.equals(depdate.getTextTrim())) {    msgstr=msgstr+"choice=YES";    msgstr=msgstr+"#flight="+flighnotelement.getTextTrim();    msgstr=msgstr+"#aircrafttype="+aircrafttypeelement.getTextTrim();    msgstr=msgstr+"#origin="+originelement.getTextTrim();    msgstr=msgstr+"#noofstop="+noofstopelement.getTextTrim();    msgstr=msgstr+"#destination="+destinationelement.getTextTrim();    msgstr=msgstr+"#ddate="+depdate.getTextTrim()+" "+dtime.getTextTrim();    msgstr=msgstr+"#adate="+arrdate.getTextTrim()+" "+arrtime.getTextTrim();    msgstr=msgstr+"#executive="+eclass.getTextTrim();    msgstr=msgstr+"#economy="+gclass.getTextTrim();    msgstr=msgstr+"##eclassprice="+eclassprice.getTextTrim();    msgstr=msgstr+"#gclassprice="+gclassprice.getTextTrim();    msgstr=msgstr+startmsgstr; } if(typeofjurney.equals("roundtrip")) {    if (destination.equals(originelement.getTextTrim())&&origin.equals    (destinationelement.getTextTrim())&&rdate.equals(depdate.getTextTrim()))    {       msgstr=msgstr+"choice=YES";       msgstr=msgstr+"#flight="+flighnotelement.getTextTrim();       msgstr=msgstr+"#aircrafttype="+aircrafttypeelement.getTextTrim();       msgstr=msgstr+"#origin="+originelement.getTextTrim();       msgstr=msgstr+"#noofstop="+noofstopelement.getTextTrim();       msgstr=msgstr+"#destination="+destinationelement.getTextTrim();       msgstr=msgstr+"#ddate="+depdate.getTextTrim()+" "+dtime.getTextTrim();       msgstr=msgstr+"#adate="+arrdate.getTextTrim()+" "+arrtime.getTextTrim();       msgstr=msgstr+"#executive="+eclass.getTextTrim();       msgstr=msgstr+"#economy="+gclass.getTextTrim();       msgstr=msgstr+"##eclassprice="+eclassprice.getTextTrim();       msgstr=msgstr+"#gclassprice="+gclassprice.getTextTrim();       msgstr=msgstr+startmsgstr;    } } } if (msgstr.equals("")) {    sendXMLToJabber("<message to='"+sendername+" type=\"chat\"><body    >No matching record found</body></message>"); } else {    sendXMLToJabber("<message to='"+sendername+"    type=\"chat\"><body>"+msgstr+"</body></message>"); } } /* 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) {    String[] tokenizerstring=outputmessage.split("\n");    System.out.println(outputmessage);    for (int i=0;i<tokenizerstring.length;i++ )    {    try    {       out.println(tokenizerstring[i]);       out.flush();    }    catch(Exception e)    {       System.out.println("error");       return;    }    out.flush();    } } /* getErrorString: This method checks input string for error code. Parameter: codeid - object of String class Return Value: String */ public String getErrorString(String codeid) {    if (codeid=="'401'")    {       errortype="minor";       return "You have sent malformed syntax, which can not be understood by server.";    }    if (codeid=="'404'")    {       errortype="major";       return "No User exist with this user id.";    }    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.";    }    return "";    }    /*    checkForError: This method substracts input string, retrieves errorcode, and calls getErrorString()    Parameter: tagentity - object of String class    Return Value: String    */    public String checkForError(String tagentity)    {       String error="";       String codeid="";       if (tagentity.startsWith("error"))       {       if (tagentity.indexOf("code=")>0)       {          codeid=tagentity.substring(tagentity.indexOf("code=")+6,tagentity.indexOf("type="));          error=getErrorString(codeid.trim());       }    }    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)    {    String sendername="";    if (tagentity.startsWith("message"))    {       if (tagentity.indexOf("from=")>0&&tagentity.indexOf("to=")>0)       {          sendernamestring=tagentity.substring(tagentity.indexOf("from=")+6,tagentity.indexOf("to="));       }    } } } /* class SocketOpenerClass - This class is used to create an object of socket class.  Constructor: openSocket Methods: getSocket: This method returns an handler of the object of socket class. */ class SocketOpenerClass implements Runnable { private String openerhost; private int openerport; private Socket socket; public static Socket openSocket(String hostip,int portnumber,int timeinsec) { SocketOpenerClass opener=new SocketOpenerClass(hostip,portnumber); Thread t=new Thread(opener); t.start(); try { t.join(timeinsec); } catch(InterruptedException exception) { } return opener.getSocket(); } public SocketOpenerClass(String host,int port) { socket=null; openerhost=host; openerport=port; } public Socket getSocket() { return socket; } public void run() { try { socket=new Socket(openerhost,openerport); } catch(IOException ie) { } } } 
end example

Download this listing.

In the above code, the constructor of the SocketConnector class takes the ipaddress string, and portno and wait intergers as input parameters. The ipaddress string retrieves the ip address of the Jabber server to connect. The portno integer retrieves the port number of the Jabber server to open a socket and the wait integer retrieves the initial time to wait before connecting to the Jabber server.

The methods defined in Listing 6-5 are:

  • openPort(): Opens a socket between the Jabber server and the Airline Reservation application.

  • writemessage(): Creates an object of the XMLReader class to read airline schedules from the airlines.xml file. The writemessage() method calls the sendXMLToJabber() method and passes the matched airline schedules to the sendXMLToJabber() method.

  • sendXMLToJabber(): Takes the matched airline schedule as an input parameter and sends the information to the Jabber server.

  • sendername(): Retrieves the name of the sender from the input message and checks the identity of the sender.

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

  • SocketOpenerClass(): Initializes the object of the SocketOpenerClass class.

  • getSocket(): Returns an object 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