All pages
Powered by GitBook
1 of 9

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Interceptors

Interceptors are a powerful event-driven model inside CommandBox that allows you to listen to broadcasts from within the core code to respond to events and even influence execution. Interceptors are packaged within CommandBox Modules and can be for your own use, just debugging, or to share with the world.

To create a simple interceptor, re-create the simple folder structure below inside your CommandBox installation directory.

~/.CommandBox/cfml/modules
+-- myModule/
    |-- ModuleConfig.cfc
    +-- interceptors/
        +-- MyInterceptor.cfc

Creating An Interceptor

An interceptor is a CFC that has one or more methods whose names match the name of an interception point that is broadcast. Interceptors are packaged within CommandBox modules. When the module is loaded, the InterceptorService will register your interceptor and take care of calling it when necessary.

Here is an example of an interceptor. It listens to the postCommand event and upper cases all output from the command before it is returned to the console. It also listens to onException to perform some additional error processing.

MyInterceptor.cfc

component {

    // This runs after every command execution
    function postCommand( interceptData ) {
        // Overwrite the results with an upper case version of itself
        interceptData.results = ucase( interceptData.results );
    }

    // This runs after every error
    function onException( interceptData ) {
        // Write the last exception to a file
        fileWrite( '/commandbox-home/logs/lastError.txt', serializeJSON( interceptData.exception ) );
    }

}

Registering An Interceptor

Now that we have our interceptor above, how do we register it? This code in our module's config file registers the interceptor so it will listen to the announcements it has declared.

ModuleConfig.cfc

component{
    function configure(){

        // Declare our interceptors to listen
        interceptors = [
            { class='#moduleMapping#.interceptors.MyInterceptor' }
        ];

    }
}

Core Interception Points

Here is a list of all the core interception points in CommandBox that you can listen to. Some have interceptData that comes along with them, while others don't. Remember, the interceptData struct is passed by reference. This means modifying any values directly in that struct will affect how processing continues afterwards inside of CommandBox where those values are used.

Click a category for more information.

  • CLI Lifecycle

    • onCLIStart

    • onCLIExit

    • onSystemSettingExpansion

    • onConfigSettingSave

    • onEndpointLogin

  • Command Execution Lifecycle

    • preCommand

    • preCommandParamProcess

    • postCommand

    • prePrompt

    • preProcessLine

    • postProcessLine

  • Module Lifecycle

    • preModuleLoad

    • postModuleLoad

    • preModuleUnLoad

    • postModuleUnload

  • Server Lifecycle

    • preServerStart

    • onServerStart

    • onServerInstall

    • onServerInitialInstall

    • onServerStop

    • preServerForget

    • postServerForget

  • Error Handling

    • onException

  • Package Lifecycle

    • preInstall

    • onInstall

    • postInstall

    • preUninstall

    • postUninstall

    • preInstallAll

    • postInstallAll

    • preVersion

    • postVersion

    • prePublish

    • postPublish

    • preUnpublish

    • postUnpublish

    • onRelease

Custom Interception Points

You have the ability to create your own interception points on top of the core ones in CommandBox. This can be handy to employ your own event listener model within a module-- which could be comprised of multiple models and commands. Interceptors that listen to custom interception points work the exact same as interceptors that listen to core interception points. In fact, the same interceptor file can listen to both.

Register

To register your custom interception point with InterceptorService, place the following config in your module's ModuleConfig.cfc. This module is registering a custom interception point called onCustomEvent.

component{

  function configure(){

    interceptorSettings = {
        customInterceptionPoints = 'onCustomEvent'
    };

  }
}

Announce

It's up to you to decide when to announce this event and what intercept data you want to provide to it. To announce, use the announceInterception method in the InterceptorService. Here's a model that shows how:

component{
    property name="InterceptorService" inject="InterceptorService";

    function doSomethingAmazing(){

        interceptorService.announceInterception(
            state='onCustomEvent',
            interceptData={
                data='foo',
                moreData='bar'
            }
        );

    }
}

Error Handling

onException

Announced any time an unhandled exception is thrown.

interceptData

  • exception - Error struct

Package Lifecycle

preInstall

