com.orderlysoftware.orderlycalls.asterisk.manager
Class ManagerClient

java.lang.Object
  extended by com.orderlysoftware.orderlycalls.base.Service
      extended by com.orderlysoftware.orderlycalls.asterisk.manager.ManagerClient
All Implemented Interfaces:
java.lang.Runnable

public class ManagerClient
extends Service
implements java.lang.Runnable

This class represents the TCP/IP connection to the Asterisk Manager system. The class contains an internal queue to ensure that only one action is processed at a time. Calls to the Send method will therefore block until a response is received. The class also distributes Events to registered ManagerEventListener objects. NOTE: If you require more than one Manager connection to a particular Asterisk server, you should use a proxy to prevent collisions.

Author:
Matt King, M.A. Oxon.

Field Summary
static java.util.logging.Logger log
           
 
Constructor Summary
ManagerClient(ManagerSettings settings)
          Creates a ManagerClient but does not start it.
 
Method Summary
 ManagerResponse absoluteTimeout(java.lang.String channel, int timeout)
          Hangup a channel after a certain time.
 void addManagerEventListener(ManagerEventListener mel)
          If you're interested in Asterisk Manager Events, create a class that implements ManagerEventListener, and add it here.
 ManagerResponse changeMonitor(java.lang.String channel, java.lang.String file)
          Change monitoring filename of a channel.
 void clean()
           
 ManagerResponse command(java.lang.String command, java.lang.String actionId)
          Execute Command Run a CLI command.
 void connect(java.lang.String host, int port)
          Connects to the Aterisk system by TCP/IP, but does not log in.
 void connectAndLogin(ManagerSettings settings)
          Connects to Asterisk over TCP/IP and logs in.
 ManagerResponse events(java.lang.String eventMask)
          Contol Event Flow
 ManagerResponse extensionState(java.lang.String exten, java.lang.String context, java.lang.String actionId)
          Check Extension Status
 long getActionTimeout()
          How long this manager will wait for a response before proceding to the next action.
static ManagerClient getByInetAddress(java.net.InetAddress address)
          Gets a ManagerClient connected to a particular remote IP address.
 java.util.ArrayList getEventListeners()
          Gets all attached ManagerEventListeners.
static ManagerClient getInstance(ManagerSettings settings)
          Gets a ManagerClient instance, or creates one if none can be found.
static ManagerClient getInstance(ManagerSettings settings, boolean reuse)
          Gets a connected ManagerClient instance.
static ManagerClient getInstance(java.lang.String name)
          Gets a connected ManagerClient instance, or null if none can be found.
