ymsg.network
Class Session

Object
  extended bySession
All Implemented Interfaces:
ServiceConstants, StatusConstants

public class Session
extends Object
implements StatusConstants, ServiceConstants

Encapsulates one instant message session, using YMSG. When writing a client, this is the entry point into the API, allowing access to YMSG features and generating events based upon incoming network activity.

This document uses various terms

Term Meaning
UserA single unique Yahoo user
FriendA user who is in your Yahoo friends list
GroupOne sub-division of your Yahoo friends list
ContactA Yahoo user (not necessarily a friend) who has contacted you
PacketA single Yahoo network message
YMSGYahoo Instant Messager protocol

The connection handling and general housekeeping methods are:

The Yahoo status methods are used to change the way your client is repesented to the rest of the YMSG world - normally they are used to indicate whether you are busy, out of the office, etc. The status methods are: The users/groups list methods are used to alter the list of 'friend' users and their associated groups (the folders they occupy in the on-screen tree). Users are represented by either an id (text string) or a YahooUser object. The latter are canonical, meaning that only one object is ever created for each user. If you hold a reference to a YahooUser object, the values inside it will be updated as the status of the user changes. The friends/groups/users methods are: Conferences are ad-hoc private chatrooms, with users invited to join by a host. The conference methods are: Chatrooms are themed instant messager forums, where like-minded users can meet and chat. The chatroom methods are: Here's an example of some very basic sample code, connecting to the server and sending a single message, before disconnecting:
	try
	{   // Create a session, try fallback ports if default fails
	    Session ss = new Session();
	    // Register for session events
	    ss.addSessionListener(new MySessionHandler());
	    // Optionally, set status to login as invisible
	    ss.setStatus(StatusConstants.STATUS_INVISIBLE);
	    // Login (obviously you'd use your real username/password)
	    ss.login("username","password");
	    // Did we successfully log in?
	    if(ss.getSessionStatus()==MESSAGING)
	    {   // We might want to save the port somewhere for next login attempt
	        System.out.println("Success on port: "+session.getPort());
	        // Send a message to myFriend, wait for 5 seconds, then logout
	        ss.sendMessage("myFriend","Borag Thung, Earthlet");
	        try { Thread.sleep(5*1000); } catch(InterruptedException e) {}
	        ss.logout();
	    }
	    else
	    {   // Failed to log in - reset so we can re-use the same object
	        ss.reset();
	    }
	}catch(Exception e) { ss.reset(); }
	
To modify the status there are a couple of overloaded methods. Here's some examples of how to use them:
	// Change to on phone and change to invisible
	ss.setStatus(StatusConstants.STATUS_ONPHONE);
	ss.setStatus(StatusConstants.STATUS_INVISIBLE);
	

// Change to custom away message, and custom back (available) message // (the API automatically sets the status to custom for us) ss.setStatus("I'm otta'here!",true); ss.setStatus("Ready and waiting!!",false);

To print the group and friends list, we might do something like this:
	YahooGroup[] yg = ss.getGroups();
	for(int i=0;i<yg.length;i++)
	{   System.out.println(yg[i].getName());
	    for(int j=0;j<yg[i].size();j++)
	    {   YahooUser yu = yg[i].getUserAt(j);
	        System.out.println("  "+yu.toString());
	    }
	}
	
Upon receiving a message we might do something like this (note: see SessionListener for messageReceived details) :
	public void messageReceived(SessionEvent ev)
	{   String from=ev.getFrom() , msg=ev.getMessage();
	    Hashtable h = ss.getUsers();
	    YahooUser yu = (YahooUser)h.get(from);
	    if(yu==null)
	    {   System.out.println("<Not a friend> "+from+": "+msg);
	    }
	    else
	    {   if(yu.isIgnored())  return;
	            else  System.out.println(yu.getId()+": "+msg);
	    }
	}
	
Before we log into a chatroom we need to select one from the list of room lobbies available at Yahoo. Rooms are organised into a hierarchy of categories, each category holding zero or more categories and/or zero or more public rooms and/or zero or more private rooms. Each room holds one or more lobby.
	// Load first lobby of first room of first category
	YahooChatCategory root = YahooChatCategory.loadCategories();
	YahooChatCategory ycc = (YahooChatCategory)root.getCategories().elementAt(0);
	YahooChatRoom ycr = (YahooChatRoom)ycc.getPublicRooms().elementAt(0);
	YahooChatLobby ycl = (YahooChatLobby)ycr.getLobbies().elementAt(0);
	
Having selected a lobby, connecting and using a room is easy.
	// Connect to a lobby, send a message, then logout
	ss.chatLogin(ycl);
	ss.sendChatMessage("Hello world!");
	ss.chatLogout();
	
Messages from the room arrive as part of methods in the SessionListener interface. chatLogonReceived and chatLogoffReceived inform us of members arriving and leaving, while chatMessageReceived details a new chat message.

