Event Gateways - Gateway Instances

Create and manage event gateway instances for asynchronous messaging

Overview

Gateway instances are individual running instances of event gateways that process asynchronous events in ColdFusion. Each instance is based on a gateway type (SMS, IM, custom) and can be configured with specific settings, startup behavior, and CFCs to handle incoming messages or events.

Event gateways enable ColdFusion applications to respond to events from external systems without requiring direct HTTP requests, making them ideal for SMS processing, instant messaging, directory monitoring, and custom integration scenarios.

Gateway Instance Configuration

Essential settings for creating and managing gateway instances.

Gateway ID

PurposeUnique identifier for the gateway instance
RequirementsMust be unique across all gateway instances
RecommendationUse descriptive names like SMS_Notifications or Order_Directory_Monitor
Best Practice: Use clear, descriptive names that indicate the gateway's purpose and type. This makes maintenance and troubleshooting easier.

Gateway Type

PurposeSpecifies the type of gateway this instance uses
Built-in TypesSMS, XMPP (Jabber IM), DataManagement, FMS, DirectoryWatcher
Custom TypesCan be created by developing Java classes that implement gateway interfaces
Note: Gateway types must be configured in the Gateway Types section before you can create instances. Custom gateway types require Java development and deployment.

CFC Path

PurposePath to the CFC that processes incoming events
FormatDot notation path (e.g., gateways.SMSHandler)
Required MethodsonIncomingMessage() for most gateway types
Important: The CFC must implement the appropriate listener methods for the gateway type. Different gateway types may require different method signatures.

Configuration File

PurposePath to properties file containing gateway-specific configuration
FormatJava properties file (.properties or .cfg)
ContentsGateway-specific settings like host, port, credentials, polling intervals
Security: Store sensitive information like passwords and API keys in the configuration file rather than hardcoding them in CFCs. Ensure proper file permissions to protect credentials.

Startup Mode

PurposeControls when the gateway starts
OptionsAutomatic: Starts when ColdFusion starts
Manual: Must be started explicitly
Disabled: Gateway will not start
RecommendationProduction: Automatic for critical gateways
Development: Manual for testing
Warning: Automatic startup can cause issues if gateway dependencies (databases, external services) are not available when ColdFusion starts. Ensure proper startup order.

Common Gateway Types

Built-in gateway types and their typical use cases.

SMS Gateway

Purpose
Send and receive SMS messages
Use Cases
Notifications, two-factor authentication, mobile alerts
Requirements
SMS provider account and credentials

Processes incoming SMS messages and sends outbound messages through SMS providers.

XMPP (Jabber) Gateway

Purpose
Instant messaging integration
Use Cases
Chat bots, notifications, team communication
Requirements
XMPP server connection details

Enables ColdFusion to send and receive instant messages via XMPP protocol.

Directory Watcher

Purpose
Monitor file system for changes
Use Cases
File processing, import automation, batch jobs
Requirements
Directory path and file permissions

Watches directories for file additions, changes, or deletions and triggers CFC processing.

DataManagement Gateway

Purpose
BlazeDS data synchronization
Use Cases
Flex/Flash applications (legacy)
Status
Legacy - Flash EOL December 2020

Provided data services for Adobe Flex applications. No longer recommended for new development.

Gateway Instance Management

Operations available for managing gateway instances.

Start/Stop/Restart

StartBegins processing events for the gateway instance
StopGracefully shuts down the gateway and stops event processing
RestartStops and starts the gateway (useful after configuration changes)
Best Practice: Always restart gateway instances after modifying their configuration files or updating the listener CFC to ensure changes take effect.

Status Monitoring

RunningGateway is active and processing events
StoppedGateway is not running
FailedGateway encountered an error during startup or operation
Troubleshooting: Check ColdFusion logs (coldfusion-event.log) for error details when a gateway fails to start or shows failed status.

Example Gateway Listener CFC

Basic gateway listener CFC showing core functionality:

Gateway Listener CFC
// gateways/SMSHandler.cfc
component {

  /**
   * Process incoming SMS messages
   * @cfcEvent The event object containing message data
   */
  public void function onIncomingMessage(required struct cfcEvent) {
    // Extract message data
    var senderPhone = arguments.cfcEvent.data.fromNumber;
    var messageText = arguments.cfcEvent.data.message;
    var gatewayID = arguments.cfcEvent.gatewayID;

    // Log the incoming message
    writeLog(
      file = "sms-gateway",
      type = "information",
      text = "SMS from #senderPhone#: #messageText#"
    );

    try {
      // Process the message
      processSMSCommand(senderPhone, messageText);

    } catch (any e) {
      // Log errors
      writeLog(
        file = "sms-gateway",
        type = "error",
        text = "Error processing SMS: #e.message#"
      );
    }
  }

  /**
   * Process SMS commands
   */
  private void function processSMSCommand(
    required string phone,
    required string message
  ) {
    // Parse command (e.g., "SUBSCRIBE", "STOP", "HELP")
    var command = trim(ucase(arguments.message));

    switch (command) {
      case "SUBSCRIBE":
        // Add to subscription list
        subscribeUser(arguments.phone);
        sendSMSReply(arguments.phone, "You are now subscribed!");
        break;

      case "STOP":
      case "UNSUBSCRIBE":
        // Remove from subscription list
        unsubscribeUser(arguments.phone);
        sendSMSReply(arguments.phone, "You have been unsubscribed.");
        break;

      case "HELP":
        sendSMSReply(
          arguments.phone,
          "Commands: SUBSCRIBE, STOP, HELP"
        );
        break;

      default:
        sendSMSReply(arguments.phone, "Unknown command. Reply HELP for options.");
    }
  }

  /**
   * Send SMS reply
   */
  private void function sendSMSReply(
    required string phone,
    required string message
  ) {
    // Use SendGatewayMessage to send reply
    var msgData = {
      "toNumber" = arguments.phone,
      "message" = arguments.message
    };

    sendGatewayMessage("SMS_Notifications", msgData);
  }

  private void function subscribeUser(required string phone) {
    // Database logic to add subscriber
    queryExecute(
      "INSERT INTO sms_subscribers (phone, subscribed_date) VALUES (?, ?)",
      [arguments.phone, now()],
      {datasource: "myDB"}
    );
  }

  private void function unsubscribeUser(required string phone) {
    // Database logic to remove subscriber
    queryExecute(
      "DELETE FROM sms_subscribers WHERE phone = ?",
      [arguments.phone],
      {datasource: "myDB"}
    );
  }

}
// gateways/FileProcessor.cfc
component {

  /**
   * Process file system events
   * @cfcEvent The event object containing file change data
   */
  public void function onIncomingMessage(required struct cfcEvent) {
    var changeType = arguments.cfcEvent.data.type;
    var fileName = arguments.cfcEvent.data.filename;
    var filePath = arguments.cfcEvent.data.path;

    writeLog(
      file = "file-watcher",
      type = "information",
      text = "File #changeType#: #filePath##fileName#"
    );

    // Only process file additions
    if (changeType == "ADD") {
      processNewFile(filePath, fileName);
    }
  }

  /**
   * Process newly added files
   */
  private void function processNewFile(
    required string path,
    required string filename
  ) {
    var fullPath = arguments.path & arguments.filename;

    try {
      // Read file content
      var fileContent = fileRead(fullPath);

      // Process based on file type
      if (findNoCase(".csv", arguments.filename)) {
        processCSVFile(fileContent, arguments.filename);
      }
      else if (findNoCase(".xml", arguments.filename)) {
        processXMLFile(fileContent, arguments.filename);
      }

      // Archive processed file
      archiveFile(fullPath);

    } catch (any e) {
      writeLog(
        file = "file-watcher",
        type = "error",
        text = "Error processing #arguments.filename#: #e.message#"
      );

      // Move to error directory
      moveToErrorDirectory(fullPath);
    }
  }

  private void function processCSVFile(
    required string content,
    required string filename
  ) {
    // CSV processing logic
    writeLog(
      file = "file-watcher",
      text = "Processing CSV file: #arguments.filename#"
    );
  }

  private void function processXMLFile(
    required string content,
    required string filename
  ) {
    // XML processing logic
    writeLog(
      file = "file-watcher",
      text = "Processing XML file: #arguments.filename#"
    );
  }

  private void function archiveFile(required string filePath) {
    var archivePath = expandPath("/archives/");
    fileMove(arguments.filePath, archivePath);
  }

  private void function moveToErrorDirectory(required string filePath) {
    var errorPath = expandPath("/errors/");
    fileMove(arguments.filePath, errorPath);
  }

}

Programmatic Gateway Management

You can also manage gateway instances programmatically using ColdFusion functions:

Gateway Management Functions
// Get all gateway instances
gateways = getGatewayHelper().getGateways();
writeDump(gateways);

// Get specific gateway state
gatewayState = getGatewayHelper().getGatewayState("SMS_Notifications");
writeOutput("Gateway status: #gatewayState#");

// Start a gateway
result = getGatewayHelper().startGateway("SMS_Notifications");

// Stop a gateway
result = getGatewayHelper().stopGateway("SMS_Notifications");

// Restart a gateway
result = getGatewayHelper().restartGateway("SMS_Notifications");

// Send message via gateway
msgData = {
  "toNumber": "+15555551234",
  "message": "Hello from ColdFusion!"
};
sendGatewayMessage("SMS_Notifications", msgData);

Common Issues & Solutions

Gateway Fails to Start

Symptom: Gateway shows "Failed" status and does not process events
Solutions:
  • Check coldfusion-event.log for error messages
  • Verify CFC path is correct and CFC file exists
  • Ensure configuration file path is valid
  • Check that required methods exist in listener CFC
  • Verify external service connectivity (for SMS, IM gateways)
  • Confirm file permissions on configuration files

Events Not Being Processed

Symptom: Gateway is running but events are not triggering CFC methods
Solutions:
  • Verify gateway status is "Running" not just "Started"
  • Check that onIncomingMessage() method exists in CFC
  • Review method signature matches gateway type requirements
  • Add logging inside CFC to verify method is being called
  • Restart gateway after CFC changes
  • Check for errors in exception.log

Configuration Changes Not Taking Effect

Symptom: Modified configuration settings or CFC code not being used
Solutions:
  • Restart the gateway instance (configuration is loaded at startup)
  • For CFC changes, clear template cache or restart gateway
  • Verify you modified the correct configuration file
  • Check file permissions allow ColdFusion to read the file
  • Ensure no syntax errors in configuration file

Related Resources