Announced prior to installing a package. If a package has additional dependencies to install, each of them will fire this interception point.

interceptData

  • installArgs - Struct containing the following keys used in installation of the package.

    • ID - The ID of the package to install

    • directory - Directory to install to. May be null, if none supplied.

    • save - Flag to save box.json dependency

    • saveDev - Flag to save box.json dev dependency

    • production - Flag to perform a production install

    • currentWorkingDirectory - Original working directory that requested installation

    • verbose - Flag to print verbose output

    • force - Flag to force installation

    • packagePathRequestingInstallation - Path to package requesting installing. This climbs the folders structure for nested dependencies.

onInstall

Announced while a package is being installed, after the package endpoint and installation directory has been resolved but before the actual installation occurs. This allows you to override things like the installation directory based on package type. Any values updated in the interceptData struct will override what the install command uses.

interceptData

  • installArgs - Same as preInstall above

  • installDirectory - Directory that the package will be installed in

  • containerBoxJSON - A struct containing the box.json of the page requesting the installation

  • artifactDescriptor - A struct containing the box.json of the package artifcat about to be installed

  • artifactPath - The folder containing the unzipped artifact, ready to be installed.

  • ignorePatterns - An array of file globbing patterns to ignore on installation

  • endpointData - A struct containing the following keys.

    • endpointName - The name of the endpoint. i.e. "forgebox" or "HTTP"

    • package - The name of the package. i.e. "cborm" or "coldbox"

    • ID - The canonical ID of the endpoint. i.e. "forgebox:coldbox" or "github:user/repo"

    • endpoint - The instance of the endpoint CFC that implements IEndpoint.

postInstall

Announced after an installation is complete. If a package has additional dependencies to install, each of them will fire this interception point. This fires even if an install is skipped due to an existing package that satisfies the dependencies, or if the package is already installed.

interceptData

  • installArgs - Same as preInstall above

preUninstall

Announced before the uninstallation of a package.

interceptData

  • uninstallArgs - Struct containing the following keys used in removal of the package

    • ID - ID of the package to uninstall

    • directory - The directory to be uninstalled from (used to find box.json)

    • save - Whether to update box.json

    • currentWorkingDirectory - Path to package requesting removal . This climbs the folders structure for nested dependencies.

postUninstall

Announced after the uninstallation of a package.

interceptData

  • uninstallArgs - Same as preUninstall above

preInstallAll

Announced once before all dependencies are installed, no matter how many are actually installed.

interceptData

  • installArgs - Raw parameters passed to the install command.

postInstallAll

Announced once after all dependencies are installed, no matter how many are actually installed.

interceptData

  • installArgs - Raw parameters passed to the install command.

preVersion

Announced before the new version is set in the package.

interceptData

  • versionArgs - A struct containing the following keys:

    • version - The new version about to be set

    • tagVersion - Boolean that determines whether to tag a Git repo

    • message - Commit message to use when tagging Git repo

    • directory - The working directory of the package

    • force - If true, tag a Git repo even if it isn't clean

postVersion

Announced after the new version is set in the package but before the Git repo is tagged.

interceptData

  • versionArgs - Same as preVersion above.

onRelease

Announced after a new version is set using the bump command and after the Git repo is tagged.

interceptData

  • directory - The working directory of the package

  • version - The new version about was set

prePublish

Announced prior to publishing a package to an endpoint

interceptData

  • publishArgs - A struct containing the following keys:

    • endpointName - The name of the endpoint being published to

    • directory - The directory that the package lives in

  • boxJSON - A struct containing the defaulted box.json properties for the package

postPublish

Announced after publishing a package to an endpoint

interceptData

  • publishArgs - Same as prePublish above.

  • boxJSON - Same as prePublish above.

  • preUnpublish

Announced prior to unpublishing a package from an endpoint

interceptData

  • unpublishArgs - A struct containing the following keys:

    • endpointName - The name of the endpoint being published to

    • directory - The directory that the package lives in

    • version - The version being unpublished

    • force - Boolean to skip the interactive prompt

  • boxJSON - A struct containing the defaulted box.json properties for the package

postUnpublish

Announced after unpublishing a package from an endpoint