Identities are Yahoo's way of allowing users to have multiple aliases, and this package supports them via the YahooIdentity object. An array of these objects is created during the login process, accessible via the getIdentities method. The objects in this array can then be passed to various overloaded methods, and the resulting network messages will be 'badged' with that identity.

	YahooIdentity[] ids = ss.getIdentities();
	ss.sendMessage("lois","This looks like a job for...",ids[0]);
	ss.sendMessage("lois","Superman!",ids[1]);
	
In the above example the user lois will be sent a message from two apparently different users. Little does she suspect that they are the same person. (In reality you should not 'hard code' identity objects by index like this, as objects may be re-ordered each time the data is refreshed.)

Since:
1.0

Field Summary
 
Fields inherited from interface StatusConstants
AUTH, CONNECT, FAILED, LOGON, MESSAGING, NOTIFY_GAME, NOTIFY_TYPING, STATUS_AVAILABLE, STATUS_AVAILABLE_STR, STATUS_BAD, STATUS_BADUSERNAME, STATUS_BRB, STATUS_BRB_STR, STATUS_BUSY, STATUS_BUSY_STR, STATUS_COMPLETE, STATUS_CUSTOM, STATUS_CUSTOM_STR, STATUS_IDLE, STATUS_IDLE_STR, STATUS_INCOMPLETE, STATUS_INVISIBLE, STATUS_INVISIBLE_STR, STATUS_LOCKED, STATUS_NOTATDESK, STATUS_NOTATDESK_STR, STATUS_NOTATHOME, STATUS_NOTATHOME_STR, STATUS_NOTINOFFICE, STATUS_NOTINOFFICE_STR, STATUS_OFFLINE, STATUS_ONPHONE, STATUS_ONPHONE_STR, STATUS_ONVACATION, STATUS_ONVACATION_STR, STATUS_OUTTOLUNCH, STATUS_OUTTOLUNCH_STR, STATUS_STEPPEDOUT, STATUS_STEPPEDOUT_STR, STATUS_TYPING, UNSTARTED
 
Fields inherited from interface ServiceConstants
SERVICE_ADDIDENT, SERVICE_ADDIGNORE, SERVICE_AUTH, SERVICE_AUTHRESP, SERVICE_CALENDAR, SERVICE_CHATCONNECT, SERVICE_CHATDISCONNECT, SERVICE_CHATGOTO, SERVICE_CHATINVITE, SERVICE_CHATLEAVE, SERVICE_CHATLOGOFF, SERVICE_CHATLOGON, SERVICE_CHATMSG, SERVICE_CHATPING, SERVICE_CHATPM, SERVICE_CONFADDINVITE, SERVICE_CONFDECLINE, SERVICE_CONFINVITE, SERVICE_CONFLOGOFF, SERVICE_CONFLOGON, SERVICE_CONFMSG, SERVICE_CONTACTIGNORE, SERVICE_CONTACTNEW, SERVICE_CONTACTREJECT, SERVICE_FILETRANSFER, SERVICE_FRIENDADD, SERVICE_FRIENDREMOVE, SERVICE_GAMELOGOFF, SERVICE_GAMELOGON, SERVICE_GAMEMSG, SERVICE_GROUPRENAME, SERVICE_IDACT, SERVICE_IDDEACT, SERVICE_IDLE, SERVICE_ISAWAY, SERVICE_ISBACK, SERVICE_LIST, SERVICE_LOGOFF, SERVICE_LOGON, SERVICE_MAILSTAT, SERVICE_MESSAGE, SERVICE_NEWMAIL, SERVICE_NEWPERSONMAIL, SERVICE_NOTIFY, SERVICE_P2PFILEXFER, SERVICE_PASSTHROUGH2, SERVICE_PEERTOPEER, SERVICE_PING, SERVICE_SYSMESSAGE, SERVICE_USERSTAT, SERVICE_VOICECHAT, SERVICE_X_BUZZ, SERVICE_X_CHATUPDATE, SERVICE_X_ERROR, SERVICE_X_EXCEPTION, SERVICE_X_OFFLINE
 
Constructor Summary
Session()
          Creates a single Yahoo session using the best guess connection handler.
Session(ConnectionHandler ch)
          Creates a single Yahoo session, using the prescribed connection handler.
 
