KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > planetamessenger > protocols > comvc > JClientEngine


1 /*
2     =========================================================================
3     Package comvc - Implements the ComVc Protocol.
4
5     This module is developed and maintained by PlanetaMessenger.org.
6     Specs, New and updated versions can be found in
7     http://www.planetamessenger.org
8     If you want contact the Team please send a email to Project Manager
9     Leidson Campos Alves Ferreira at leidson@planetamessenger.org
10
11     Copyright (C) since 2001 by PlanetaMessenger.org
12     
13     This library is free software; you can redistribute it and/or
14     modify it under the terms of the GNU Lesser General Public
15     License as published by the Free Software Foundation; either
16     version 2.1 of the License, or (at your option) any later version.
17
18     This library is distributed in the hope that it will be useful,
19     but WITHOUT ANY WARRANTY; without even the implied warranty of
20     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21     Lesser General Public License for more details.
22
23     You should have received a copy of the GNU Lesser General Public
24     License along with this library; if not, write to the Free Software
25     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26
27     =========================================================================
28 */

29 /**
30  *
31  * $Id: JClientEngine.java,v 1.11 2007/02/12 00:43:55 popolony2k Exp $
32  * $Author: popolony2k $
33  * $Name: $
34  * $Revision: 1.11 $
35  * $State: Exp $
36  *
37  */