interceptData

  • unpublishArgs - Same as preUnpublish above.

  • boxJSON - Same as preUnpublish above.

CLI Lifecycle

onCLIStart

Announced when shell first starts, but before any commands are run or output has been flushed to the console.

interceptData

  • shellType - The string interactive if starting the interactive shell, or command if running a one-off command and exiting

  • args - An array of arguments provided from the OS when box was executed.

  • banner - A string containing the CommandBox banner text that displays when in interactive mode.

This fires every time the reload command runs and a fresh shell is created.

onCLIExit

Announced right before the shell exits and control is returned back to the OS. This fires every time the reload command runs right before the shell is destroyed and re-created.

onSystemSettingExpansion

Announced every time a system setting in the format of ${something} is expanded. Any interceptor listening can provide an expanded value.

interceptData

  • setting - The name of the setting with the default value removed.

  • defaultValue - The text after the final : or an empty string if there is no default provided

  • resolved - Set this to true if your interceptor expands the value and return true from your interceptor method so CommandBox stops the interceptor chain.

  • context - A struct of values if this system setting is being expanded in the context of a JSON file.

onConfigSettingSave

Announced every time a Config Setting is added, removed, or updated.

interceptData

  • configFilePath- Full path to the CommandBox.json file

  • configSettings- Struct of current config settings

onEndpointLogin

Announced any time a user either logs into ForgeBox (forgebox login) or switches users (forgebox use)

interceptData

  • endpointName - Name of endpoint logged into

  • username - Username that was logged into

  • endpoint - Endpoint CFC instance

  • APIToken - API Token of user that logged in

Command Execution Lifecycle

preCommand

Announced before the execution of a command. This fires after all command parameters have been evaluated, including expressions. If piping the output of one command into another in a command chain, this will fire twice-- once for each command in the chain.

interceptData

  • commandInfo - A struct containing the following keys about the command to execute

    • commandString - A string representing the command name

    • commandReference - The instantiated Command CFC

    • parameters - An array of un-parsed parameter tokens typed in the CLI

    • closestHelpCommand - The CFC path to the most-applicable help command. Used to generate namespace help.

  • parameterInfo - A struct containing the following keys about the processed parameters for the command execution

    • positionalParameters - An array of parameter values

    • namedParameters - A struct of name/value pairs. The named parameters are always what is passed to the command's run() method.

    • flags - A struct of flags that were passed in.

preCommandParamProcess

preCommand fires after expression, system setting, and colon param expansions have already occurred. preCommandParamProcess will fire prior to that so you can affect the system prior to the time the system settings are expanded in parameter values.

  • commandInfo - Same as above

  • parameterInfo - Same as above

postCommand

Announced immediately after command execution is complete. If more than one command is piped together in a command chain, this is announced after each command in the chain.

interceptData

  • commandInfo - Same as preCommand above

  • parameterInfo - Same as preCommand above

  • results - A string that represents any output from the command that hasn't already been flushed to the console.

prePrompt

Announced prior to drawing the prompt in the interactive shell. This interception point can be used to customize the text of the prompt by modifying the prompt variable in intercept data which is an ANSI-formatted string to be output before the cursor.

interceptData

  • prompt - An ANSI-formatted string containing the prompt text. Replacing this value will override the prompt.

preProcessLine

Pre and post command fire before and after each command, but that means they fire twice for something like:

echo `package show name`

preProcessLine will fire only once for the above command after the user hits enter but before anything is processed.

interceptData

  • line - A string representing the line typed into the shell. Changing the contents of this string will override what actually gets executed.

postProcessLine

Pre and post command fire before and after each command, but that means they fire twice for something like:

echo `package show name`

postProcessLine will fire only once for the above command after the entire line has been executed. Any output is already sent to the console by the time this interception point fires.

interceptData

  • line - A string representing the line that was just executed in the shell.

Module Lifecycle

preModuleLoad

Announced before each module that is loaded.

interceptData

  • moduleLocation - Path to the module

  • moduleName - Name of the module

postModuleLoad

Announced after each module that is loaded.

interceptData

  • moduleLocation - Path to the module

  • moduleName - Name of the module

  • moduleConfig - Struct representing the configuration data for the module.