Method Summary
 void acceptConferenceInvite(YahooConference room)
          Accepts a conference invite from another user.
 void activateIdentity(YahooIdentity yid, boolean activate)
          Activates or deactivates a Yahoo identity.
 void addFriend(String friend, String group)
          Add a user to a group.
 void addSessionListener(SessionListener ss)
          Adds a listener object to receive events from the session.
 void addTypingNotification(String user, Component com)
          Sets the AWT component being used for typing notification.
 void chatLogin(YahooChatLobby ycl)
          Requests a chat login, blocking until the login process is over.
 void chatLogin(YahooChatLobby ycl, YahooIdentity yid)
          Requests a chat login, using a specific identity, blocking until the login process is over.
 void chatLogout()
          Requests to be logged out of a chat room.
 YahooConference createConference(String[] users, String msg)
          Creates a new conference.
 YahooConference createConference(String[] users, String msg, YahooIdentity yid)
          Creates a new conference, using a specific identity.
 void declineConferenceInvite(YahooConference room, String msg)
          Decline a conference invite from another user.
 void extendConference(YahooConference room, String user, String msg)
          Invites a user to an existing conference.
 int getChatSessionStatus()
          Returns the status of the chat connection.
 ConnectionHandler getConnectionHandler()
          Returns the currently employed connection handler.
 String[] getCookies()
          Returns the three cookies Yahoo sends the client upon successful login.
 YahooChatLobby getCurrentChatLobby()
          Returns the current chatroom lobby, or null if not logged into a chatroom.
 String getCustomStatusMessage()
          Returns the custom status message.
 YahooGroup[] getGroups()
          Gets a copy of the array of groups containing Yahoo friends.
 YahooIdentity[] getIdentities()
          Returns a list of valid identities for this Yahoo account.
 String getImvironment()
          Returns the Imvironment string passed to the client during login.
 YahooIdentity getLoginIdentity()
          Returns the login identity for this Yahoo account.
 YahooIdentity getPrimaryIdentity()
          Returns the true identity for this Yahoo account.
 int getSessionStatus()
          Gets the status of the connection.
 long getStatus()
          Returns the actual status of the Yahoo user.
 YahooUser getUser(String id)
          Returns the object for the given Yahoo id string.
 Hashtable getUsers()
          Returns a hashtable of all users known by this session.
 void ignoreContact(String friend, boolean ignore)
          Change the ignore status of a Yahoo user.
 boolean isCustomBusy()
          Returns the custom status busy flag.
 void keyTyped(String user)
          Manually update key notification.
 void leaveConference(YahooConference room)
          Leaves a conference.
 void login(String u, String p)
          Requests the session be logged in.
 void logout()
          Requests the session be logged out (disconnected).
 void refreshFriends()
          Sends a request for the friends/groups data to be updated.
 void refreshStats()
          Requests a refresh of status and new mail count from server.
 void rejectContact(String friend, String msg)
          Reject an offer to be added to a friends list.
 void removeFriend(String friend, String group)
          Remove a friend from a group.
 void removeSessionListener(SessionListener ss)
          Removes a listener object to receive events from the session.
 void removeTypingNotification(String user)
          Clears the AWT component being used for typing notification.
 void reset()
          Resets a spent session so the object can be re-used.
 void resetChat()
          Resets a failed chat login.
 void saveFileTransferAs(SessionFileTransferEvent ev, String filename)
          Saves an incoming file transfer to the specified filename.
 void saveFileTransferTo(SessionFileTransferEvent ev, String dir)
          Saves an incoming file transfer to the specified directory.
 void sendBuzz(String to)
          Sends a buzz message.
 void sendBuzz(String to, YahooIdentity yid)
          Sends a buzz message, using a specific identity.
 void sendChatEmote(String emote)
          Send a message to the current chatroom lobby, marked as an emote.
 void sendChatMessage(String msg)
          Send a message to the current chatroom lobby.
 void sendConferenceMessage(YahooConference room, String msg)
          Sends a message to users in a conference.
 void sendFileTransfer(String user, String filename, String msg)
          Send a binary file to the specified Yahoo user.
 void sendMessage(String to, String msg)
          Sends a message.
 void sendMessage(String to, String msg, YahooIdentity yid)
          Sends a message, using a specific identity.
 void setStatus(long s)
          Sets the status of the Yahoo user.
 void setStatus(String m, boolean b)
          Sets the status of the Yahoo user using custom status.
 
Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Session

public Session()
Creates a single Yahoo session using the best guess connection handler. If the system property socksProxyHost is set, a SOCKSConnectionHandler is installed; otherwise if http.proxyHost or proxyHost are set, a HTTPConnectionHandler is installed; otherwise a DirectConnectionHandler is installed. (In all three cases the default (no args) constructor of the connection handler is called.)

Since:
1.0

Session

public Session(ConnectionHandler ch)
Creates a single Yahoo session, using the prescribed connection handler.

Parameters:
ch - connection handler
Since:
1.0
Method Detail

addSessionListener

public void addSessionListener(SessionListener ss)
Adds a listener object to receive events from the session. This should be done ASAP after creating a new session, and before login is called, as without it any application using this API will be effectively deaf (but not mute).

Multiple listeners may be added for a single session, but duplicates are ignored. The order in which each listener is served a given event is not guaranteed - do not assume the event handlers will be called in the same order that the listeners were registered.

Parameters:
ss - the event listener to add
Since:
1.0
See Also:
removeSessionListener(SessionListener ss)

removeSessionListener

public void removeSessionListener(SessionListener ss)
Removes a listener object to receive events from the session. Has no effect if listener not already registered.

Parameters:
ss - the event listener to remove
Since:
1.0
See Also:
addSessionListener(SessionListener ss)

getConnectionHandler

public ConnectionHandler getConnectionHandler()
Returns the currently employed connection handler.

Returns:
current connection handler
Since:
1.0

login

public void login(String u,
                  String p)
           throws IllegalStateException,
                  IOException,
                  AccountLockedException,
                  LoginRefusedException