38
39 package org.planetamessenger.protocols.comvc;
40
41 import java.io.*;
42 import java.net.*;
43 import java.util.*;
44 import java.text.*;
45 import org.planetamessenger.io.*;
46 import org.planetamessenger.net.*;
47 import org.planetamessenger.util.*;
48
49
50
51 class JClientEngine implements org.planetamessenger.system.JTimerListener {
52
53   private final int MAX_ACK_FAIL = 2;
54   private final int CH_LOGIN_HOST = 0;
55   private final int CH_BOS_HOST = 1;
56   private final int CH_BOS_SERVICES = 2;
57   private final int DATAGRAM_TIMEOUT = 50000;
58   private final int SOCKET_TIMEOUT = 20000;
59   
60   private boolean bLoggedIn;
61   private JComVcEventListener pluginListener;
62   private JComVcSocketEvents peerSokListener;
63   private JComVcUDPEvents peerUDPListener;
64   private JThreadServerSocket peerServerSok;
65   private JThreadServerUDP peerServerUDP;
66   private org.planetamessenger.system.JTimer keepAliveTimer;
67   private HashMap<Long JavaDoc, JComVcContactItem> hContactList;
68   private int nAckError;
69   
70   protected java.lang.String JavaDoc strAdminHost;
71   protected int nAdminPort;
72   public JUserDetails userDetails;
73   public JSystemDetails systemDetails;
74
75   
76
77   private Socket connectToHost( int nWhatHost ) {
78   /**
79      Try to create a connected socket with
80      the Login host specified in systemDetails
81      object.
82      Parameters:
83       * nWhatHost - What is the host to connect ??
84   */

85     
86     Socket clientSok;
87     String JavaDoc strHost;
88     int nPort;
89     
90     
91     // Sets the host specified in parameter nWhatHost
92
if( ( nWhatHost == CH_BOS_HOST ) || ( nWhatHost == CH_BOS_SERVICES ) ) {
93       strHost = systemDetails.getBOSAddress();
94       
95       if( nWhatHost == CH_BOS_HOST )
96         nPort = systemDetails.getBOSPort();
97       else
98         nPort = systemDetails.getServicesPort();
99     }
100     else {
101       strHost = systemDetails.getLoginHost();
102       nPort = systemDetails.getLoginHostPort();
103     }
104   
105     try {
106       clientSok = new Socket( strHost, nPort );
107       clientSok.setSoTimeout( SOCKET_TIMEOUT );
108     } catch ( IOException e ) {
109       System.err.println( "connectToHost(1) - " + e );
110       return null;
111     }
112     
113     return clientSok;
114   }
115   
116   private Socket connectToHost( JComVcContactItem contactItem ) {
117   /**
118      Try to create a connected socket with
119      the Login host specified in systemDetails
120      object.
121      Parameters:
122       * contactItem - Peer to connect;
123   */

124     
125     Socket clientSok;
126   
127     try {
128       clientSok = new Socket( contactItem.strIPAddress, contactItem.nTCPPort );
129       clientSok.setSoTimeout( SOCKET_TIMEOUT );
130     } catch ( IOException e ) {
131       System.err.println( "connectToHost(2) - " + e );
132       return null;
133     }
134        
135     return clientSok;
136   }
137   
138   private boolean sendNotificationToUser( JComVcContactItem contactItem ) {
139   /**
140    * Send a INP message to user.
141    * Parameters:
142    * o contactItem - The user that will
143    * receive the packet;
144   */

145     
146     DatagramSocket udpSok;
147     String JavaDoc strFmt;
148     
149     
150     
151     if( userDetails.getStatus() != JComVcConstants.STATUS_OFFLINE )
152       strFmt = JComVcConstants.formatInpOutString( true, userDetails, systemDetails, contactItem.nTicket );
153     else
154       strFmt = JComVcConstants.formatInpOutString( false, userDetails, systemDetails, contactItem.nTicket );
155     
156     try {
157       udpSok = new DatagramSocket();
158       udpSok.setSoTimeout( DATAGRAM_TIMEOUT );
159     } catch( SocketException e ) {
160       System.err.println( "sendNotificationToUser()" + e );
161       return false;
162     }
163       
164     try {
165       InetAddress address = InetAddress.getByName( contactItem.strIPAddress );
166       DatagramPacket pak = new DatagramPacket( strFmt.getBytes(), strFmt.getBytes().length, address, contactItem.nUDPPort );
167
168       
169       udpSok.send( pak );
170       pak = null;
171     } catch( UnknownHostException uhe ) {
172       System.err.println( "sendNotificationToUser()" + uhe );
173       return false;
174     } catch( IOException ioe ) {
175       System.err.println( "sendNotificationToUser()" + ioe );
176       return false;
177     }
178
179     return true;
180   }
181   
182   private boolean notifyContactList() {
183   /**
184    * Notify the ContactList the new user
185    * info.
186   */

187     int nContactListSize = hContactList.values().toArray().length;
188     
189     
190     for( int nCount = 0; nCount < nContactListSize; nCount++ ) {
191       JComVcContactItem contactItem = ( JComVcContactItem ) hContactList.values().toArray()[nCount];
192     
193       if( contactItem.nUserStatus != JComVcConstants.STATUS_OFFLINE )
194         sendNotificationToUser( contactItem );
195     }
196     
197     return true;
198   }
199   
200   private void processAckTolerance() {
201   /**
202    * Ack fail tolerance implementation.
203    * Verify if server ack tolerance error
204    * was reached and disconnects plugin
205    */

206    
207     if( nAckError == MAX_ACK_FAIL ) {
208       logout();
209       nAckError = 0;
210     }
211     else
212       nAckError++;
213   }
214
215   JClientEngine() {
216   /**
217      Constructor. Initializes all class
218      data.
219   */

220
221     hContactList = new HashMap<Long JavaDoc, JComVcContactItem>();
222     userDetails = new JUserDetails();
223     systemDetails = new JSystemDetails();
224     peerSokListener = new JComVcSocketEvents();
225     peerUDPListener = new JComVcUDPEvents( hContactList );
226     keepAliveTimer = new org.planetamessenger.system.JTimer( JComVcConstants.COMVC_KEEPALIVE_TIME, this );
227     strAdminHost = JComVcConstants.COMVC_ADMIN_SERVER;
228     nAdminPort = JComVcConstants.COMVC_ADMIN_PORT;
229     bLoggedIn = false;
230     pluginListener = null;
231     nAckError = 0;
232   }
233   
234   void addComVcEventListener( JComVcEventListener listener ) {
235   /**
236      Add a event listener to this
237      engine class. All events will
238      be dispatch to this listener.
239      Parameter:
240       * listener - Listener to attach
241         in this class;
242   */

243     
244     pluginListener = listener;
245     peerSokListener.addComVcEventListener( listener );
246     peerUDPListener.addComVcEventListener( listener );
247   }
248   
249   void setUser( JUserDetails userDetails ) {
250   /**
251    * Sets the user info for this
252    * connection.
253    * Parameters:
254    * o userDetails - User details class
255    * for this connection.
256    */

257     
258     this.userDetails = userDetails;
259   }
260   
261   JUserDetails getUser() {
262   /**
263    * Retrieve the user details
264    * object of this connection.
265    */

266     
267     return userDetails;
268   }
269   
270   boolean createNewUser() {
271   /**
272    * Create a new user. If the new user is created,
273    * the function returns true and the field nUserId
274    * of JUserDetails is filled, else the function
275    * returns false;
276    * The userDetails password field must be filled;
277    */

278
279     URL url;
280     java.lang.String JavaDoc strURL = JComVcConstants.formatNewUserString( userDetails );
281     JIOStream ioStream = new JIOStream();
282     HashMap<String JavaDoc, String JavaDoc> hUserId = new HashMap<String JavaDoc, String JavaDoc>();
283         
284     
285     
286     try {
287       url = new URL( "http", strAdminHost, nAdminPort, strURL );
288       
289       System.err.println( "createNewUser() - URL : " + url.toExternalForm() );
290       
291       // Receives the Create new user OK from Admin Server.
292
if( !ioStream.recv( url.openStream(), hUserId ) ) {
293         System.err.println( "createNewUser() - Server response error : " + hUserId.toString() );
294         
295         if( pluginListener != null )
296           pluginListener.onCreateUserError();
297         
298         return false;
299       }
300       
301       System.err.println( "createNewUser() - Server response : " + hUserId.toString() );
302     
303       // Checks the Ok from server
304
if( !hUserId.containsKey( JComVcConstants.COMVC_REG_SUCCESS ) ) {
305         if( pluginListener != null )
306           pluginListener.onCreateUserError();
307       
308         return false;
309       }
310       
311       userDetails.setUserId( Long.parseLong( hUserId.get( JComVcConstants.COMVC_REG_SUCCESS ).toString() ) );
312
313       System.err.println( "createNewUser() - User Id : " + userDetails.getUserId() );
314
315       if( pluginListener != null )
316         pluginListener.onUserCreated( userDetails.getUserId() );
317     
318       return true;
319       
320     } catch( MalformedURLException e ) {
321       System.err.println( "createNewUser() - " + e );
322       
323       if( pluginListener != null )
324         pluginListener.onCreateUserError();
325       return false;
326     } catch( IOException e ) {
327       System.err.println( "createNewUser() - " + e );
328       
329       if( pluginListener != null )
330         pluginListener.onCreateUserError();
331       return false;
332     } catch( Exception JavaDoc e ) {
333       System.err.println( "createNewUser() - " + e );
334       
335       if( pluginListener != null )
336         pluginListener.onCreateUserError();
337       return false;
338     }
339   }
340   
341   boolean changePassword( java.lang.String JavaDoc strOldPasswd, java.lang.String JavaDoc strNewPasswd ) {
342   /**
343    * Change the user password.
344    * Parameters:
345    * o strOldPasswd - The user old password;
346    * o strNewPasswd - The user new password;
347    */

348
349     URL url;
350     java.lang.String JavaDoc strURL = JComVcConstants.formatChangePasswordString( userDetails, strNewPasswd );
351     JIOStream ioStream = new JIOStream();
352     java.lang.String JavaDoc strServerResponse;
353         
354     
355     
356     try {
357       url = new URL( "http", strAdminHost, nAdminPort, strURL );
358       
359       System.err.println( "changePassword() - URL : " + url.toExternalForm() );
360
361       // Receives the Change Password OK from Admin Server.
362
strServerResponse = ioStream.recv( url.openStream() );
363       
364       if( strServerResponse.indexOf( JComVcConstants.COMVC_SERVER_OK ) < 0 ) {
365         System.err.println( "changePassword() - Server response error : " + strServerResponse );
366
367         if( pluginListener != null )
368           pluginListener.onChangePasswordError( userDetails.getUserId() );
369
370         return false;
371       }
372       
373       System.err.println( "changePassword() - Server response : " + strServerResponse );
374       userDetails.setPassword( strNewPasswd );
375
376       if( pluginListener != null )
377         pluginListener.onPasswordChanged( userDetails.getUserId() );
378     
379       return true;
380       
381     } catch( MalformedURLException e ) {
382       System.err.println( "changePassword() - " + e );
383       
384       if( pluginListener != null )
385         pluginListener.onChangePasswordError( userDetails.getUserId() );
386       
387       return false;
388     } catch( IOException e ) {
389       System.err.println( "changePassword() - " + e );
390       
391       if( pluginListener != null )
392         pluginListener.onChangePasswordError( userDetails.getUserId() );
393
394       return false;
395     } catch( Exception JavaDoc e ) {
396       System.err.println( "changePassword() - " + e );
397       
398       if( pluginListener != null )
399         pluginListener.onChangePasswordError( userDetails.getUserId() );
400
401       return false;
402     }
403   }
404
405   JBuddyDetails getBuddyDetails( long nUserId ) {
406   /**
407    * Returns the specific user details.
408    * Parameters:
409    * o nUserId - The user id to retrieve
410    * details;
411    */

412    
413     URL url;
414     java.lang.String JavaDoc strServerResponse;
415     java.lang.String JavaDoc strURL = JComVcConstants.formatSearchUserString( nUserId );
416     JIOStream ioStream = new JIOStream();
417     
418
419     
420     try {
421       url = new URL( "http", strAdminHost, nAdminPort, strURL );
422       
423       System.err.println( "getBuddyDetails() - URL : " + url.toExternalForm() );
424
425       // Receives the Create new user OK from Admin Server.
426
strServerResponse = ioStream.recv( url.openStream() );
427       System.err.println( "getBuddyDetails() - Server response : " + strServerResponse );
428       
429       // Serach is ok ???
430
if( strServerResponse.indexOf( JComVcConstants.COMVC_SEARCH_ERROR ) != -1 ) {
431         System.err.println( "getBuddyDetails(" + Long.toString( nUserId ) + ") - Error to find user details" );
432         return null;
433       }
434       
435       // Build the JBuddyDetails
436
java.util.ArrayList JavaDoc<String JavaDoc> aBuddyDetails = new java.util.ArrayList JavaDoc<String JavaDoc>();
437       JBuddyDetails buddyDetails = new JBuddyDetails();
438     
439       
440       if( org.planetamessenger.util.JKeyParser.parseKeys( strServerResponse, aBuddyDetails, ',', '\n' ) ) {
441         
442         buddyDetails.setUserId( aBuddyDetails.get( 0 ) );
443         buddyDetails.setUserName( aBuddyDetails.get( 1 ) );
444         buddyDetails.setNickName( aBuddyDetails.get( 2 ) );
445         buddyDetails.setEmail( aBuddyDetails.get( 3 ) );
446         buddyDetails.setLastName( aBuddyDetails.get( 4 ) );
447         
448         return buddyDetails;
449       }
450       else
451         return null;
452       
453     } catch( MalformedURLException e ) {
454       System.err.println( "getBuddyDetails() - " + e );
455       return null;
456     } catch( IOException e ) {
457       System.err.println( "getBuddyDetails() - " + e );
458       return null;
459     } catch( Exception JavaDoc e ) {
460       System.err.println( "getBuddyDetails() - " + e );
461       return null;
462     }
463   }
464   
465   boolean setStatus( int nStatus ) {
466   /**
467      Sets the connection engine status.
468      Parameters:
469       * nStatus - The new client Connection
470         status.
471   */

472     
473     // Checks if is a valid status
474
if( ( nStatus < JComVcConstants.STATUS_OFFLINE ) && ( nStatus > JComVcConstants.STATUS_AWAY ) ) {
475       System.err.println( "JClientEngine.setStatus() - Invalid Status " + nStatus );
476       
477       if( pluginListener != null )
478         pluginListener.onStatusError( nStatus );
479       
480       return false;
481     }
482       
483     if( !bLoggedIn ) {
484       if( pluginListener != null )
485         pluginListener.onStatusError( nStatus );
486       
487       return false;
488     }
489     
490     // Same as logout
491
if( nStatus == JComVcConstants.STATUS_OFFLINE ) {
492       
493       System.err.println( "setStatus() - logout performed" );
494       
495       bLoggedIn = false;
496       keepAliveTimer.stop();
497       peerServerSok.listen( false );
498       peerServerUDP.listen( false );
499
500       updateContactList();
501
502       // Ack tolerance reached, disconnecting
503
if( nAckError == MAX_ACK_FAIL ) {
504         userDetails.setStatus( nStatus );
505         
506         if( pluginListener != null )
507           pluginListener.onStatusChanged( nStatus );
508         
509         return true;
510       }
511     }
512     
513     int nOldStatus = userDetails.getStatus();
514     
515     userDetails.setStatus( nStatus );
516    
517     try {
518       
519       Socket clientSok = connectToHost( CH_BOS_HOST );
520       JIOStream ioStream = new JIOStream();
521       HashMap<String JavaDoc, String JavaDoc> hServerResp = new HashMap<String JavaDoc, String JavaDoc>();
522       String JavaDoc strFmt = JComVcConstants.formatStatusString( userDetails, systemDetails );
523
524
525       if( clientSok == null ) {
526         System.err.println( "setStaus() - Error to connect to BOS Host" );
527         
528         if( pluginListener != null )
529           pluginListener.onStatusError( nStatus );
530         
531         return false;
532       }
533         
534       if( !ioStream.send( clientSok.getOutputStream(), strFmt ) ) {
535         System.err.println( "setStatus() - Client send data error" );
536         userDetails.setStatus( nOldStatus );
537         
538         if( pluginListener != null )
539           pluginListener.onStatusError( nStatus );
540       
541         return false;
542       }
543
544       // Receives the BOS response for status changed ok (STS=200)
545
if( !ioStream.recv( clientSok.getInputStream(), hServerResp ) ) {
546         System.err.println( "setStatus() - Server response error : " + hServerResp.toString() );
547         userDetails.setStatus( nOldStatus );
548         
549         if( pluginListener != null )
550           pluginListener.onStatusError( nStatus );
551       
552         return false;
553       }
554     
555       System.err.println( "setStatus() - Server sent : " + hServerResp.toString() );
556       
557       // Verify if the server responses JComVcConstants.COMVC_SERVER_OK
558
strFmt = ( String JavaDoc ) hServerResp.get( JComVcConstants.COMVC_STATUS_FLAG );
559       
560       if( JComVcConstants.COMVC_SERVER_OK.compareTo( ( strFmt == null ? "" : strFmt ) ) != 0 ) {
561
562         System.err.println( "setStatus() - setStatus error" );
563         userDetails.setStatus( nOldStatus );
564
565         if( pluginListener != null )
566           pluginListener.onStatusError( nStatus );
567
568         return false;
569       }
570       
571       // Send the new status for all ContactList users
572
notifyContactList();
573       
574       System.err.println( "setStatus() - New status changed to " + nStatus );
575       
576       if( pluginListener != null )
577         pluginListener.onStatusChanged( nStatus );
578       
579       clientSok.close();
580       
581       return true;
582       
583     } catch( IOException e ) {
584      
585       System.err.println( "setStatus()" + e );
586       userDetails.setStatus( nOldStatus );
587       
588       if( pluginListener != null )
589         pluginListener.onStatusError( nStatus );
590       
591       return false;
592     } catch( Exception JavaDoc e ) {
593      
594       System.err.println( "setStatus()" + e );
595       userDetails.setStatus( nOldStatus );
596       
597       if( pluginListener != null )
598         pluginListener.onStatusError( nStatus );
599       
600       return false;
601     }
602   }
603   
604   int getStatus() {
605   /**
606      Return the engine conection status.
607   */

608     
609     return userDetails.getStatus();
610   }
611   
612   boolean addToContactList( long nUserId, boolean bRequestAuth ) {
613   /**
614    * Add a user into protocol contact
615    * list.
616    * Parameters:
617    * o nUserId - The UserId that will
618    * be inserted into ContactList;
619    * o bRequestAuth - Request authorization
620    * flag;
621    */

622     
623     Long JavaDoc userId = new Long JavaDoc( nUserId );
624
625   
626     if( !hContactList.containsKey( userId ) ) {
627       JComVcContactItem contactItem = new JComVcContactItem();
628
629       contactItem.nUserId = nUserId;
630             
631       if( bLoggedIn ) {
632         HashMap<Long JavaDoc, JComVcContactItem> hContactItem = new HashMap<Long JavaDoc, JComVcContactItem>();
633         Socket clientSok = connectToHost( CH_BOS_HOST );
634         JIOStream ioStream = new JIOStream();
635         String JavaDoc strFmt;
636              
637        
638         if( clientSok == null ) {
639           System.err.println( "addToContactList() - Error to connect to BOS Host" );
640           return false;
641         }
642         
643         hContactItem.put( userId, contactItem );
644         strFmt = JComVcConstants.formatIPListString( userDetails, systemDetails, hContactItem );
645         
646         System.err.print( "addToContactList() - Client sent : " + strFmt );
647     
648         try {
649           // Send the list request to server
650
if( !ioStream.send( clientSok.getOutputStream(), strFmt ) ) {
651             System.err.println( "addToContactList() - Client send data error" );
652             return false;
653           }
654       
655           // Receives all ContactList IP's from server
656
String JavaDoc strContactList = ioStream.recv( clientSok.getInputStream() );
657           int nPos;
658
659           
660           System.err.println( "addToContactList() - Server sent : " + strContactList );
661       
662           // Verify server OK
663
if( strContactList.indexOf( JComVcConstants.COMVC_SERVER_OK ) < 0 ) {
664             System.err.println( "addToContactList() - Server response error" );
665             return false;
666           }
667       
668           // Clear the protocol specific data and leaves only the ContactList data
669
nPos = strContactList.indexOf( "LIST:\r\n" );
670           strContactList = strContactList.substring( nPos + 7 );
671     
672           /** This code is the last thing to do now !!!!
673           // Adds all contactlist to our memory contactlist
674           if( strContactList.compareTo( "\r\n" ) != 0 ) {
675             contactItem = JComVcContactItem.parseItem( strContactList );
676             sendNotificationToUser( contactItem );
677           }
678           */

679           
680           clientSok.close();
681           ioStream = null;
682           
683           // Request authorization ?
684
if( bRequestAuth ) {
685             ioStream = new JIOStream();
686             clientSok = connectToHost( CH_BOS_HOST );
687           
688             // Send the add user to BOS host
689
strFmt = JComVcConstants.formatAddUserString( userDetails, systemDetails, nUserId );
690
691             System.err.print( "addToContactList() - Client sent : " + strFmt );
692     
693             // Send the authorization request to server
694
if( !ioStream.send( clientSok.getOutputStream(), strFmt ) ) {
695               System.err.println( "addToContactList() - Client send data error" );
696               return false;
697             }
698       
699             // Receives ok from server
700
String JavaDoc strServerResponse = ioStream.recv( clientSok.getInputStream() );
701           
702             System.err.println( "addToContactList() - Server sent : " + strServerResponse );
703             clientSok.close();
704           
705             // Verify server OK
706
if( strServerResponse.indexOf( JComVcConstants.COMVC_SERVER_OK ) < 0 ) {
707               System.err.println( "addToContactList() - Server response error" );
708               return false;
709             }
710           }
711           
712           hContactList.put( userId, contactItem );
713
714           // Adds all contactlist to our memory contactlist
715
if( strContactList.compareTo( "\r\n" ) != 0 ) {
716             contactItem = JComVcContactItem.parseItem( strContactList );
717             sendNotificationToUser( contactItem );
718           }
719           
720           // We'll update the buddy status in our contact list
721
if( pluginListener != null )
722             pluginListener.onBuddyStatusChanged( contactItem.nUserId, contactItem.nUserStatus );
723           
724           return true;
725           
726         } catch( IOException e ) {
727           System.err.println( "addToContactList() - " + e );
728           return false;
729         } catch( Exception JavaDoc e ) {
730           System.err.println( "addToContactList() - " + e );
731           return false;
732         }
733       }
734       else
735         hContactList.put( userId, contactItem );
736     }
737     
738     return false;
739   }
740   
741   boolean removeFromContactList( long nUserId ) {
742   /**
743    * remove a user from protocol contact
744    * list.
745    * Parameters:
746    * o nUserId - The UserId that will
747    * be removed from ContactList;
748    */

749     
750     Long JavaDoc userId = new Long JavaDoc( nUserId );
751
752   
753     if( hContactList.containsKey( userId ) ) {
754       hContactList.remove( userId );
755       return true;
756     }
757     
758     return false;
759   }
760   
761   void clearContactList() {
762   /**
763    * Clear all contact list.
764    */

765     
766     hContactList.clear();
767   }
768
769   boolean authorizeUser( long nUserId ) {
770   /**
771    * Authorize another user to put in contactlist
772    * in your ContactList.
773    * Parameters:
774    * o nUserId - The UserId that authorization
775    * will be sent;
776   */

777     
778     Long JavaDoc userId = new Long JavaDoc( nUserId );
779
780   
781     if( hContactList.containsKey( userId ) ) {
782       
783       if( bLoggedIn ) {
784         Socket clientSok = connectToHost( CH_BOS_HOST );
785         JIOStream ioStream = new JIOStream();
786         String JavaDoc strFmt = JComVcConstants.formatAuthorizeUser( nUserId, userDetails, systemDetails );
787
788         
789         if( clientSok == null ) {
790           System.err.println( "authorizeUser() - Error to connect to BOS Host" );
791           return false;
792         }
793
794         System.err.print( "authorizeUser() - Client sent : " + strFmt );
795     
796         try {
797           // Send the authorization request to server
798
if( !ioStream.send( clientSok.getOutputStream(), strFmt ) ) {
799             System.err.println( "authorizeUser() - Client send data error" );
800             return false;
801           }
802       
803           // Receives ok from server
804
String JavaDoc strServerResponse = ioStream.recv( clientSok.getInputStream() );
805           
806           System.err.println( "authorizeUser() - Server sent : " + strServerResponse );
807           clientSok.close();
808           
809           // Verify server OK
810
if( strServerResponse.indexOf( JComVcConstants.COMVC_SERVER_OK ) < 0 ) {
811             System.err.println( "authorizeUser() - Server response error" );
812             return false;
813           }
814           
815         } catch( IOException e ) {
816           System.err.println( "authorizeUser() - " + e );
817           return false;
818         } catch( Exception JavaDoc e ) {
819           System.err.println( "authorizeUser() - " + e );
820           return false;
821         }
822       }
823       
824       return true;
825     }
826     
827     return false;
828   }
829
830   boolean updateContactList() {
831   /**
832      Retrieve all IP's assigned in
833      the array of strings.
834   */

835     
836     // Verify connection
837
if( !bLoggedIn ) {
838       int nContactListSize = hContactList.values().toArray().length;
839
840
841       for( int nCount = 0; nCount < nContactListSize; nCount++ ) {
842         JComVcContactItem contactItem = ( JComVcContactItem ) hContactList.values().toArray()[nCount];
843     
844         contactItem.nUserStatus = JComVcConstants.STATUS_OFFLINE;
845         
846         if( pluginListener != null )
847           pluginListener.onBuddyStatusChanged( contactItem.nUserId, contactItem.nUserStatus );
848       }
849       
850       return true;
851     }
852     else {
853
854       String JavaDoc strFmt = JComVcConstants.formatIPListString( userDetails, systemDetails, hContactList );
855       Socket clientSok = connectToHost( CH_BOS_HOST );
856       JIOStream ioStream = new JIOStream();
857
858
859       if( clientSok == null ) {
860         System.err.println( "updateContactList() - Error to connect to BOS Host" );
861         return false;
862       }
863
864       System.err.println( "updateContactList() - Client sent : " + strFmt );
865
866       try {
867         // Send the list request to server
868
if( !ioStream.send( clientSok.getOutputStream(), strFmt ) ) {
869           System.err.println( "updateContactList() - Client send data error" );
870           return false;
871         }
872
873         // Receives all ContactList IP's from server
874
String JavaDoc strContactList = ioStream.recv( clientSok.getInputStream() );
875         int nPos;
876         java.util.HashMap JavaDoc<Long JavaDoc, JComVcContactItem> hServerSentList;
877         java.util.Iterator JavaDoc<JComVcContactItem> itItems;
878
879
880         System.err.println( "updateContactList() - Server sent : " + strContactList );
881
882         // Verify server OK
883
if( strContactList.indexOf( JComVcConstants.COMVC_SERVER_OK ) < 0 ) {
884           System.err.println( "updateContactList() - Server response error" );
885
886           return false;
887         }
888
889         // Clear the protocol specific data and retrieve only the ContactList data
890
nPos = strContactList.indexOf( "LIST:\r\n" );
891         strContactList = strContactList.substring( nPos + 7 );
892         hServerSentList = JComVcContactItem.parseList( strContactList );
893         itItems = hContactList.values().iterator();
894
895         // Adds all contactlist to our memory contactlist
896
while( itItems.hasNext() ) {
897
898           JComVcContactItem contactItem = itItems.next();
899           Long JavaDoc userId = new Long JavaDoc( contactItem.nUserId );
900           JComVcContactItem serverSentItem = hServerSentList.get( userId );
901
902
903
904           if( serverSentItem == null ) {
905             contactItem.nUserStatus = JComVcConstants.STATUS_OFFLINE;
906             serverSentItem = contactItem;
907           }
908
909           hContactList.put( userId, serverSentItem );
910
911           if( pluginListener != null )
912             pluginListener.onBuddyStatusChanged( serverSentItem.nUserId, serverSentItem.nUserStatus );
913         }
914
915         /*
916         while( ( contactItem = JComVcContactItem.parseContactList( strContactList ) ) != null ) {
917
918           Long userId = new Long( contactItem.nUserId );
919
920           // Adds server sent ContactList to our ContactList
921           hContactList.put( userId, contactItem );
922
923           // Trigger the onStatus event for each contact list Buddy
924           if( pluginListener != null )
925             pluginListener.onBuddyStatusChanged( Long.toString( contactItem.nUserId ), contactItem.nUserStatus );
926
927           // Cut this ContactItem from ContactList string
928           strContactList = strContactList.substring( strContactList.indexOf( "\r\n" ) + 2 ); // + 2 from \r\n
929           System.err.println( "Contact List " + strContactList );
930         }
931         */

932
933       } catch( IOException e ) {
934         System.err.println( "updateContactList()" + e );
935         return false;
936       } catch( Exception JavaDoc e ) {
937         System.err.println( "updateContactList()" + e );
938         return false;
939       }
940       
941       return true;
942     }
943   }
944
945   synchronized boolean login( int nInitialStatus ) {
946   /**
947      Do the login sequence in the
948      login server.
949      Parameters:
950       * nInitialStatus - Sets the initial
951         status of the user;
952   */

953
954     if( bLoggedIn )
955       return true;
956     
957     if( nInitialStatus == JComVcConstants.STATUS_OFFLINE ) {
958       System.err.println( "login() - Initial status is offline, nothing to do" );
959       return false;
960     }
961     
962     String JavaDoc strFmt;
963     Socket clientSok = connectToHost( CH_LOGIN_HOST );
964     JIOStream ioStream = new JIOStream();
965     HashMap<String JavaDoc, String JavaDoc> hServerParms = new HashMap<String JavaDoc, String JavaDoc>();
966
967
968
969     if( clientSok == null ) {
970       System.err.println( "login() - Server Conection error " + systemDetails.getLoginHost() + " Port : " + Integer.toString( systemDetails.getLoginHostPort() ) );
971       
972       if( pluginListener != null )
973         pluginListener.onLoginError( userDetails.getUserId() );
974
975       return false;
976     }
977     
978     // Creates the peer TCP & UDP Server Socket to send & receive data
979
try {
980       
981       java.net.InetAddress JavaDoc ownerAddress = java.net.InetAddress.getLocalHost();
982       
983       
984       peerServerSok = new JThreadServerSocket( JComVcConstants.COMVC_BEGIN_PORT, JComVcConstants.COMVC_END_PORT );
985       systemDetails.setTCPPort( peerServerSok.getLocalPort() );
986       systemDetails.setIPAddress( ownerAddress.getHostAddress() );
987       peerServerSok.addSocketEventListener( peerSokListener );
988       
989       peerServerUDP = new JThreadServerUDP( JComVcConstants.COMVC_BEGIN_PORT, JComVcConstants.COMVC_END_PORT );
990       systemDetails.setUDPPort( peerServerUDP.getLocalPort() );
991       peerServerUDP.addDatagramEventListener( peerUDPListener );
992
993     } catch( IOException e ) {
994       System.err.println( "JClientEngine.login() - " + e );
995
996       if( pluginListener != null )
997         pluginListener.onLoginError( userDetails.getUserId() );
998
999       return false;
1000    } catch( Exception JavaDoc e ) {
1001      System.err.println( "JClientEngine.login() - " + e );
1002
1003      if( pluginListener != null )
1004        pluginListener.onLoginError( userDetails.getUserId() );
1005
1006      return false;
1007    }
1008    
1009    strFmt = JComVcConstants.formatLoginString( userDetails, systemDetails );
1010    System.err.println( "login() - Client sent : " + strFmt );
1011
1012    try {
1013      if( !ioStream.send( clientSok.getOutputStream(), strFmt ) ) {
1014        System.err.println( "login() - Client send data error" );
1015      
1016        if( pluginListener != null )
1017          pluginListener.onLoginError( userDetails.getUserId() );
1018      
1019        return false;
1020      }
1021
1022      // Receives all BOS parameters from Login server
1023
if( !ioStream.recv( clientSok.getInputStream(), hServerParms ) ) {
1024        System.err.println( "login() - Server response error : " + hServerParms.toString() );
1025      
1026        if( pluginListener != null )
1027          pluginListener.onLoginError( userDetails.getUserId() );
1028      
1029        return false;
1030      }
1031
1032      System.err.println( "login() - Server sent : " + hServerParms.toString() );
1033
1034      // Verify if the server responses JComVcConstants.COMVC_SERVER_OK
1035
if( !JComVcConstants.COMVC_SERVER_OK.equals( hServerParms.get( JComVcConstants.COMVC_INIT_FLAG ) ) ) {
1036
1037        System.err.println( "login() - Login error" );
1038      
1039        if( pluginListener != null )
1040          pluginListener.onLoginError( userDetails.getUserId() );
1041      
1042        return false;
1043      }
1044      
1045      // Sets all System Details parameters.
1046
systemDetails.setBOSAddress( hServerParms.get( JComVcConstants.COMVC_IP_KEY ).toString() );
1047      systemDetails.setBOSPort( Integer.parseInt( hServerParms.get( JComVcConstants.COMVC_PORT_KEY ).toString() ) );
1048      systemDetails.setTicket( Long.parseLong( hServerParms.get( JComVcConstants.COMVC_TICKET_KEY ).toString() ) );
1049      systemDetails.setCrypt( Byte.parseByte( hServerParms.get( JComVcConstants.COMVC_CRYPT_KEY ).toString() ) );
1050    
1051      // Closes the Server Login connection
1052
clientSok.close();
1053    
1054      System.err.println( "login() - Login Accepted" );
1055
1056      // Changing initial status & Updating the user contact list
1057
System.err.println( "login() - changing initial status" );
1058      
1059      bLoggedIn = true;
1060      
1061      if( setStatus( nInitialStatus ) ) {
1062        
1063        System.err.println( "login() - Retrieving the user contact list status" );
1064        if( updateContactList() ) {
1065          nAckError = 0;
1066          peerServerSok.listen( true );
1067          peerServerUDP.listen( true );
1068          keepAliveTimer.start();
1069
1070          if( pluginListener != null )
1071            pluginListener.onLoginAccepted( userDetails.getUserId() );
1072          
1073          return true;
1074        }
1075        else {
1076          System.err.println( "login() - User contact list error. Logging off" );
1077
1078          bLoggedIn = false;
1079          peerServerSok.close();
1080          peerServerUDP.close();
1081        
1082          if( pluginListener != null )
1083            pluginListener.onLoginError( userDetails.getUserId() );
1084        }
1085        
1086        return false;
1087      }
1088      else {
1089        System.err.println( "login() - changing initial status error. Logging off" );
1090        
1091        bLoggedIn = false;
1092        peerServerSok.close();
1093        peerServerUDP.close();
1094        
1095        if( pluginListener != null )
1096          pluginListener.onLoginError( userDetails.getUserId() );
1097      }
1098
1099      return false;
1100      
1101    } catch( IOException e ) {
1102      System.err.println( "login() - " + e );
1103      
1104      if( pluginListener != null )
1105        pluginListener.onLoginError( userDetails.getUserId() );
1106      
1107      return false;
1108    } catch( Exception JavaDoc e ) {
1109      System.err.println( "login() - " + e );
1110      
1111      if( pluginListener != null )
1112        pluginListener.onLoginError( userDetails.getUserId() );
1113      
1114      return false;
1115    }
1116  }
1117  
1118  synchronized boolean logout() {
1119  /**
1120    *
1121    * Performs the logout in ComVC Server.
1122    */

1123  
1124    System.err.println( "logout() - logout performed" );
1125
1126    if( bLoggedIn ) {
1127      setStatus( JComVcConstants.STATUS_OFFLINE );
1128      return true;
1129    }
1130
1131    return false;
1132  }
1133  
1134  boolean sendMessage( long nUserId, java.lang.String JavaDoc strMsg ) {
1135  /**
1136    * Send a message to a Buddy from
1137    * ContactList.
1138    * Parameters:
1139    * o nUserId - The UserId that
1140    * the message will be sent;
1141    * o strMsg - Message to be sent;
1142    */

1143    
1144    if( !bLoggedIn )
1145      return false;
1146    
1147    String JavaDoc strFmt;
1148    Long JavaDoc lUserId = new Long JavaDoc( nUserId );
1149    JComVcContactItem contactItem;
1150    Socket clientSok;
1151    JIOStream ioStream;
1152    boolean bDirectMsg = true;
1153        
1154    
1155    if( hContactList.containsKey( lUserId ) ) {
1156      ioStream = new JIOStream();
1157      contactItem = ( JComVcContactItem ) hContactList.get( lUserId );
1158      clientSok = connectToHost( contactItem );
1159      
1160      if( clientSok == null ) {
1161        System.err.println( "sendMessage() - Error to create direct connection. Sending through server." );
1162        
1163        //clientSok = connectToHost( CH_BOS_SERVICES );
1164
clientSok = connectToHost( CH_BOS_HOST );
1165        
1166        if( clientSok == null ) {
1167          
1168          System.err.println( "sendMessage() - Through server message error." );
1169          
1170          if( pluginListener != null )
1171            pluginListener.onMessageError( nUserId );
1172          
1173          return false;
1174        }
1175        else
1176          bDirectMsg = false;
1177      }
1178      
1179      strFmt = JComVcConstants.formatMessageString( userDetails, systemDetails, nUserId, strMsg, bDirectMsg );
1180      
1181      try {
1182        // Send the message
1183
if( !ioStream.send( clientSok.getOutputStream(), strFmt ) ) {
1184          System.err.println( "sendMessage() - Client send data error" );
1185          clientSok.close();
1186          
1187          if( pluginListener != null )
1188            pluginListener.onMessageError( nUserId );
1189          
1190          return false;
1191        }
1192        
1193        System.err.println( "sendMessage() - Client sent " + strFmt );
1194 
1195        // Receives ok from Server
1196
java.lang.String JavaDoc strServerOk;
1197        
1198        if( bDirectMsg )
1199          strServerOk = JComVcConstants.formatSuccessString( JComVcConstants.COMVC_MESSAGE_FLAG );
1200        else
1201          strServerOk = JComVcConstants.formatSuccessString( JComVcConstants.COMVC_MSG_OFF_FLAG );
1202        
1203        java.lang.String JavaDoc strServerResponse = ioStream.recv( clientSok.getInputStream(), strServerOk.length() );
1204        
1205        System.err.println( "sendMessage() - Server sent : " + strServerResponse );
1206
1207        // Verify if the client responses JComVcConstants.COMVC_SERVER_OK
1208
if( strServerOk.compareTo( strServerResponse ) != 0 ) {
1209          System.err.println( "sendMessage() - Message error" );
1210          clientSok.close();
1211          
1212          if( pluginListener != null )
1213            pluginListener.onMessageError( nUserId );
1214          
1215          return false;
1216        }
1217        else {
1218          System.err.println( "sendMessage(" + nUserId + ") - Message successfull sent" );
1219        }
1220
1221        clientSok.close();
1222
1223      } catch( IOException e ) {
1224        System.err.println( "sendMessage()" + e );
1225      } catch( Exception JavaDoc e ) {
1226        System.err.println( "sendMessage()" + e );
1227      }
1228      
1229      if( pluginListener != null )
1230        pluginListener.onMessageSent( nUserId );
1231      
1232      return true;
1233    }
1234    
1235    return false;
1236  }
1237  
1238  public void actionPerformed( java.awt.event.ActionEvent JavaDoc evt ) {
1239  /**
1240   * Handle the actionPerformed timer event.
1241   * Parameters:
1242   * o sender - The timer that sent this
1243   * event.
1244   */

1245
1246    System.err.println( "JClientEngine.actionPerformed() - Timer event reached" );
1247
1248    if( bLoggedIn ) {
1249      Socket clientSok = connectToHost( CH_BOS_HOST );
1250      JIOStream ioStream = new JIOStream();
1251      String JavaDoc strFmt = JComVcConstants.formatAckString( userDetails, systemDetails );
1252    
1253
1254      
1255      if( clientSok == null ) {
1256        System.err.println( "JClientEngine.actionPerformed() - Unable to connect to BOS host : " + systemDetails.getBOSAddress() );
1257        processAckTolerance();
1258        return;
1259      }
1260      else
1261        System.err.println( "JClientEngine.actionPerformed() - Connected on BOS Host : " + systemDetails.getBOSAddress() );
1262    
1263      try {
1264        if( !ioStream.send( clientSok.getOutputStream(), strFmt ) ) {
1265          System.err.println( "JClientEngine.actionPerformed() - Client send data error" );
1266          processAckTolerance();
1267          return;
1268        }
1269      
1270        System.err.println( "JClientEngine.actionPerformed() - Client sent " + strFmt );
1271
1272        // Receives all BOS keep alive parameters from BOS host
1273
strFmt = ioStream.recv( clientSok.getInputStream() );
1274
1275        System.err.println( "JClientEngine.actionPerformed() - Server sent : " + strFmt );
1276
1277        if( strFmt.indexOf( ( JComVcConstants.COMVC_ACK_FLAG + " " + JComVcConstants.COMVC_SERVER_OK ) ) >= 0 ) {
1278
1279          int nPos;
1280          java.util.ArrayList JavaDoc<String JavaDoc> aAckList = new java.util.ArrayList JavaDoc<String JavaDoc>();
1281
1282
1283          System.err.println( "JClientEngine.actionPerformed() - Ack successfull received" );
1284          
1285          // Parse the server Ack message
1286
if( ( nPos = strFmt.indexOf( "\r\n" ) ) >= 0 ) {
1287            
1288            strFmt = strFmt.substring( nPos + 2 );
1289            
1290            if( org.planetamessenger.util.JKeyParser.parseKeys( strFmt, aAckList, '\n', '\t' ) ) {
1291
1292              for( int nCount = 0; nCount < aAckList.size(); nCount++ ) {
1293                
1294                // Verify for Contact List Authorization request (requests from original ComVC)
1295
if( aAckList.get( nCount ).toString().indexOf( JComVcConstants.COMVC_GETAUT_KEY ) >= 0 ) {
1296                  
1297                  String JavaDoc strUserId;
1298                  String JavaDoc strNickName;
1299                  
1300                  
1301                  strUserId = aAckList.get( ++nCount ).toString();
1302                  nPos = strUserId.indexOf( "|" );
1303
1304                  if( nPos < 0 )
1305                    break;
1306                
1307                  strNickName = strUserId.substring( nPos, strUserId.indexOf( '\r' ) );
1308                  strUserId = strUserId.substring( 0, nPos );
1309
1310                  System.err.println( "JClientEngine.actionPerformed() - Processing authorization request from user [" + strUserId + "] - " + strNickName.substring( 1 ) );
1311                
1312                  if( pluginListener != null )
1313                    pluginListener.onBuddyRequestAuthorization( Long.parseLong( strUserId ), strNickName.substring( 1 ) );
1314                }
1315                
1316                // Verify for contact list updates
1317
if( aAckList.get( nCount ).toString().indexOf( JComVcConstants.COMVC_LIST_KEY ) >= 0 ) {
1318
1319                  String JavaDoc strContactItem = aAckList.get( ++nCount ).toString();
1320                  JComVcContactItem serverItem;
1321                  JComVcContactItem localItem;
1322
1323                  try {
1324                    strContactItem = strContactItem.substring( 0, strContactItem.indexOf( '\r' ) ) + "|200006\r\n";
1325                    serverItem = JComVcContactItem.parseItem( strContactItem );
1326                    localItem = ( JComVcContactItem ) hContactList.get( new Long JavaDoc( serverItem.nUserId ) );
1327
1328                    // Update local item list
1329
localItem.strIPAddress = serverItem.strIPAddress;
1330                    localItem.nTicket = serverItem.nTicket;
1331                    localItem.nTCPPort = serverItem.nTCPPort;
1332                    localItem.nUDPPort = serverItem.nUDPPort;
1333                    localItem.nClientVersion = serverItem.nClientVersion;
1334                    localItem.nUserStatus = ( ( serverItem.nUserStatus == JComVcConstants.STATUS_BUDDY_INVISIBLE ) ? JComVcConstants.STATUS_INVISIBLE : serverItem.nUserStatus );
1335
1336                    System.err.println( "JClientEngine.actionPerformed() - Processing update user status [" + localItem.nUserId + "]" );
1337
1338                    if( pluginListener != null )
1339                      pluginListener.onBuddyStatusChanged( localItem.nUserId, localItem.nUserStatus );
1340                  }
1341                  catch( java.lang.NumberFormatException JavaDoc nfe ) {
1342                  }
1343                }
1344                
1345                // Verify if server sent offline messages
1346
if( aAckList.get( nCount ).toString().indexOf( JComVcConstants.COMVC_MSGOFF_KEY ) >= 0 ) {
1347                  
1348                  java.util.HashMap JavaDoc<String JavaDoc, String JavaDoc> hMsgOffParms = new java.util.HashMap JavaDoc<String JavaDoc, String JavaDoc>();
1349                  String JavaDoc strUserId = aAckList.get( ++nCount ).toString();
1350                  String JavaDoc strDate = aAckList.get( ++nCount ).toString();
1351                  String JavaDoc strTime = aAckList.get( ++nCount ).toString();
1352                  String JavaDoc strIcon = aAckList.get( ++nCount ).toString();
1353                  String JavaDoc strFormat = aAckList.get( ++nCount ).toString();
1354                  String JavaDoc strMsg = aAckList.get( ++nCount ).toString();
1355
1356                  
1357                  System.err.println( "JClientEngine.actionPerformed() - Processing offline message" );
1358                  
1359                  strUserId = strUserId.substring( strUserId.indexOf( '=' ) + 1, strUserId.indexOf( '\r' ) );
1360                  strDate = strDate.substring( strDate.indexOf( '=' ) + 1, strDate.indexOf( '\r' ) );
1361                  strTime = strTime.substring( strTime.indexOf( '=' ) + 1, strTime.indexOf( '\r' ) );
1362                  strFormat = strFormat.substring( strFormat.indexOf( '=' ) + 1, strFormat.indexOf( '\r' ) );
1363                  strMsg = strMsg.substring( strMsg.indexOf( '=' ) + 1, strMsg.indexOf( '\r' ) );
1364                  
1365                  hMsgOffParms.put( JComVcConstants.COMVC_MSGOFF_KEY, "" );
1366                  hMsgOffParms.put( JComVcConstants.COMVC_USERID_KEY, strUserId );
1367                  hMsgOffParms.put( JComVcConstants.COMVC_DATE_KEY, strDate );
1368                  hMsgOffParms.put( JComVcConstants.COMVC_TIME_KEY, strTime );
1369                  hMsgOffParms.put( JComVcConstants.COMVC_FORMAT_KEY, strFormat );
1370                  hMsgOffParms.put( JComVcConstants.COMVC_MESSAGE_FLAG, strMsg );
1371                  
1372                  JComVcSocketEvents.dispatchMessage( hMsgOffParms, pluginListener );
1373                  nCount+=2;
1374                }
1375              }
1376            }
1377          }
1378        }
1379        else { // Check ack tolerance
1380
processAckTolerance();
1381        }
1382      
1383        clientSok.close();
1384        
1385      } catch( IOException e ) {
1386        System.err.println( "JClientEngine.actionPerformed() - " + e );
1387        processAckTolerance();
1388      } catch( Exception JavaDoc e ) {
1389        System.err.println( "JClientEngine.actionPerformed() - " + e );
1390        processAckTolerance();
1391      }
1392    }
1393  }
1394}
1395
1396// JClientEngine class
1397
Popular Tags