static java.lang.String getShortChannelName(java.lang.String fullName)
          Utility method for converting a full channel name (e.g.
 java.lang.String getVar(java.lang.String channel, java.lang.String variable, java.lang.String actionId)
          Gets a Channel Variable
 ManagerResponse hangUp(java.lang.String channel)
          Hangup Channel
 ManagerResponse iaxPeers()
          Lists all IAX Peers.
 void init()
          Initialises this ManagerClient based on the settings object stored.
 boolean isRunning()
          Determines whether this service is active.
 ManagerResponse listCommands()
          List available manager commands
 ManagerResponse login(java.lang.String username, java.lang.String password)
          Logs in to Asterisk Manager.
 ManagerResponse logOff()
          Logoff Manager
 ManagerResponse logout()
          Synonym for logOff()
 ManagerResponse mailboxCount(java.lang.String mailbox, java.lang.String actionId)
          Check Mailbox Message Count.
 ManagerResponse mailboxStatus(java.lang.String mailbox, java.lang.String actionId)
          Check Mailbox
static void main(java.lang.String[] args)
          For running ManagerClient as a stand-alone appliction.
 ManagerResponse monitor(java.lang.String channel, java.lang.String file, java.lang.String format, boolean mix)
          Monitor a channel
 ManagerResponse originate(java.lang.String channel, java.lang.String exten, java.lang.String context, java.lang.String priority, java.lang.String application, java.lang.String data, long timeout, java.lang.String callerID, java.lang.String variable, java.lang.String account, boolean async)
          Originate Call
 ManagerResponse parkedCalls()
          Lists parked calls.
 ManagerResponse ping()
          Pings Asterisk.
 ManagerResponse queueAdd(java.lang.String queue, java.lang.String interfaceId, java.lang.String penalty, boolean isPaused, java.lang.String actionId)
          Add interface to queue.
 ManagerResponse queueRemove(java.lang.String queue, java.lang.String interfaceId)
          Remove interface from queue.
 ManagerResponse queues()
          Shows queue status information for all queues.
 ManagerResponse queueStatus(java.lang.String actionId)
          Causes a series of queue status events to be fired.
 ManagerResponse redirect(java.lang.String channel, java.lang.String extraChannel, java.lang.String exten, java.lang.String context, java.lang.String priority)
          Redirects channel(s) to a different extension.
 void removeManagerEventListener(ManagerEventListener mel)
          Call this method to remove event listeners.
 void run()
          The message queue thread.
 void safeClean()
          Closes any connections without throwing an exception.
 ManagerResponse send(ManagerAction action)
          Once you've got a connected ManagerClient object, call this method to send Actions to the Asterisk system.
 void setActionTimeout(long actionTimeout)
          Sets how long this manager will wait for a response before
 ManagerResponse setCDRUserField(java.lang.String userField, java.lang.String channel, java.lang.String append)
          Sets the CDR user field.
 ManagerResponse setVar(java.lang.String channel, java.lang.String variable, java.lang.String value)
          Set a local channel variable.
 void shutdown()
          Gracefully stops the Client.
 ManagerResponse status(java.lang.String channel)
           
 ManagerResponse status(java.lang.String channel, java.lang.String actionId)
          Fires channel status events.
 ManagerResponse stopMonitor(java.lang.String channel)
          Stop monitoring (recording) a channel.
 ManagerResponse zapDialOffHook(java.lang.String zapChannel, java.lang.String number)
          Dial over Zap channel while offhook
 ManagerResponse zapDNDOff(java.lang.String zapChannel)
          Toggle Zap channel Do Not Disturb status OFF
 ManagerResponse zapDNDOn(java.lang.String zapChannel)
          Toggle Zap channel Do Not Disturb status ON
 ManagerResponse zapHangUp(java.lang.String zapChannel)
          Hangup Zap Channel
 ManagerResponse zapShowChannels(java.lang.String actionId)
          Show Zap Channels
 ManagerResponse zapTransfer(java.lang.String zapChannel)
          Transfer Zap Channel
 
Methods inherited from class com.orderlysoftware.orderlycalls.base.Service
getExecutorService, getInstance, getInstance, getInstance, getInstanceByName, getLogName, getName, getSettings, setExecutorService, shutdownAll
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

log

public static java.util.logging.Logger log
Constructor Detail

ManagerClient

public ManagerClient(ManagerSettings settings)
Creates a ManagerClient but does not start it.

Parameters:
settings -
Method Detail

getInstance

public static ManagerClient getInstance(ManagerSettings settings)
Gets a ManagerClient instance, or creates one if none can be found.

Parameters:
settings - The settings to use.
Returns:
A connected, logged in ManagerClient instance.

getInstance

public static ManagerClient getInstance(ManagerSettings settings,
                                        boolean reuse)
Gets a connected ManagerClient instance.

Parameters:
settings - The settings to use.
reuse - Whether or not to reuse an existing instance, if found.
Returns:
A connected, logged in ManagerClient instance.

isRunning

public boolean isRunning()
Description copied from class: Service
Determines whether this service is active.

Specified by:
isRunning in class Service
Returns:
true if running, false otherwise.

getInstance

public static ManagerClient getInstance(java.lang.String name)
Gets a connected ManagerClient instance, or null if none can be found.

Parameters:
name - the Name of the Settings object for the service.
Returns:
The client or null.

init

public void init()
Initialises this ManagerClient based on the settings object stored.

All ManagerEventListeners listed in the settings are created and added.

Specified by:
init in class Service

getByInetAddress

public static ManagerClient getByInetAddress(java.net.InetAddress address)
Gets a ManagerClient connected to a particular remote IP address.

Parameters:
address - The address of the Asterisk server.
Returns:
A connected, logged in ManagerClient, or null if none can be found.

getEventListeners

public java.util.ArrayList getEventListeners()
Gets all attached ManagerEventListeners.

Returns:
Returns the ManagerEventListeners registered.

getActionTimeout

public long getActionTimeout()
How long this manager will wait for a response before proceding to the next action.

Returns:
Returns the actionTimeout.

setActionTimeout

public void setActionTimeout(long actionTimeout)
Sets how long this manager will wait for a response before

Parameters:
actionTimeout - The actionTimeout to set.

addManagerEventListener

public void addManagerEventListener(ManagerEventListener mel)
If you're interested in Asterisk Manager Events, create a class that implements ManagerEventListener, and add it here.

Parameters:
mel - the event listener to add.

removeManagerEventListener

public void removeManagerEventListener(ManagerEventListener mel)
Call this method to remove event listeners.

Parameters:
mel - The event listener to remove.

run

public void run()
The message queue thread. Actions block until responses are received, or the action times out.

Started automatically by the connect() method, which is called by init().

Also pings the server once every minute to keep the connection alive.

Specified by:
run in interface java.lang.Runnable

safeClean

public void safeClean()
Closes any connections without throwing an exception.

Called by shutdown().


getShortChannelName

public static java.lang.String getShortChannelName(java.lang.String fullName)
Utility method for converting a full channel name (e.g. SIP/12345-ab37) to its shortened version (e.g. SIP/12345).

Useful for originating calls.

Parameters:
fullName - The extended name of the channel.
Returns:
the shortened name.

send

public ManagerResponse send(ManagerAction action)
Once you've got a connected ManagerClient object, call this method to send Actions to the Asterisk system. Calling threads will Block until a response is received.

Parameters:
action - The action to execute
Returns:
the response received.

connect

public void connect(java.lang.String host,
                    int port)
Connects to the Aterisk system by TCP/IP, but does not log in.


connectAndLogin

public void connectAndLogin(ManagerSettings settings)
Connects to Asterisk over TCP/IP and logs in. This method is called for you by init().

Parameters:
settings -

clean

public void clean()
           throws java.io.IOException
Throws:
java.io.IOException
See Also:
safeClean()

shutdown

public void shutdown()
Gracefully stops the Client.

Specified by:
shutdown in class Service

absoluteTimeout

public ManagerResponse absoluteTimeout(java.lang.String channel,
                                       int timeout)
Hangup a channel after a certain time.

Privilege: call

Acknowledges with 'Timeout Set' message

Parameters:
channel - Channel name to hangup
timeout - Maximum duration of the call (sec)
Returns:

changeMonitor

public ManagerResponse changeMonitor(java.lang.String channel,
                                     java.lang.String file)
Change monitoring filename of a channel.

The 'ChangeMonitor' action may be used to change the file started by a previous 'Monitor' action.

Privilege: call

Parameters:
channel - Required. Used to specify the channel to record.
file - Required. Is the new name of the file created in the monitor spool directory.
Returns:

command

public ManagerResponse command(java.lang.String command,
                               java.lang.String actionId)
Execute Command Run a CLI command.

Privilege: command

Parameters:
command - Required: Asterisk CLI command to run
actionId - Optional: Action id for message matching.
Returns:

events

public ManagerResponse events(java.lang.String eventMask)
Contol Event Flow

Enable/Disable sending of events to this manager client.

Warning: This manager action does not always return a response. Specifically, if the "on" command is sent when events are already being sent, no response is returned.

This will cause the message queue to hang for until actionTimeout milliseconds have passed (default 10 seconds).

There is no known workaround.

Privilege: none

Parameters:
eventMask - "on" if all events should be sent, "off" if no events should be sent, "system,call,log" to select which flags events should have to be sent.
-
Returns:

extensionState

public ManagerResponse extensionState(java.lang.String exten,
                                      java.lang.String context,
                                      java.lang.String actionId)
Check Extension Status

Report the extension state for given extension. If the extension has a hint, will use devicestate to check the status of the device connected to the extension.

Will return an "Extension Status" message.

Parameters:
exten - Required: Extension to check state on
context - Required: Context for extension
actionId - Optional: ID for this transaction
Returns:
The response will include the hint for the extension and the status.

getVar

public java.lang.String getVar(java.lang.String channel,
                               java.lang.String variable,
                               java.lang.String actionId)
Gets a Channel Variable

Get the value of a local channel variable.

Privilege: call

Parameters:
channel - Required: Channel to read variable from
variable - Required: Variable name
actionId - Optional: Action id for message matching.
Returns:
the value of the variable, or null if not set.

hangUp

public ManagerResponse hangUp(java.lang.String channel)
Hangup Channel

Privilege: call

Parameters:
channel - The channel name to be hungup
Returns:

iaxPeers

public ManagerResponse iaxPeers()
Lists all IAX Peers.

Warning: If no peers are registered to the asterisk server, no response is returned. This will cause the message queue to hang for timeout (default 10 seconds)

Privilege: None

Returns:

listCommands

public ManagerResponse listCommands()
List available manager commands

Privilege: none

Returns:
the action name and synopsis for every action that is available to the user

login

public ManagerResponse login(java.lang.String username,
                             java.lang.String password)
                      throws java.io.IOException
Logs in to Asterisk Manager.

This method is called for you by connectAndLogin(ManagerSettings settings).

Parameters:
settings -
Returns:
Throws:
java.io.IOException

logOff

public ManagerResponse logOff()
Logoff Manager

Logoff this manager session

Privilege: none

Returns:

logout

public ManagerResponse logout()
Synonym for logOff()

Returns:

mailboxCount

public ManagerResponse mailboxCount(java.lang.String mailbox,
                                    java.lang.String actionId)
Check Mailbox Message Count.

Checks a voicemail account for new messages.

Privilege: call

Parameters:
mailbox - Required: Full mailbox ID (e.g. mailbox@vm-context)
actionId - Optional: ActionID for message matching.
Returns:
response containing number of new and old messages. Message: Mailbox Message Count Mailbox: mailboxid NewMessages: count OldMessages: count

mailboxStatus

public ManagerResponse mailboxStatus(java.lang.String mailbox,
                                     java.lang.String actionId)
Check Mailbox

Checks a voicemail account for status.

Privilege: call

Parameters:
mailbox - Required: Full mailbox ID (e.g. mailbox@vm-context)
actionId - Optional: ActionID for message matching.
Returns:
ManagerResponse containing number of messages. Message: Mailbox Status Mailbox: mailboxid Waiting: count

monitor

public ManagerResponse monitor(java.lang.String channel,
                               java.lang.String file,
                               java.lang.String format,
                               boolean mix)
Monitor a channel

The 'Monitor' action may be used to record the audio on a specified channel.

Privilege: call

Parameters:
channel - Required: Used to specify the channel to record.
file - Optional: Is the name of the file created in the monitor spool directory. Defaults to the same name as the channel (with slashes replaced with dashes).
format - Optional. Is the audio recording format. Defaults to "wav". "gsm" and "mp3" are also valid values.
mix - mixes the input and output channels together after the recording is finished to produce a single file if true.
Returns:

originate

public ManagerResponse originate(java.lang.String channel,
                                 java.lang.String exten,
                                 java.lang.String context,
                                 java.lang.String priority,
                                 java.lang.String application,
                                 java.lang.String data,
                                 long timeout,
                                 java.lang.String callerID,
                                 java.lang.String variable,
                                 java.lang.String account,
                                 boolean async)
Originate Call

Generates an outgoing call to a Extension/Context/Priority or Application/Data

Privilege: call

Parameters:
channel - Required: Channel name to call
exten - Optional: Extension to use (requires 'Context' and 'Priority')
context - Optional: Context to use (requires 'Exten' and 'Priority')
priority - Optional: Priority to use (requires 'Exten' and 'Context')
application - Optional: Application to use
data - Optional: Data to use (requires 'Application')
timeout - Optional: How long to wait for call to be answered (in ms)
callerID - Optional: Caller ID to be set on the outgoing channel
variable - Optional: Channel variable to set (use "VAR1=value1|VAR2=value2" to set multiple variables)
account - Optional: Account code
async - Optional: Uses fast origination when true.
Returns:

parkedCalls

public ManagerResponse parkedCalls()
Lists parked calls.

Privilege: none

Note: The actual Parked Call data is sent in an event immediately following this call, and is not returned in the response. To capture the data, you must add a ManagerEventListener.

Returns:

ping

public ManagerResponse ping()
Pings Asterisk.

A 'Ping' action will ellicit a 'Pong' response. Used to keep the manager connection open.

ManagerClient objects automatically Ping the server once per minute in order to maintain connections.

Returns:
Throws:
java.io.IOException

queueAdd

public ManagerResponse queueAdd(java.lang.String queue,
                                java.lang.String interfaceId,
                                java.lang.String penalty,
                                boolean isPaused,
                                java.lang.String actionId)
Add interface to queue.

Privilege: agent

Parameters:
queue - Required: Existing queue to add member.
interfaceId - Required: Member interface (sip/1000, zap/1-1, etc) .
penalty - Optional: Entries with higher penalties are considered last.
isPaused - If true member is initially paused.
actionId - Optional: Action ID for message tracking.
Returns:

queueRemove

public ManagerResponse queueRemove(java.lang.String queue,
                                   java.lang.String interfaceId)
Remove interface from queue.

Privilege: agent

Parameters:
queue -
interfaceId -
Returns:

queues

public ManagerResponse queues()
Shows queue status information for all queues.

Privilege: none

Returns:

queueStatus

public ManagerResponse queueStatus(java.lang.String actionId)
Causes a series of queue status events to be fired.

You must add a ManagerEventListener in order to receive these events.

Parameters:
actionId - Optional: parameter for message tracking
Returns:

redirect

public ManagerResponse redirect(java.lang.String channel,
                                java.lang.String extraChannel,
                                java.lang.String exten,
                                java.lang.String context,
                                java.lang.String priority)
Redirects channel(s) to a different extension.

Parameters:
channel - Required: the channel to redirect
extraChannel - Optional: An additional channel to redirect (e.g. 2-party call to meeting room)
exten - The target extension
context - The target context
priority - The target priority
Returns:

setCDRUserField

public ManagerResponse setCDRUserField(java.lang.String userField,
                                       java.lang.String channel,
                                       java.lang.String append)
Sets the CDR user field.

Parameters:
userField -
channel -
append -
Returns:

setVar

public ManagerResponse setVar(java.lang.String channel,
                              java.lang.String variable,
                              java.lang.String value)
Set a local channel variable.

All parameters are required.

Privilege: call

Parameters:
channel - channel to set variable for
variable - variable name
value - variable value
Returns:

status

public ManagerResponse status(java.lang.String channel,
                              java.lang.String actionId)
Fires channel status events.

You will need to add a ManagerEventListener to capture them.

Privilege: call

Parameters:
channel - Required: the channel to show the status.
actionId - Optional: message identifier for tracking.
Returns:

status

public ManagerResponse status(java.lang.String channel)

stopMonitor

public ManagerResponse stopMonitor(java.lang.String channel)
Stop monitoring (recording) a channel.

Privilege: call

Parameters:
channel - Required: The channel to cease recording.
Returns:

zapDialOffHook

public ManagerResponse zapDialOffHook(java.lang.String zapChannel,
                                      java.lang.String number)
Dial over Zap channel while offhook

Parameters:
zapChannel -
number -
Returns:

zapDNDOff

public ManagerResponse zapDNDOff(java.lang.String zapChannel)
Toggle Zap channel Do Not Disturb status OFF

Parameters:
zapChannel -
Returns:

zapDNDOn

public ManagerResponse zapDNDOn(java.lang.String zapChannel)
Toggle Zap channel Do Not Disturb status ON

Parameters:
zapChannel -
Returns:

zapHangUp

public ManagerResponse zapHangUp(java.lang.String zapChannel)
Hangup Zap Channel

Parameters:
zapChannel -
Returns:

zapShowChannels

public ManagerResponse zapShowChannels(java.lang.String actionId)
Show Zap Channels

Parameters:
actionId - Optional: message id for tracking.
Returns:

zapTransfer

public ManagerResponse zapTransfer(java.lang.String zapChannel)
Transfer Zap Channel

Parameters:
zapChannel -
Returns:

main

public static void main(java.lang.String[] args)
For running ManagerClient as a stand-alone appliction.

If you also require AGI functionality, you should run an AGIServer instead, and have your AGIProcessor objects call ManagerClient.getManagerClient()

 Usage: java com.orderlysoftware.orderlycalls.manager.ManagerClient    [username] [password]
 
Username and Password are mandatory, all other arguments optional.

Parameters:
args -