Requests the session be logged in. It is advised that a SessionListener be registered with the session before this method is called. After calling this method (which will block until logon is complete) getSessionStatus should be checked to see if the login attempt was successful. Unsuccessful Session objects must be reset before being re-used.

Yahoo doesn't really have a good line in error conditions. We either logged in or we failed, although the overwhelming source of errors (barring poor network connections) will come from bad usernames and/or passwords. This method throws two exceptions which are subclasses of YahooException - the first is AccountLockedException and the second is LoginRefusedException. Both indicate a failure to log into the Yahoo service. The first typically carries a URL of a Web page to display when the account is locked - usually the generic Yahoo login page.

Usernames are converted to lower case, as Yahoo's usernames are case insensitive.

The property ymsg.network.loginTimeout can be used to specify a timeout, in seconds, after which the method will throw an IOException. A value of zero or below disables the timeout facility.

Parameters:
u - Yahoo username of the account to be connected to
p - password of said Yahoo account
Throws:
IllegalStateException - if already logged in
IOException - if i/o problems from underlying streams or timeout
AccountLockedxception - if Yahoo is blocking the account
LoginRefusedException - if the username/password is refused
AccountLockedException
Since:
1.0
See Also:
logout(), getSessionStatus(), reset()

logout

public void logout()
            throws IllegalStateException,
                   IOException
Requests the session be logged out (disconnected). This will terminate the current Yahoo session. A session object can be re-used after logout.

Throws:
IllegalStateException - if not logged in
IOException - if i/o problems from underlying streams
Since:
1.0
See Also:
login(String u,String p)

reset

public void reset()
           throws IllegalStateException
