Sample IM message handling application



The application described here consists of two CFCs: an employee phone directory lookup CFC that responds to an onIncomingMessage event, and a Gateway management CFC that responds to all other events. This example shows how an application can respond to events and send outgoing messages.

You can configure a gateway to use both CFCs by entering the paths to the two CFCs, separated by a comma, in the CFC Path field of the Add/Edit ColdFusion Event Gateways form on the Gateway Instances page in the ColdFusion Administrator.

Phone directory lookup CFC

The following CFC implements a simple employee phone directory lookup application. The user sends an instant message containing some part of the name to looked up (a space requests all names). The onIncomingMessage response depends on the number matches.

  • If there is no match, the onIncomingMessage function returns a message indicating that there are no matches.

  • If there is one match, the function returns the name, department, and phone number.

  • If there are up to ten matches, the function returns a list of the names preceded by a number that the user can enter to get the detailed information.

  • If there are over ten matches, the function returns a list of only the first ten names. A more complex application can let the user get multiple lists of messages to provide access to all names.

  • If the user enters a number, and previously got a multiple-match list, the application returns the information for the name that corresponds to the number.

The following listing shows the CFC code:

<cfcomponent> 
    <cffunction name="onIncomingMessage"> 
        <cfargument name="CFEvent" type="struct" required="YES"> 
        <!--- Remove any extra white space from the message. ---> 
        <cfset message =Trim(arguments.CFEvent.data.MESSAGE)> 
        <!--- If the message is numeric, a previous search probably returned a 
            list of names. Get the name to search for from the name list stored in 
            the Session scope. ---> 
        <cfif isNumeric(message)> 
            <cfscript> 
                if (structKeyExists(session.users, val(message))) { 
                    message = session.users[val(message)]; 
                }             
            </cfscript> 
        </cfif> 
 
        <!--- Search the database for the requested name. ---> 
        <cfquery name="employees" datasource="cfdocexamples"> 
            select FirstName, LastName, Department, Phone 
            from Employees 
            where 0 = 0 
            <!--- A space indicates the user entered a first and last name. ---> 
            <cfif listlen(message, " ") eq 2> 
                and FirstName like '#listFirst(message, " ")#%' 
                and LastName like '#listlast(message, " ")#%' 
            <!--- No space: the user entered a first or a last name. ---> 
            <cfelse> 
                and (FirstName like '#listFirst(message, " ")#%'  
                or LastName like '#listFirst(message, " ")#%') 
            </cfif> 
        </cfquery> 
 
        <!--- Generate andreturn the message.---> 
        <cfscript> 
            retrunVal = structNew(); 
            retrunVal.command = "submit"; 
            retrunVal.buddyID = arguments.CFEvent.data.SENDER; 
             
            //No records were found.  
            if (employees.recordCount eq 0) { 
                retrunVal.message = "No records found for '#message#'"; 
            } 
            //One record was found. 
            else if (employees.recordCount eq 1) { 
            // Whitespace in the message text results in bad formatting, 
            // so the source cannot be indented. 
                retrunVal.message = "Requested information: 
#employees.firstName# #employees.lastName# 
#employees.Department# 
#employees.Phone#"; 
            } 
            //Multiple possibilities were found. 
            else if (employees.recordCount gt 1) { 
                //If more than ten were found, return only the first ten. 
                if (employees.recordCount gt 10) 
                { 
                    retrunVal.message = "First 10 of #employees.recordCount# records"; 
                }else{ 
                    retrunVal.message = "Records found: #employees.recordCount#"; 
                } 
                // The session.users structure contains the found names. 
                // The record key is a number that is also returned in front of the  
                // name in the message. 
                session.users = structNew(); 
                for(i=1; i lte min(10, employees.recordCount); i=i+1) 
                { 
                    // These two lines are formatted to prevent extra white space. 
                    retrunVal.message = retrunVal.message & " 
#i# - #employees.firstName[i]# #employees.lastName[i]#"; 
                    // The following two lines must be a single line in the source 
                    session.users[i]="#employees.firstName[i]# 
                        #employees.lastName[i]#"; 
                } 
            } 
            return retrunVal; 
        </cfscript> 
    </cffunction> 
</cfcomponent>

Status and request-handling CFC

The following CFC handles all IM events, except onIncomingMessage. It maintains an Application scope buddyStatus structure that contains information on the gateway buddies. This structure limits the interactions that are needed with the IM server to get buddy and status information. The application also logs significant events, such as requests to add buddies and error messages from the IM server. In particular, it does the following:

  • The onBuddyStatus function updates the Application scope buddy status structure when the gateway gets an event message indicating that a buddy’s status has changed.

  • The onAddBuddyRequest function searches for the requested buddy’s name in a data source. If it finds a single instance of the name, it adds the buddy and updates the status in the Application scope buddyStatus structure. If it doesn’t find name, it declines the buddy request. If it finds multiple instances of the name, it tells the gateway to take no action. It also logs all actions.

  • The onAddBuddyResponse function adds the buddy to the Application scope buddy status structure if the buddy request is accepted, and sets the current status. It logs all responses.

  • The onIMServerMessage function logs all messages that it receives.

    This example uses the IM_ID column of the Employees database of the cfdocexamples database that is included with ColdFusion. The entries in this column assume that you use an XMPP server “company.” To run this exampleconfigure an XMPP server with this name and with clients with names in this database, or change the database entries to match IM server clients. Also, configure a gateway instance in the ColdFusion Administrator that uses this server.

The following listing shows the CFC code:

<cfcomponent> 
 
<cffunction name="onBuddyStatus"> 
    <cfargument name="CFEvent" type="struct" required="YES"> 
    <cflock scope="APPLICATION" timeout="10" type="EXCLUSIVE"> 
        <cfscript> 
        // Create the status structures if they don't exist. 
            if (NOT StructKeyExists(Application, "buddyStatus")) { 
                Application.buddyStatus=StructNew(); 
            } 
            if (NOT StructKeyExists(Application.buddyStatus, CFEvent.Data.BUDDYNAME)) { 
                Application.buddyStatus[#CFEvent.Data.BUDDYNAME#]=StructNew(); 
            } 
            // Save the buddy status and timestamp. 
            Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].status=CFEvent.Data.BUDDYSTATUS; 
            Application.buddyStatus[#CFEvent.Data.BUDDYNAME#].timeStamp=CFEvent.Data.TIMESTAMP; 
        </cfscript> 
    </cflock> 
</cffunction> 
     
<cffunction name="onAddBuddyRequest"> 
    <cfargument name="CFEvent" type="struct" required="YES"> 
    <cfquery name="buddysearch" datasource="cfdocexamples"> 
        select IM_ID 
        from Employees 
        where IM_ID = '#CFEvent.Data.SENDER#' 
    </cfquery> 
    <cflock scope="APPLICATION" timeout="10" type="EXCLUSIVE"> 
        <cfscript> 
            // If the name is in the DB once, accept; if it is missing, decline. 
            // If it is in the DB multiple times, take no action. 
            if (buddysearch.RecordCount IS 0) { 
                action="decline"; 
                reason="Invalid ID"; 
            } 
            else if (buddysearch.RecordCount IS 1) { 
                action="accept"; 
                reason="Valid ID"; 
                //Add the buddy to the buddy status structure only if accepted. 
                if (NOT StructKeyExists(Application, 
                        "buddyStatus")) { 
                    Application.buddyStatus=StructNew(); 
                } 
                if (NOT StructKeyExists(Application.buddyStatus, 
                        CFEvent.Data.SENDER)) { 
                    Application.buddyStatus[#CFEvent.Data.SENDER#]=StructNew(); 
                } 
                Application.buddyStatus[#CFEvent.Data.SENDER#].status= 
                    "Accepted Buddy Request"; 
                Application.buddyStatus[#CFEvent.Data.SENDER#].timeStamp= 
                    CFEvent.Data.TIMESTAMP; 
                Application.buddyStatus[#CFEvent.Data.SENDER#].message= 
                    CFEvent.Data.MESSAGE; 
            } 
            else { 
                action="noact"; 
                reason="Duplicate ID"; 
            } 
        </cfscript> 
    </cflock> 
    <!--- Log the request and decision information. ---> 
    <cflog file="#CFEvent.GatewayID#Status"  
            text="onAddBuddyRequest; SENDER: #CFEvent.Data.SENDER# MESSAGE: #CFEvent.Data.MESSAGE# TIMESTAMP: #CFEvent.Data.TIMESTAMP# ACTION: #action#"> 
    <!--- Return the action decision. ---> 
    <cfset retValue = structNew()> 
    <cfset retValue.command = action> 
    <cfset retValue.BuddyID = CFEvent.DATA.SENDER> 
    <cfset retValue.Reason = reason> 
    <cfreturn retValue>  
</cffunction> 
 
     
<cffunction name="onAddBuddyResponse"> 
    <cfargument name="CFEvent" type="struct" required="YES"> 
    <cflock scope="APPLICATION" timeout="10" type="EXCLUSIVE"> 
        <cfscript> 
            //Do the following only if the buddy accepted the request. 
            if (NOT StructKeyExists(Application, "buddyStatus")) { 
                Application.buddyStatus=StructNew(); 
                } 
            if (#CFEVENT.Data.MESSAGE# IS "accept") { 
                //Create a new entry in the buddyStatus record for the buddy. 
                if (NOT StructKeyExists(Application.buddyStatus, 
                        CFEvent.Data.SENDER)) { 
                    Application.buddyStatus[#CFEvent.Data.SENDER#]=StructNew(); 
                } 
                //Set the buddy status information to indicate buddy was added. 
                Application.buddyStatus[#CFEvent.Data.SENDER#].status= 
                    "Buddy accepted us"; 
                Application.buddyStatus[#CFEvent.Data.SENDER#].timeStamp= 
                    CFEvent.Data.TIMESTAMP; 
                Application.buddyStatus[#CFEvent.Data.SENDER#].message= 
                    CFEvent.Data.MESSAGE; 
            } 
        </cfscript> 
    </cflock> 
    <!--- Log the information for all responses. ---> 
    <cflog file="#CFEvent.GatewayID#Status"  
        text="onAddBuddyResponse; BUDDY: #CFEvent.Data.SENDER# RESPONSE: #CFEvent.Data.MESSAGE# TIMESTAMP: #CFEvent.Data.TIMESTAMP#"> 
</cffunction> 
 
     
<cffunction name="onIMServerMessage"> 
    <!--- This function just logs the message. ---> 
    <cfargument name="CFEvent" type="struct" required="YES"> 
    <cflog file="#CFEvent.GatewayID#Status"  
        text="onIMServerMEssage; SENDER: #CFEvent.OriginatorID# MESSAGE: #CFEvent.Data.MESSAGE# TIMESTAMP: #CFEvent.Data.TIMESTAMP#"> 
</cffunction>     
</cfcomponent>