preModuleUnLoad

Announced before each module that is unloaded.

interceptData

  • moduleName - Name of the module

postModuleUnload

Announced after each module that is unloaded.

interceptData

  • moduleName - Name of the module

Server Lifecycle

preServerStart

Announced before a server starts. This fires after server.json has been located but before any configuration is resolved. Use this to override any user inputs, influence how the server's details are resolved, or to modify things like hostname before ports are bound.

interceptData

  • serverDetails - A struct with the following keys used in starting the server

    • defaultName - The name of the server

    • defaultwebroot - The web root of the server

    • defaultServerConfigFile - The location of the server.json (May not exist yet)

    • serverJSON - The parsed contents of the JSON file

    • serverInfo - The serverInfo Struct (see below)

    • serverIsNew - A boolean whether this server has been started before.

  • serverProps - A struct with the parameters passed to the start command from the CLI. Omitted params will not be present.

    • See the help for the server start command to see the current list of parameters.

onServerStart

Announced as a server is starting after the configuration values have been resolved, but prior to the actual server starts. Use this to modify the settings for the server before it starts.

interceptData

  • serverInfo - A struct with the following keys used in starting the server

    • name - The name of the server

    • webroot - The path to the web root

    • serverConfigFile - The path to the server.json file (may not exist)

    • trayEnable - If tray menu is enabled

    • customServerFolder - Where the server's log files live. May be the same as serverHomeDirectory

    • debug - Whether to start Runwar in debug mode

    • trace - Whether to start Runwar in trace mode

    • console - Whether to start server in console mode

    • openbrowser - Flag to open web browser upon start

    • host - The hostname to bind the server to

    • port - The HTTP port

    • stopsocket - The socket to listen for stop connections

    • webConfigDir - Path to the Lucee web context

    • serverConfigDir - Path to the Lucee server context

    • libDirs - List of additional lib paths

    • trayEnable - If tray menu is enabled

    • trayIcon - Path to .png file for tray icon

    • trayOptions - Array of tray menu options

    • webXML - Path to web.com file

    • SSLEnable - Enable HTTPS flag

    • HTTPEnable - Enable HTTP flag

    • SSLPort - HTTPS port

    • SSLCert - SSL Certificate

    • SSLKey -SSL Key

    • SSLKeyPass - SSL Key passphrase

    • rewritesEnable - Enable URL rewrites

    • rewritesConfig - Path to custom Tuckey rewrite config file

    • heapSize - Max heap size in Megabytes

    • directoryBrowsing - Enable directory browsing

    • JVMargs - Additional JVM args to use when starting the server

    • runwarArgs - Additional Runwar options to use when starting the server

    • logdir - Path to directory for server logs

    • welcomeFiles - List of welcome files

  • serverDetails - Same as onServerStart above

  • installDetails - Same as onInstall below

onServerInstall

Announced when a server is starting and the cfengine is being installed. This gives you a chance to influence how the server is installed or to modify default settings before the server process actually starts. This is not announced for servers using a WARPath setting. It is announced every time a server is started, but you can use the installDetails.initialInstall flag to determine if this is the first time the engine is being installed for one-time tasks.

interceptData

  • serverInfo - Same as onServerStart above

  • installDetails A struct with the following keys:

    • internal - True if using the embedded jars from the CLI

    • enginename - The name of the cfengine that was installed

    • version - The version of the cfengine that was installed

    • installDir - The folder where the server is installed to

    • initialInstall - True if this is the first time the engine was installed

onServerInitialInstall

This is the same as onServerInstall above, but it only runs the VERY FIRST time a CF engine is installed. This is helpful if you want to install Lucee extensions or ACF modules and you only need to do it the first time. This interceptor is easier than using onServerInstall and inspecting the installDetails.initialInstall flag.

onServerStop

Announced before a server stop.

interceptData

  • serverInfo - Same as onServerStart above

preServerForget

Always fires before attempting to forget a server whether or not the forgetting is actually successful. Has access to all files and settings for the server.

interceptData

  • serverInfo - Same as onServerStart above

postServerForget

Fires after a successful server forget. If the forget fails, this will not fire.

interceptData

  • serverInfo - Same as onServerStart above