Resets a spent session so the object can be re-used. (Hey - let's be kind to the garbage collector! :-) Should be used after an unsuccessful login.

Throws:
IllegalStateException - if still logged in.
Since:
1.0
See Also:
login(String u,String p), logout()

sendMessage

public void sendMessage(String to,
                        String msg)
                 throws IllegalStateException,
                        IOException
Sends a message.

Parameters:
to - Yahoo id of person to send message to
msg - Text of message (ASCII or UTF-8 please!)
Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
Since:
1.0

sendMessage

public void sendMessage(String to,
                        String msg,
                        YahooIdentity yid)
                 throws IllegalStateException,
                        IOException,
                        IllegalIdentityException
Sends a message, using a specific identity.

Parameters:
to - Yahoo id of person to send message to
msg - Text of message (ASCII or UTF-8 please!)
yid - Yahoo id (alias) to send the message as
Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
IllegalIdentityException - if the user does not 'own' the supplied identity
Since:
1.0

sendBuzz

public void sendBuzz(String to)
              throws IllegalStateException,
                     IOException
Sends a buzz message. The standard Yahoo client deals with this type of message by displaying a BUZZ message and vibrating the messaging window for a second or so.

Parameters:
to - Yahoo id of person to send buzz to
Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
Since:
1.0

sendBuzz

public void sendBuzz(String to,
                     YahooIdentity yid)
              throws IllegalStateException,
                     IOException,
                     IllegalIdentityException
Sends a buzz message, using a specific identity. The standard Yahoo client deals with this type of message by displaying a BUZZ message and vibrating the messaging window for a second or so.

Parameters:
to - Yahoo id of person to send buzz to
yid - Yahoo id (alias) to send the message as
Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
IllegalIdentityException - if the user does not 'own' the supplied identity
Since:
1.0

getSessionStatus

public int getSessionStatus()
Gets the status of the connection. This will be either UNSTARTED when idle and ready to go, AUTH when currently engaged in trying to log in, MESSAGING when successfully connected or FAILED when a login was unsuccessful.

Note: DO NOT confuse this with the status of the Yahoo user themself. The session status documents the state of the network connection to the Yahoo service. The Yahoo status (see getStatus and setStatus) documents the state of the Yahoo user to the 'outside world' (ie: available, busy, not in the office, etc).

Returns:
session status code
Since:
1.0
See Also:
StatusConstants

getStatus

public long getStatus()
Returns the actual status of the Yahoo user. For example available, busy, invisible etc. See the constants in the StatusConstants interface.

Returns:
unsigned 32 bit Yahoo status
Since:
1.0
See Also:
setStatus(long s)

setStatus

public void setStatus(long s)
               throws IllegalArgumentException,
                      IOException
Sets the status of the Yahoo user. See the constants in the StatusConstants interface. Note: status can only be set initially to available or invisible, prior to logging in.

Parameters:
s - status integer, preferably from StatusConstants
Throws:
IllegalArgumentException - if the status is set to something other than available or invisible and the session is unstarted.
IOException - if i/o problems from underlying streams
Since:
1.0
See Also:
getStatus(), setStatus(String m,boolean b)

setStatus

public void setStatus(String m,
                      boolean b)
               throws IllegalArgumentException,
                      IOException
Sets the status of the Yahoo user using custom status. This method attempts to set the Yahoo status to the message and flag provided.

Parameters:
m - custom message text
b - busy (true) or available (false) flag - busy changes the user's smiley face icon to feature a no-entry sign
Throws:
IllegalArgumentException - if the session is unstarted (only available or invisible allowed) or the message is null.
IOException - if i/o problems from underlying streams
Since:
1.0
See Also:
getStatus(), setStatus(long s)

getCustomStatusMessage

public String getCustomStatusMessage()
Returns the custom status message. When the current status is not set to custom, this method returns null.

Returns:
custom status text
Since:
1.0
See Also:
isCustomBusy()

isCustomBusy

public boolean isCustomBusy()
Returns the custom status busy flag. True implies the custom status will be shown as busy (with a no entry logo over the smiley).

Returns:
custom status flag
Since:
1.0
See Also:
getCustomStatusMessage()

refreshStats

public void refreshStats()
                  throws IllegalStateException,
                         IOException
Requests a refresh of status and new mail count from server. The server may respond by sending back status and new mail messages shortly after.

Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
Since:
1.0

getIdentities

public YahooIdentity[] getIdentities()
Returns a list of valid identities for this Yahoo account. These may be used to send messages under different aliases in those methods which support an optional YahooIdentity parameter.

Do not rely on the order of these identities in the array. To find an identity object with a given username, search the array, do not assume it will always be at the same index.

Returns:
an array of valid YahooIdentity objects, or null if not logged in
Since:
1.0

getPrimaryIdentity

public YahooIdentity getPrimaryIdentity()
Returns the true identity for this Yahoo account. This is the identity which was originally used to create the accoun (?) and to which all other identities are merely aliases.

Returns:
the YahooIdentity object of the true identity, or null if not logged in
Since:
1.0

getLoginIdentity

public YahooIdentity getLoginIdentity()
Returns the login identity for this Yahoo account. This is the default identity, which was used to log into the account for this session.

Returns:
the YahooIdentity object of the login identity, or null if not logged in
Since:
1.0

activateIdentity

public void activateIdentity(YahooIdentity yid,
                             boolean activate)
                      throws IllegalStateException,
                             IllegalIdentityException,
                             IOException
Activates or deactivates a Yahoo identity. An activated identity will appear to be logged in. A deactivated identity will appear to be off-line.

The primary identity cannot be deactivated. Attempting to call this method with the primary identity, either for activation or deactivation, will result in an IllegalIdentityException.

Parameters:
yid - Yahoo id (alias) to de/activate
activate - true to activate, false to deactivate
Throws:
IllegalStateException - if not connected to Yahoo
IllegalIdentityException - if the user does not 'own' the supplied identity or the primary identity is used
IOException - if i/o problems from underlying streams
Since:
1.0

addTypingNotification

public void addTypingNotification(String user,
                                  Component com)
Sets the AWT component being used for typing notification.

Yahoo sends out notification packets whenever it knows you are typing a message to someone (yes - it sounds like a waste of network bandwidth to me too... but never the less, this is what it does!). These messages can be automatically generated if you provide an AWT component for the jYMSG API to monitor. A listener will be registered with the target component to monitor key presses, and notification packets automatically sent at intervals.

Only one notification handler can be set for each target user. Attempts to add a second, without first removing the current one, will be ignored.

For clients which do not use AWT or Swing, the notification system now supports a manual scheme for sending typing events. To use the manual scheme, call this method with a null component parameter, then use keyTyped to inform the session of each key press.

Note: DO NOT use this feature for conferences, only regular one to one style messages.

Parameters:
user - Yahoo id to send notifications to
com - AWT component to monitor for key presses, or null
Since:
1.0
See Also:
removeTypingNotification(String user), keyTyped(String user)

removeTypingNotification

public void removeTypingNotification(String user)
Clears the AWT component being used for typing notification.

Yahoo sends out notification packets when it knows you are typing to someone. The jYMSG API can generate these automatically. This method clears the current AWT component being monitored. Specifically, it attempts to unregister it's key event listener. It has no effect if an event source has not already been set.

Parameters:
user - Yahoo id to stop notifcations for
Since:
1.0
See Also:
addTypingNotification(String user,Component com)

keyTyped

public void keyTyped(String user)
Manually update key notification. This method is designed to be used in clients which wish to employ key notification, but do not use AWT or Swing components. addTypingNotfication can be called with a null component, then this method used to manually inform the notification thread of each key press. The notification thread will dispatch notify packets, as necessary.

Note: this method can also be used to send 'fake' key presses to notifiers which are registered with an AWT/Swing component - although there is no legitimate reason to do this.

Parameters:
user - Yahoo id to 'fake' a key notifcation for
Since:
1.0
See Also:
addTypingNotification(String user,Component com)

getGroups

public YahooGroup[] getGroups()
Gets a copy of the array of groups containing Yahoo friends. Each group is a vector containing zero or more YahooUser objects. Each friend is represented by a specific object unique to that user id. if a friend appears more than once, either within a single group or in more than one group, then the same YahooUser object will be referenced.

This method will return null if the session is not connected.

Note: this method returns a clone of the array, not the original, which makes it more expensive than simply returning a reference - avoid calling this method repeately inside a tight loop.

Returns:
an array of group objects, or null if not connected
Since:
1.0
See Also:
getUsers()

getUsers

public Hashtable getUsers()
Returns a hashtable of all users known by this session. The hash has their Yahoo id string as its key, and holds YahooUser objects for every user that this session has come into contact with, either via the friends group listing, or because they were in a chat room the session visited.

There is no ability to maintain the details or status of Yahoo users which the session is no longer in contact with. If we leave a chatroom, although the member's objects will remain, they will not necessarily get updated (unless the session is also connected with that user via another path - such as if they are in a friends group).

Returns:
hashtable of users
Since:
1.0

getUser

public YahooUser getUser(String id)
Returns the object for the given Yahoo id string. The method does not contact the Yahoo service, and cannot be used to query random Yahoo users 'at large'.

Looking up users is handy when a message comes in and we quickly need to check if the sender is ignored, a friend, or something similar. Use the accessor methods on the returned YahooUser object to determine a user's status.

This method will return null if the Yahoo id is unknown. Unknown users are those who have not already come to the session's attention (via the friends list, for example).

Take note of the issues with maintaining accurate status details, as mentioned in the getUsers method above.

Parameters:
id - string id of Yahoo user
Returns:
a yahoo user object, or null
Since:
1.0

getImvironment

public String getImvironment()
Returns the Imvironment string passed to the client during login. (Note: this method may be replaced if this API ever provides fuller support for IMvironments.)

Returns:
IMvironment string
Since:
1.0

getCookies

public String[] getCookies()
Returns the three cookies Yahoo sends the client upon successful login. The cookies are in the following indexes (from 0 to 2) : Y, T then C.

Returns:
Cookie array
Since:
1.0

createConference

public YahooConference createConference(String[] users,
                                        String msg)
                                 throws IllegalStateException,
                                        IOException
Creates a new conference. The specified users (Yahoo id's) are contacted with an invite to join, containing the supplied message.

This method returns a conference name string, which is used to identify this specific conference when using other conference methods.

Do not put the current user, or any of their identities, into the users list. For logistics, jYMSG maintains a sharp distinction between conferences created by the user, and those the user was invited to. Inviting yourself to your own conference will confuse matters. (At some point this restiction may be lifted.)

Parameters:
users - array of Yahoo id's to invite
msg - invite message / topic
Returns:
conference object
Throws:
IllegalStateException - if not connected to Yahoo
IllegalIdentityException - if the 'users' array contains the current user
IOException
Since:
1.0
See Also:
extendConference(YahooConference room,String user,String msg)

createConference

public YahooConference createConference(String[] users,
                                        String msg,
                                        YahooIdentity yid)
                                 throws IllegalStateException,
                                        IOException,
                                        IllegalIdentityException
Creates a new conference, using a specific identity. The specified users (Yahoo id's) are contacted with an invite to join, containing the supplied message.

The identity used to create the conference is stored as part of the YahooConference object, with all subsequent calls using said conference object automatically using this identity.

This method returns a conference name string, which is used to identify this specific conference when using other conference methods.

Do not put the current user, or any of their identities, into the users list. For logistics, jYMSG maintains a sharp distinction between conferences created by the user, and those the user was invited to. Inviting yourself to your own conference will confuse matters. (At some point this restiction may be lifted.)

Parameters:
users - array of Yahoo id's to invite
msg - invite message / topic
Returns:
conference object
Throws:
IllegalStateException - if not connected to Yahoo
IllegalIdentityException - if the user does not 'own' the supplied identity
IllegalIdentityException - if the 'users' array contains the current user
IOException
Since:
1.0
See Also:
extendConference(YahooConference room,String user,String msg)

acceptConferenceInvite

public void acceptConferenceInvite(YahooConference room)
                            throws NoSuchConferenceException,
                                   IOException,
                                   IllegalStateException
Accepts a conference invite from another user. Typically this method would be called in response to the SessionListener method conferenceInviteReceived. The room parameter can be found by using getRoom in SessionConferenceEvent.

Parameters:
room - conference object
Throws:
IllegalStateException - if not connected to Yahoo
NoSuchConferenceException - if no such conference exists (this should never happen, unless called outside an invite event!)
IOException - if i/o problems from underlying streams
Since:
1.0

declineConferenceInvite

public void declineConferenceInvite(YahooConference room,
                                    String msg)
                             throws NoSuchConferenceException,
                                    IOException,
                                    IllegalStateException
Decline a conference invite from another user. Typically this method would be called in response to the SessionListener method conferenceInviteReceived. The room parameter can be found by using getRoom in SessionConferenceEvent.

Parameters:
room - conference object
msg - rejection message
Throws:
IllegalStateException - if not connected to Yahoo
NoSuchConferenceException - if no such conference exists (this should never happen, unless called outside an invite event!)
IOException - if i/o problems from underlying streams
Since:
1.0

extendConference

public void extendConference(YahooConference room,
                             String user,
                             String msg)
                      throws NoSuchConferenceException,
                             IOException,
                             IllegalStateException
Invites a user to an existing conference. The specified user (Yahoo id's) is contacted with an invite to join, containing the supplied message.

See createConference for notes on the restriction on identities of the current user.

Parameters:
room - conference object
user - Yahoo id of user to invite
msg - invite message / topic
Throws:
IllegalStateException - if not connected to Yahoo
NoSuchConferenceException - if no such conference exists
IOException - if i/o problems from underlying streams
IllegalIdentityException - if 'user' is the current user
Since:
1.0
See Also:
createConference(String[] users,String msg)

sendConferenceMessage

public void sendConferenceMessage(YahooConference room,
                                  String msg)
                           throws NoSuchConferenceException,
                                  IOException,
                                  IllegalStateException
Sends a message to users in a conference.

Parameters:
room - conference object
msg - message text
Throws:
IllegalStateException - if not connected to Yahoo
NoSuchConferenceException - if no such conference exists
IOException - if i/o problems from underlying streams
Since:
1.0

leaveConference

public void leaveConference(YahooConference room)
                     throws NoSuchConferenceException,
                            IOException,
                            IllegalStateException
Leaves a conference.

Parameters:
room - conference object
Throws:
IllegalStateException - if not connected to Yahoo
NoSuchConferenceException - if no such conference exists
IOException - if i/o problems from underlying streams
Since:
1.0

addFriend

public void addFriend(String friend,
                      String group)
               throws IllegalStateException
Add a user to a group. If the group does not exist in the current list, it will automatically be created.

Note: A request packet will be sent to the specified user (if they are offline if will be held for them and delivered at the earliest available time) giving them a chance to reject your addition, causing their Yahoo id to be removed from your friends list. The event method contactRejectionReceived will be called when confirmation of a refusal is received (please remember, this may be some time, even days, after we added the user).

Parameters:
friend - Yahoo id of friend to add
group - group name
Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
Since:
1.0

removeFriend

public void removeFriend(String friend,
                         String group)
                  throws IllegalStateException
Remove a friend from a group. If the group becomes empty it will automatically be deleted.

Parameters:
friend - Yahoo id of friend to remove
group - group name
Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
Since:
1.0

rejectContact

public void rejectContact(String friend,
                          String msg)
                   throws IllegalStateException
Reject an offer to be added to a friends list. Typically this method will be called in response to the SessionListener method contactRequestReceived. The getFrom method of SessionEvent will reveal the id of the user who is trying to add us to their list.

Note: the way Yahoo works with regard to friends lists is unusual. It is the responsibility of the target to reject unwanted attempts to add them to other user's lists. If the target does nothing, the attempt is successful (indeed, the intended way to allow yourself to be added to someone else's list is to just ignore their request - without a refusal the addition stands!)

Parameters:
friend - Yahoo id of contact wishing to add us to their list
msg - rejection message
Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
Since:
1.0

ignoreContact

public void ignoreContact(String friend,
                          boolean ignore)
                   throws IllegalStateException
Change the ignore status of a Yahoo user.

Parameters:
friend - Yahoo id of contact to change
ignore - True to ignore, false to unignore
Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
Since:
1.0

refreshFriends

public void refreshFriends()
Sends a request for the friends/groups data to be updated. Typically this would be called if the user selected a 'Refresh' option on the client user interface (perhaps a menu item?) to force a manual refresh of the friends data.

Note: this method merely sends a request to Yahoo for a refresh of the data. The SessionListener should be used to determine when (or if!) this data has arrived, via its friendsUpdateReceived method.

Throws:
IllegalStateException - if not connected to Yahoo
IOException - if i/o problems from underlying streams
Since:
1.0

sendFileTransfer

public void sendFileTransfer(String user,
                             String filename,
                             String msg)
                      throws IllegalStateException,
                             FileTransferFailedException,
                             IOException
Send a binary file to the specified Yahoo user. This method employs server upload - this API currently does not support direct Peer-to-Peer file transfer.

There is a system properties which alters the target of a connection. ymsg.network.fileTransferHost can be used to set the host to which the connection will be made. In reality is it highly unlikely that this property should need to be changed from its default: filetransfer.msg.yahoo.com.

Parameters:
user - the Yahoo user to send the file to
filename - the full filename and path of the file to send
msg - an accompanying message text
Throws:
IllegalStateException - if not connected to Yahoo
FailedFileTransferException - if the upload fails or is rejected
IOException - if i/o problems from underlying streams
FileTransferFailedException
Since:
1.0

saveFileTransferAs

public void saveFileTransferAs(SessionFileTransferEvent ev,
                               String filename)
                        throws FileTransferFailedException,
                               IOException
Saves an incoming file transfer to the specified filename.

Parameters:
ev - The event object associated with this file transfer
filename - The full filename and path of the file to save the incoming data to
Throws:
FailedFileTransferException - if the download fails
IOException - if i/o problems from underlying streams
FileTransferFailedException
Since:
1.0

saveFileTransferTo

public void saveFileTransferTo(SessionFileTransferEvent ev,
                               String dir)
                        throws FileTransferFailedException,
                               IOException
Saves an incoming file transfer to the specified directory. The filename will be obtained from the URL, however if the HTTP headers for the download request feature a Content-Disposition: header with a filename, this will be used in preference.

Parameters:
ev - The event object associated with this file transfer
dir - The full path of the directory to save the file to
Throws:
FailedFileTransferException - if the download fails
IOException - if i/o problems from underlying streams
FileTransferFailedException
Since:
1.0

chatLogin

public void chatLogin(YahooChatLobby ycl)
               throws IllegalStateException,
                      IOException,
                      LoginRefusedException
Requests a chat login, blocking until the login process is over. Connecting to chat is a two stage process, there is a round of hankshaking which needs to be performed before the login request itself can be sent. This method encapsulates both steps. Note that this process, coupled with a possible large volume of user data which may be downloaded for a busy room, means that this method may block for several seconds.

To check the outcome, use getChatSessionStatus. As with the session login itself, an unsuccessful chat login must be reset by using resetChatStatus before a second login can be attempted.

The property ymsg.network.loginTimeout can be used to specify a timeout, in seconds, after which the method will throw an IOException. A value of zero or below disables the timeout facility.

Yahoo only permits a session to be logged into one lobby at a time. Joining a second lobby will result in being removed from the first. (Don't blame me - blame Yahoo!)

Parameters:
ycl - the chat lobby to join
Throws:
IllegalStateException - if already logged into a lobby
IOException - if i/o problems from underlying streams
LoginRefusedException - if the room is inaccessible/full
Since:
1.0

chatLogin

public void chatLogin(YahooChatLobby ycl,
                      YahooIdentity yid)
               throws IllegalStateException,
                      IOException,
                      LoginRefusedException,
                      IllegalIdentityException
Requests a chat login, using a specific identity, blocking until the login process is over. Connecting to chat is a two stage process, there is a round of hankshaking which needs to be performed before the login request itself can be sent. This method encapsulates both steps. Note that this process, coupled with a possible large volume of user data which may be downloaded for a busy room, means that this method may block for several seconds.

To check the outcome, use getChatSessionStatus. As with the session login itself, an unsuccessful chat login must be reset by using resetChatStatus before a second login can be attempted.

The property ymsg.network.loginTimeout can be used to specify a timeout, in seconds, after which the method will throw an IOException. A value of zero or below disables the timeout facility.

Yahoo only permits a session to be logged into one lobby at a time. Joining a second lobby will result in being removed from the first. (Don't blame me - blame Yahoo!)

Parameters:
ycl - the chat lobby to join
Throws:
IllegalStateException - if already logged into a lobby
IOException - if i/o problems from underlying streams
IllegalIdentityException - if the user does not 'own' the supplied identity
LoginRefusedException - if the room is inaccessible/full
Since:
1.0

chatLogout

public void chatLogout()
                throws IllegalStateException,
                       IOException
Requests to be logged out of a chat room. Having left, a session can log into another (or the same) lobby by simply using chatLogin again.

Throws:
IllegalStateException - if not logged into a lobby
IOException - if i/o problems from underlying streams
Since:
1.0

sendChatMessage

public void sendChatMessage(String msg)
                     throws IllegalStateException,
                            IOException
Send a message to the current chatroom lobby.

Note: Yahoo does not echo the message back to the sending client, so to maintain a correct transcript on the client GUI, a well-behaved application should parrot the message to the chat display as well as transmitting it.

Parameters:
msg - Text of message (ASCII or UTF-8 please!)
Throws:
IllegalStateException - if not logged into a lobby
IOException - if i/o problems from underlying streams
Since:
1.0

sendChatEmote

public void sendChatEmote(String emote)
                   throws IllegalStateException,
                          IOException
Send a message to the current chatroom lobby, marked as an emote.

Note 1: Yahoo does not echo the message back to the sending client, so to maintain a correct transcript on the client GUI, a well-behaved application should parrot the message to the chat display as well as transmitting it.

Note 2: The ymsg.support package has an EmoteManager class which can be used to handle arrays of Emote strings.

Parameters:
emote - Text of message (ASCII or UTF-8 please!)
Throws:
IllegalStateException - if not logged into a lobby
IOException - if i/o problems from underlying streams
Since:
1.0

getCurrentChatLobby

public YahooChatLobby getCurrentChatLobby()
Returns the current chatroom lobby, or null if not logged into a chatroom.

Returns:
a YahooChatLobby, of null
Since:
1.0

getChatSessionStatus

public int getChatSessionStatus()
Returns the status of the chat connection. This can be UNSTARTED when idle, CONNECT during the handshaking stage of connecting to a room, LOGON when in the second stage, MESSAGING when successfully connected or FAILED when a login was unsuccessful.

Returns:
chat session status code
Since:
1.0

resetChat

public void resetChat()
               throws IllegalStateException
Resets a failed chat login.

Throws:
IllegalStateException - if still logged in.
Since:
1.0