A POP3 Custom Gateway


You've read about the architecture and classes that make up the event gateway, so let's go ahead and walk through making our own custom gateway. In this example, you're going to make a simple gateway that connects to a POP3 server and, if there are new emails on the POP server for a specific account defined in a configuration file, the gateway will send an event to a listener CFC with the number of new emails.

To work through this example, you'll need to have the J2EE.jar, to make use of the javax.mail classes, and the cfusion.jar in your classpath. If you are using ANT you can modify the build.xml file that can usally be found at cf_root\gateway\src\ and use that. . When you do compile the example, you'll want to compile the code and then deploy it as POP3Gateway.jar along with the J2EE.jar. Now let's look at Listing 31.4.

Listing 31.4. POP3Gateway.javaChecks for new e-mail and creates a event

[View full width]

 import coldfusion.eventgateway.CFEvent; import coldfusion.eventgateway.Gateway; import coldfusion.eventgateway.GatewayServices; import coldfusion.server.ServiceRuntimeException; import coldfusion.eventgateway.Logger; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class POP3Gateway implements Gateway {     private GatewayServices gatewayService = null;     private String gatewayID = "";     private String[] listeners = null;     private String config = null;     private Thread listenerThread = null;     private boolean shutdown = false;     private int status = STOPPED;     private String hostname = null;         private String username = null;         private String password = null;     private long pollingInterval = 60000;     private long listenerThreadWait = 10000;         private Logger logger = null;     public POP3Gateway(String gatewayID, String config)     {         this.gatewayID = gatewayID;         this.config = config;         this.gatewayService = GatewayServices.getGatewayServices();             this.logger = gatewayService.getLogger("pop3");             this.loadPropertiesFromFile();             this.logger.info("POP3Gateway(" + gatewayID + "," + config + ").constructor:  complete");     }     public String outgoingMessage(coldfusion.eventgateway.CFEvent cfmsg)         {             return "We have no outgoing messages from this gateway.";         }         public void setCFCListeners(String[] listeners)     {         this.listeners = listeners;     }     public coldfusion.eventgateway.GatewayHelper getHelper()     {         return null;     }     public void setGatewayID(String id)     {         gatewayID = id;     }     public String getGatewayID()     {         return gatewayID;     }     public void start()     {             this.logger.info("POP3Gateway.start():enter");         this.status = STARTING;         // Start up listener thread         Runnable r = new Runnable()         {             public void run()             {                 pollForNewMessages();             }         };         this.listenerThread = new Thread(r);         this.shutdown = false;         this.listenerThread.start();         this.status = RUNNING;             this.logger.info("POP3Gateway.start():exit");     }     public void stop()     {             this.logger.info("POP3Gateway.stop():enter");         this.status = STOPPING;         this.shutdown = true;         try         {             listenerThread.interrupt();             listenerThread.join(this.listenerThreadWait);         }         catch (InterruptedException e)         {             // ignore         }         this.status = STOPPED;             this.logger.info("POP3Gateway.stop():exit");     }         public void restart()     {         stop();         loadPropertiesFromFile();         start();     }     public int getStatus()     {         return status;     }     private void loadPropertiesFromFile() throws ServiceRuntimeException     {             this.logger.info("POP3Gateway.loadPropertiesFromFile():enter");         Properties properties = new Properties();         try         {             FileInputStream propsFile = new FileInputStream(config);             properties.load(propsFile);             propsFile.close();         }         catch (IOException e)         {             String error = "POP3Gateway (" + gatewayID + ") Unable to load             configuration file";             throw new ServiceRuntimeException(error, e);         }         this.hostname = properties.getProperty("hostname");             this.username = properties.getProperty("username");             this.password = properties.getProperty("password");             this.logger.info("POP3Gateway.loadPropertiesFromFile():exit");     }     private void pollForNewMessages()     {             this.logger.info("POP3Gateway.pollForNewMessages():enter");         int lastMessageCount = 0;             Store store = null;             Folder folder = null;             try             {                     Properties properties = new Properties();                     Session session = Session.getDefaultInstance(properties, null);                     store = session.getStore("pop3");                     store.connect(hostname, username, password);             }             catch (javax.mail.MessagingException e)                 {                             throw new ServiceRuntimeException(e.getMessage());                 }                 while (!shutdown)                 {                     this.logger.info("POP3Gateway.pollForNewMessages():testing for                     mail");                     int newMessageCount = 0;                     try                     {                             folder = store.getFolder("INBOX");                             folder.open(Folder.READ_ONLY);                             newMessageCount = folder.getMessageCount();                             folder.close(false);                     }                         catch (javax.mail.MessagingException e)                     {                             throw new ServiceRuntimeException(e.getMessage());                     }                             this.logger.info("POP3Gateway.pollForNewMessages():new                             message count=" + newMessageCount);                     if (lastMessageCount != newMessageCount)                 {                             this.logger.info("POP3Gateway.pollForNewMessages():                             lastMessageCount==" + lastMessageCount + ";                             newMessageCount==" + newMessageCount);                             this.sendMessageCountToCF(newMessageCount-                             lastMessageCount);                     }                     lastMessageCount = newMessageCount;                     try                     {                             Thread.sleep(this.pollingInterval);                     }                         catch (InterruptedException e)                     {                         //   ignore                     }             }                 try                 {                     folder.close(false);                 }                 catch (Exception e)                 {}                 this.logger.info("POP3Gateway.pollForNewMessages():exit");         }     private void sendMessageCountToCF(int newMessageCount)     {             this.logger.info("POP3Gateway.sendMessageCountToCF(" + newMessageCount +             "):enter");         CFEvent cfEvent = new CFEvent(gatewayID);         cfEvent.setCfcMethod("newMailCount");         Hashtable returnedData = new Hashtable();         returnedData.put("NEWMAILCOUNT", Integer.toString(newMessageCount));         cfEvent.setData(returnedData);         cfEvent.setGatewayType("POP3Gateway");         cfEvent.setOriginatorID("POP3Gateway");         // Send to each listener         for (int i = 0; i < listeners.length; i++)         {             // Set CFC path             cfEvent.setCfcPath(listeners[i]);         // send it to the event service             gatewayService.addEvent(cfEvent);         }             this.logger.info("POP3Gateway.sendMessageCountToCF(" + newMessageCount +             "):exit");     } } 

Compare this fairly straightforward code to the ExampleGateway.java, and you can see that more or less all we added is the pollForNewMessages(), the setting of various variables, and the creation of the event that passes NewMessageCount. All the gateway does is check the POP3 server every 60 seconds and, if there is mail flagged as new, sends an event to the associated listener CFC. Another thing you might notice is the usage of the Gateway logger class. Developing custom gateways can be difficult in that you often have to run the gateway on ColdFusion before you can tell if there are any problems ColdFusion will not return much in the way of debugging information so it's a good idea to use the logger class to output information to aid in the development of your code.

Now that we have developed the code for our gateway let's deploy this new gateway type via the ColdFusion Administrator.

Deploying a Custom Event Gateway

Deploying an event gateway is about as easy as creating a new gateway instance. First you need to compile the POP3Gateway and place it in a .jar file then make sure you place the .jar file in the cf_root\gateway\lib. For this example, you also need to make sure the J2EE.jar and the POP3Gateway.jar are in this directory.

NOTE

On J2EE configurations, you want to put your .jars in cf_root\WEB-INF\cfusion\gateway\.


When you're sure that your .jar files are in the right place, go to the ColdFusion Administrator and click on Event Gateway and then on Gateway Types.

The first field is the event Type Name. Enter POP3Gateway. The Description field should show a description of the event type in the Event Gateways > Gateway Instances creation screen, so for this example, use Test of Gateway using POP3. Then enter the .jar name in the Java Class fieldPOP3Gateway in this example. For Startup Timeout, leave the default of 30 seconds. Leave the Stop on Startup Timeout option checked. Your finished page should look something like Figure 31.5.

Figure 31.5. The POP3Gateway event type before it has been deployed in the ColdFusion Administrator.


Now click on Add Type to deploy your new event gateway type. You'll see the POP3Gateway event type now under Configured ColdFusion Gateway Types.

With the gateway deployed, you can test it by using Listing 31.5, creating a config file, and setting up a new event instance.

Listing 31.5. POP3Gateway.CFCSimple CFC to log messages from the POP3gateway.
 <cfcomponent>       <cffunction name="newMailCount" output="no">        <cfargument name="CFEvent" type="struct" required="yes">        <cfset data = CFEvent.data>          <!--- NEWMAILCOUNT --->             <cflog file="pop3gateway" text="you have #data.NewMailCount#">       </cffunction> </cfcomponent> 

For this example, you can create a configuration file called pop3gateway.cfg and add your POP3 server's hostname, your email login, and your email password like this:

 hostname=mail.robisen.com login=robisen password=gloreibel2! 

Save these files in an appropriate location, and then make a new event instance in the ColdFusion Administrator. When you test this gateway, you should add a new log file and record whether you have any new emails in your POP account. You could make this example more interesting by forwarding the message about the number of new emails to your IM or SMS account. To make the Java gateway example more interesting, let it provide more information or allow you to send email or do anything else that POP3 allows you to do. Although CFMAIL and CFPOP offer a lot of functionality, creating your own POP gateway lets you add greater functionality and work with your POP accounts in asynchronously.

ColdFusion gateways are the most exciting and powerful feature to be added to ColdFusion since the original CFQUERY tag. With ColdFusion gateways, you can connect to almost anything and develop a whole new type of ColdFusion application. In Chapter 32, you will explore ColdFusion gateways even more, focusing on SMS and IM applications.



Advanced Macromedia ColdFusion MX 7 Application Development
Advanced Macromedia ColdFusion MX 7 Application Development
ISBN: 0321292693
EAN: 2147483647
Year: 2006
Pages: 240
Authors: Ben Forta, et al

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