diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..1dfca740e --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +[*.{java,html}] +charset = utf-8 +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true + +[*.{yml,yaml}] +indent_size = 2 diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..3660fe492 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,14 @@ +version: 2 +updates: + - package-ecosystem: "maven" + directory: "/" + schedule: + interval: "daily" + labels: + - "kind/dependencies" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + labels: + - "kind/dependencies" diff --git a/.github/release-drafter-master.yml b/.github/release-drafter-master.yml new file mode 100644 index 000000000..ef2d4ba5a --- /dev/null +++ b/.github/release-drafter-master.yml @@ -0,0 +1,33 @@ +filter-by-commitish: true +commitish: main +template: | + ## What's Changed + + $CHANGES +categories: + - title: '๐Ÿ’ฅ Breaking API Changes' + when: + label: 'kind/breaking' + - title: '๐Ÿš€ Features & Enhancements' + when: + labels: + - 'kind/enhancement' + - 'kind/feature' + - title: '๐Ÿ› Bug Fixes' + when: + label: 'kind/bug' + - title: '๐Ÿงน Refactor' + when: + label: 'kind/refactor' + - title: '๐Ÿ“ Documentation' + when: + label: 'kind/documentation' + - title: '๐Ÿ“ฆ Dependency Updates' + when: + label: 'kind/dependencies' + collapse-after: 5 +change-template: '* (#$NUMBER) $TITLE by @$AUTHOR' +exclude-labels: + - 'kind/question' + - 'kind/wontfix' + - 'meta/skip-changelog' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..f39a485c0 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: [ '*' ] + pull_request: + branches: [ '*' ] + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + java: [ 8, 11, 17 ] + steps: + - name: Check out code + uses: actions/checkout@v7.0.0 + with: + fetch-depth: 0 + + - name: Setup Java ${{ matrix.java }} + uses: actions/setup-java@v5.3.0 + with: + distribution: temurin + java-version: ${{ matrix.java }} + + - name: Build + run: ./mvnw clean package diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml new file mode 100644 index 000000000..9a019e555 --- /dev/null +++ b/.github/workflows/release-drafter.yml @@ -0,0 +1,21 @@ +name: Release Drafter + +on: + push: + branches: + - main + +permissions: + contents: read + +jobs: + update_release_draft: + permissions: + contents: write # for release-drafter to create a GitHub release + runs-on: ubuntu-latest + steps: + - uses: release-drafter/release-drafter@v7.4.0 + with: + config-name: release-drafter-master.yml + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000..d6fb05f29 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,67 @@ +name: Release + +on: + release: + types: [ published ] + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v7.0.0 + + - name: Set up Java + uses: actions/setup-java@v5.3.0 + with: + java-version: 8 + distribution: temurin + server-id: ossrh + server-username: NEXUS_USERNAME + server-password: NEXUS_PASSWORD + gpg-passphrase: GPG_PASSPHRASE + gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} + + - name: Set artifact version + run: ./mvnw --batch-mode --define=generateBackupPoms=false --define=newVersion=${{ github.event.release.tag_name }} versions:set + + - name: Publish package + run: ./mvnw --batch-mode --activate-profiles=deploy deploy + env: + NEXUS_USERNAME: ${{ secrets.NEXUS_USERNAME }} + NEXUS_PASSWORD: ${{ secrets.NEXUS_PASSWORD }} + GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + + update-versions: + needs: [ publish ] + permissions: + contents: write # for peter-evans/create-pull-request to create branch + pull-requests: write # for peter-evans/create-pull-request to create a PR + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v7.0.0 + with: + ref: master + fetch-depth: 0 + + - name: Update pom.xml version + run: ./mvnw --batch-mode --define=generateBackupPoms=false --define=newVersion=${{ github.event.release.tag_name }} versions:set + + - name: Update Maven version in README.md + run: sed --in-place 's/.*<\/version>/${{ github.event.release.tag_name }}<\/version>/g' README.md + + - name: Show diff + run: git diff + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v8.1.1 + with: + commit-message: Update versions to ${{ github.event.release.tag_name }} + title: Update versions to ${{ github.event.release.tag_name }} + body: Update versions to ${{ github.event.release.tag_name }} + branch: update-versions-${{ github.event.release.tag_name }} + delete-branch: true + labels: | + kind/documentation + meta/skip-changelog diff --git a/.gitignore b/.gitignore index 9d2768778..aee1dd39d 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,12 @@ target .classpath .project .settings/* +.idea +.gradle +classes +/bin +build/ +/.settings/ +/.metadata/ +/.packages +/.dart_tool/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..8dea6c227 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip diff --git a/ANNOUNCEMENT b/ANNOUNCEMENT deleted file mode 100644 index 4bee82219..000000000 --- a/ANNOUNCEMENT +++ /dev/null @@ -1,39 +0,0 @@ -ANNOUNCEMENT: Asterisk-Java 0.3.1 released - -Asterisk-Java 0.3.1, the free Java library for Asterisk PBX integration, -has been released. - -The Asterisk-Java package consists of a set of Java classes that allow -you to easily build Java applications that interact with an Asterisk -PBX Server. Asterisk-Java supports both interfaces that Asterisk -provides for this scenario: The FastAGI protocol and the Manager API. - -Asterisk-Java 0.3.1 is a maintenance release that solves the -following issues: - * [AJ-81] - executeCliCommand() always executes "show voicemail users" - * [AJ-86] - getChannelByName doesn't return the latest channel - * [AJ-80] - getMeetMeRooms() should only return active rooms - * [AJ-68] - Support for Bridge Action - * [AJ-74] - Support Strategy property in QueueParamsEvent - -Asterisk-Java takes advantage of the features of Java 5.0 and therefore -requires a Java Virtual Machine of at least version 1.5.0. - -Asterisk-Java is used in several commercial environments and by -the following Open Source projects: - * Asterisk-JTAPI - JTAPI implementation for Asterisk. - http://asterisk-jtapi.sf.net/ - * Asterisk-IM - A plugin for the Openfire XMPP (jabber) server. It provides - integrated presence between your IM client and phone, notification - of incoming calls by IM and originate calls from supported IM - clients. - http://www.igniterealtime.org/projects/openfire/ - * Asterisk Desktop Manager (ADM) - A desktop application that will allow for automatic on-call volume - reduction, one click dial from clipboard, integrated phonebook - and more. - http://adm.hamnett.org/ - -Asterisk-Java is available under Apache 2.0 license at http://asterisk-java.org diff --git a/CHANGES b/CHANGES deleted file mode 100644 index de254ee1a..000000000 --- a/CHANGES +++ /dev/null @@ -1,145 +0,0 @@ -Asterisk-Java 1.0.0 - Warning: - Values for event properties of type String that match one of the null - literals used by Asterisk are automatically set to null in A-J 1.0.0. - The null literals are: - "", "unknown", "none", "", "-none-", "(none)", - "", "(not set)", "", "n/a", "" and - "(null)". - - -Asterisk-Java 0.3.1 - * [AJ-81] - executeCliCommand() always executes "show voicemail users" - * [AJ-86] - getChannelByName doesn't return the latest channel - * [AJ-79] - Support for the CallWeaver protocol identifier - * [AJ-80] - getMeetMeRooms() should only return active rooms - * [AJ-68] - Support for Bridge Action - * [AJ-74] - Support Strategy property in QueueParamsEvent - * [AJ-78] - Documentation needs thorough examples of the Live API - -Asterisk-Java 0.3 - * [AJ-30] - Fixed version detection when restarting Asterisk - * [AJ-59] - Fixed incorrect class and method names when using JavaLoggingLog - * [AJ-60] - Fixed DefaultManagerConnection.sendEventGeneratingAction() - for Asterisk 1.4.1 - * [AJ-50] - Finished support for Asterisk 1.4 - * [AJ-54] - Fixed AsteriskQueue observer and Park events - * [AJ-55] - Added "videoSupport" and "realtimeDevice" to PeerEntryEvent - * [AJ-56] - Added "callerIdNum" to AbstractChannelEvent - * [AJ-57] - Added "memberName" to AbstractQueueMemberEvent - * [AJ-58] - Added support for OpenPBX - * [AJ-43] - Added support for GetConfig and UpdateConfig actions - * [AJ-62] - Added executeCliCommand() method to AsteriskServer - * [AJ-2] - Updated design doc and tutorial according to AGI changes - -Asterisk-Java 0.3-m2 - * Added getManagerConnection() to AsteriskServer (AJ-41) - * Added timestamp property to ManagerEvent (AJ-35) - * Added QueueSummaryAction, QueueSummaryEvent and - QueueSummaryCompleteEvent (AJ-42) - * Added ZapRestartAction (AJ-45) - * Added PauseMontiorAction and UnpauseMonitorAction and - pauseMontior() and unpauseMonitor() methods to - AsteriskChannel (AJ-44) - * Added AbstractManagerEventListener - -Asterisk-Java 0.3-m1 - * Changed package name from net.sf.asterisk to org.asteriskjava - and renamed AGI classes to Agi to conform to Java coding - standards - * Renamed ManagerEventHandler and ManagerResponseHandler to - ManagerEventListener and SendActionCallback. - * Introduced generics and leveraged other Java5 features like - java.util.concurrent. - * Added SSL support for the Manager API. - * ManagerReader threads are now daemon threads so as soon as - all other threads are terminated the JVM will quit - * Changed log level for message about ManagerReader termination - from INFO to DEBUG - * ManagerConnectionFactory has been simplified. Usage example: - new ManagerConnectionFactory("host", "user", "pass") - .createManagerConnection(); - * Fixed timing bug in ResourceBundleMappingStrategy (AJ-25) - * Fixed interrupt in DefaultManagerConnection (AJ-27) - * Fixed accountCode always being null in AgiRequest - * Fixed synchronization bug when generating internal action ids for - the Manager API - * Fixed synchronous sendAction for responses that are received really - fast, i.e. before the thread is put asleep. - * Fixed ConnectEvent being only fired after a successful - login (AJ-32) - * Fixed no setter for the dnd field when sending - ZapShowChannelsAction (AJ-33) - * Added support for login with eventMask (AJ-28) - * Added support for using non-shared instances AgiScript, i.e. a - new instance is used for each request if you set the - shareInstances property on your MappingStrategy to false. - Default is still to use shared instances (AJ-29) - * Live objects now fire PropertyChangeEvents - * Added extraContext, extraExten, extraPriority properties to - RedirectAction to support BRIstuffed versions of Asterisk (AJ-34) - * Added recordFile and controlStreamFile methods to AgiChannel and - BaseAgiScript - * Added channel variable AJ_AGISTATUS that is set by the AgiServer - to "SUCCESS" if the AgiScript completed successfully, "FAILED" - if it threw an exception or "NOT_FOUND" if the mapping strategy - did not return a script for the requested URL. - * Added MeetMeMuteEvent and muted property for MeetMeUser. - * Added MeetMeMuteAction and MeetMeUnmuteAction. - * Added ParkAction. - * Added PlayDtmfAction and playDtmf() method for AsteriskChannel. - * Added several new event properties for Asterisk 1.4: - - MeetMeEvent: channel and uniqueId - - MeetMeLeaveEvent: callerIdNum, callerIdName and duration - - MeetMeTalkingEvent: status - - StatusEvent: callerIdNum and callerIdName - - OriginateEvent: callerIdNum and callerIdName - - JoinEvent and LeaveEvent: uniqueId - - AgentConnectEvent: brigedChannel - -Asterisk-Java 0.2 - * Added SayDateTimeCommand (AJ-23) - * Added GetFullVariableCommand (AJ-23) - * Added ReceiveTextCommand (AJ-23) - * Changed SetPriorityCommand to support labels (AJ-23) - * Added callingPres, callingAni2, callingTns and callingTon - properties to AGIRequest (AJ-22) - * Fixed CallerId information in AGIRequest for - Asterisk 1.2 (AJ-21) - -Asterisk-Java 0.2-rc2 - * Fixed mapping of Variable property in OriginateAction for - Asterisk 1.2 (AJ-15) - * Added FaxReceived event from spandsp (AJ-20) - * Added SimpleMappingStrategy and AGIServerThread to ease - integration of AGIServer when using Spring Framework - * Timeout for socket connection can now be specified for - the ManagerConnection (AJ-16) - * Added getPort() method to lookup port of an AGIServer (AJ-14) - * Readded getContext(), getExtension(), getPriority() as - convenience methods to Channel (AJ-12) - * Decreased log level for unknown events to INFO (AJ-13) - -Asterisk-Java 0.2-rc1 - * Added Support for the new Actions, Events and Commands - of Asterisk 1.2 - * Fixed getting the uniqueId from a successful originate - in the DefaultAsteriskManager - * Added isConnected() method to ManagerConnection - * Changed ManagerAction to be an interface rather that an - abstract base class. If you extended ManagerAction, please - use AbstractManagerAction instead. - * Added support for event generating Actions, i.e. Actions - that send their result as a series of Event rather than - the usual ManagerResults. See the sendEventGeneratingAction() - methods in ManagerConnection for more information. - * Deprecated AbstractAGIScript in favor of BaseAGIScript. This - allows you write cleaner AGI scripts as you don't have to - pass the channel variable to all methods. - * Added convenience constructors for manager actions - -Asterisk-Java 0.1 - * Added accessors for raw attributes in ManagerResponse - * Fixed bug in action id creation - * Changed logging to use either log4j or java.util.logging - * Fixed ExecCommand diff --git a/README.md b/README.md index da5fca228..10005d85a 100644 --- a/README.md +++ b/README.md @@ -1,68 +1,138 @@ -README for Asterisk-Java -======================== +# Asterisk-Java -INTRODUCTION ------------- +## Introduction -The Asterisk-Java package consists of a set of Java classes that allow you to easily build Java applications that interact with an [Asterisk PBX Server](http://asterisk.org). Asterisk-Java supports both interfaces that Asterisk provides for this scenario: The [FastAGI](https://wiki.asterisk.org/wiki/display/AST/Application_AGI) protocol and the [Manager API](https://wiki.asterisk.org/wiki/display/AST/The+Asterisk+Manager+TCP+IP+API). +The Asterisk-Java package consists of a set of Java classes that allow you to +easily build Java applications that interact with +an [Asterisk PBX Server](https://www.asterisk.org/). +Asterisk-Java supports both interfaces that Asterisk provides for this +scenario: +The [FastAGI](https://docs.asterisk.org/Latest_API/API_Documentation/Dialplan_Applications/AGI/) +protocol and +the [Manager API](https://docs.asterisk.org/Configuration/Interfaces/Asterisk-Manager-Interface-AMI/The-Asterisk-Manager-TCP-IP-API). -The FastAGI implementation supports all commands currently available from Asterisk. +You can find the Java docs for the latest version here: +[Javadoc](https://javadoc.io/doc/org.asteriskjava/asterisk-java/latest) -The Manager API implementation supports receiving events from the Asterisk server (e.g. call progess, registered peers, channel state) and sending actions to Asterisk (e.g. originate call, agent login/logoff, start/stop voice recording). +### FastAGI -A complete list of the available events and actions is available in the javadocs. +FastAGI lets you create a service that manages a call in a similar way to how +a webserver handles an HTTP request. FastAGI can be (and should be) used to +replace dialplan. FastAGI is thousands of times faster than dialplan, easier to +debug and lets you do call control in a language that you are familiar with. -See docs/tutorial.html for examples. +The FastAGI implementation supports all commands currently available from +Asterisk. -GETTING ASTERISK-JAVA ---------------------- +### Manager API -Asterisk-Java is available from http://asterisk-java.org +The Manager API implementation supports receiving events from the Asterisk +server (e.g. call progress, registered peers, channel state) and sending actions +to Asterisk (e.g. originate call, agent login/logoff, start/stop voice +recording). +If you like, the Manager API allows you to start and manipulate calls. A +complete list of the available events and actions is available in the +[documentation](https://javadoc.io/doc/org.asteriskjava/asterisk-java/latest). -INSTALLATION FROM SOURCE ------------------------- +### Activities - git clone https://github.com/srt/asterisk-java.git - cd asterisk-java - mvn install +Activities are new to asterisk-java 2.0. The aim of Activities is to provide a +high level interface to interactions with Asterisk. Whist Activities use both +FastAGI and the Manager API you would normally consider Activities as a +replacement for the Manager API. -After the build is complete, the jar will then be built as target/asterisk-java.jar in the asterisk-java directory. +Activities provide a simple and consistent method of interaction with Asterisk +without having to worry about issues such as connection management and without +having to understand the intricacies of Asterisk Manager Actions and Events. -EXAMPLE -------- +[Getting Started](https://github.com/asterisk-java/asterisk-java/wiki/Getting-Started) -The file 'examples/ExampleCallIn.java' will answer the call and playback the audio file 'tt-monkeys'. +[Tutorial](https://github.com/asterisk-java/asterisk-java/wiki/Tutorial) - import org.asteriskjava.fastagi.AgiChannel; - import org.asteriskjava.fastagi.AgiException; - import org.asteriskjava.fastagi.AgiRequest; - import org.asteriskjava.fastagi.BaseAgiScript; - /* Example incoming call handler - Answer call, speak message */ - public class ExampleCallIn extends BaseAgiScript { - public void service(AgiRequest request, AgiChannel channel) throws AgiException { - answer(); - exec("Playback", "tt-monkeys"); - hangup(); - } - } +[Activities](https://github.com/asterisk-java/asterisk-java/wiki/Activities) -The file 'examples/fastagi-mapping.properties' maps your Asterisk diaplan context to the class you would like to invoke above. +[Examples](https://github.com/asterisk-java/asterisk-java/wiki/Examples) - callin.agi = ExampleCallIn +--- -To compile and run do: +## Getting Asterisk-Java - javac -cp asterisk-java.jar ExampleCallIn.java - java -cp asterisk-java.jar org.asteriskjavafastagi.DefaultAgiServer +Asterisk-Java is available +[on GitHub](https://github.com/asterisk-java/asterisk-java/releases). -SYSTEM REQUIREMENTS -------------------- +### Maven -Asterisk-Java needs a Java Virtual Machine of at least version 1.6 ([Java SE 6.0](http://www.oracle.com/technetwork/java/javase/downloads/index.html)). If you want to build the jar from source, you will -also need [Maven](http://maven.apache.org/). +Asterisk-Java 3.x (Java 1.8 and Asterisk Version 10 thru 23) (master) -LEGAL ------ +```xml -Asterisk-Java is subject to the terms detailed in the license agreement accompanying it. \ No newline at end of file + + org.asteriskjava + asterisk-java + 3.42.2 + +``` + +### Gradle + +```text +implementation group: 'org.asteriskjava', name: 'asterisk-java', version: '3.42.2' +``` + +### Installation from source + +```text +git clone https://github.com/asterisk-java/asterisk-java.git +cd asterisk-java +mvn install +``` + +After the build is complete, the jar will then be built as +`target/asterisk-java.jar` in the `asterisk-java` directory. + +## Example + +The file `examples/ExampleCallIn.java` will answer the call and playback the +audio file 'tt-monkeys'. + +```java +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiRequest; +import org.asteriskjava.fastagi.BaseAgiScript; + +/* Example incoming call handler. Answer call, speak message */ +public class ExampleCallIn extends BaseAgiScript { + public void service(AgiRequest request, AgiChannel channel) throws AgiException { + answer(); + exec("Playback", "tt-monkeys"); + hangup(); + } +} +``` + +The file `examples/fastagi.properties` maps your Asterisk dialplan context to +the class you would like to invoke above. + +```text +callin.agi = ExampleCallIn +``` + +To compile and run: + +```text +javac -cp asterisk-java.jar ExampleCallIn.java +java -cp asterisk-java.jar org.asteriskjava.fastagi.DefaultAgiServer +``` + +## System Requirements + +Asterisk-Java needs a Java Virtual Machine of at least version +1.8 ([Java SE 8.0](https://docs.oracle.com/javase/8/)). +If you want to build the jar from source, you will also +need [Maven](https://maven.apache.org/). + +## Legal + +Asterisk-Java is subject to the terms detailed in the license agreement +accompanying it. diff --git a/atlassian-ide-plugin.xml b/atlassian-ide-plugin.xml deleted file mode 100644 index d48888417..000000000 --- a/atlassian-ide-plugin.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - e88a6130-6bd2-45dd-aa5d-57b845f76d0f - reucon - https://secure.reucon.net/issues - false - - - 68a20e42-e943-4a1d-b807-45cad35b4f73 - reucon - https://secure.reucon.net/build - false - false - false - - - - - - - 89c4100c-3c20-4d7d-8611-0dbe1bee742e - repos - asterisk-java/trunk - e88a6130-6bd2-45dd-aa5d-57b845f76d0f - - \ No newline at end of file diff --git a/bnd.bnd b/bnd.bnd new file mode 100644 index 000000000..a2acf6699 --- /dev/null +++ b/bnd.bnd @@ -0,0 +1,15 @@ +Main-Class: org.asteriskjava.Cli + +Bundle-SymbolicName: org.asteriskjava +Bundle-Name: ${project.name} +Bundle-Description: ${project.description} +Bundle-DocURL: ${project.url} +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt + +-exportcontents: !*.internal.*, * + +Import-Package: \ + !org.asteriskjava.*,\ + org.apache.logging.log4j.*;resolution:=optional,\ + org.slf4j.*;resolution:=optional,\ + * diff --git a/dist/agi/demo.groovy b/dist/agi/demo.groovy deleted file mode 100644 index 49563fa31..000000000 --- a/dist/agi/demo.groovy +++ /dev/null @@ -1,18 +0,0 @@ -// countdown -(10..0).each { digit -> channel.sayNumber(digit.toString()) } - -channel.streamFile('beep'); - -// read a few dtmf digits -while ((digit = channel.waitForDigit(10000)) != 0) -{ - if (digit == '#' || digit == '*') - { - break; - } - channel.sayDigits(digit.toString()); -} - -// beep to say good bye ;) -channel.streamFile('beep'); - diff --git a/dist/agi/demo.js b/dist/agi/demo.js deleted file mode 100644 index 58ade0537..000000000 --- a/dist/agi/demo.js +++ /dev/null @@ -1,23 +0,0 @@ -// countdown -for (var i = 10; i >= 0; i--) -{ - channel.sayNumber(i); -} - -channel.streamFile('beep'); - -// read a few dtmf digits -var code; -while ((code = channel.waitForDigit(10000)) != 0) -{ - var digit = String.fromCharCode(code); - if (digit == '#' || digit == '*') - { - break; - } - channel.sayDigits(digit); -} - -// beep to say good bye ;) -channel.streamFile('beep'); - diff --git a/dist/agi/demo.php b/dist/agi/demo.php deleted file mode 100644 index 3117f8409..000000000 --- a/dist/agi/demo.php +++ /dev/null @@ -1,24 +0,0 @@ -= 0; $i--) -{ - $channel->sayNumber($i); -} - -$channel->streamFile('beep'); - -// read a few dtmf digits -while (($digit = $channel->waitForDigit(10000)) != 0) -{ - if ($digit == '#' || $digit == '*') - { - break; - } - $channel->sayDigits($digit); -} - -// beep to say good bye ;) -$channel->streamFile('beep'); - -?> diff --git a/dist/lib/groovy-all-1.6.2.jar b/dist/lib/groovy-all-1.6.2.jar deleted file mode 100644 index 34051aa35..000000000 Binary files a/dist/lib/groovy-all-1.6.2.jar and /dev/null differ diff --git a/dist/lib/javamail-141.jar b/dist/lib/javamail-141.jar deleted file mode 100644 index 59543774f..000000000 Binary files a/dist/lib/javamail-141.jar and /dev/null differ diff --git a/dist/lib/jruby-complete-1.2.0.jar b/dist/lib/jruby-complete-1.2.0.jar deleted file mode 100644 index 02e447d7b..000000000 Binary files a/dist/lib/jruby-complete-1.2.0.jar and /dev/null differ diff --git a/dist/lib/mysql-connector-java-5.1.7-bin.jar b/dist/lib/mysql-connector-java-5.1.7-bin.jar deleted file mode 100644 index ebfe06861..000000000 Binary files a/dist/lib/mysql-connector-java-5.1.7-bin.jar and /dev/null differ diff --git a/dist/lib/quercus-3.2.1.jar b/dist/lib/quercus-3.2.1.jar deleted file mode 100644 index 1771160a6..000000000 Binary files a/dist/lib/quercus-3.2.1.jar and /dev/null differ diff --git a/dist/lib/resin-util-3.2.1.jar b/dist/lib/resin-util-3.2.1.jar deleted file mode 100644 index 66a46885a..000000000 Binary files a/dist/lib/resin-util-3.2.1.jar and /dev/null differ diff --git a/dist/lib/servlet-api-2.5.jar b/dist/lib/servlet-api-2.5.jar deleted file mode 100644 index 4729d6ed7..000000000 Binary files a/dist/lib/servlet-api-2.5.jar and /dev/null differ diff --git a/examples/fastagi-mapping.properties b/examples/fastagi-mapping.properties deleted file mode 100644 index 916b40c85..000000000 --- a/examples/fastagi-mapping.properties +++ /dev/null @@ -1 +0,0 @@ -callin.agi = ExampleCallIn \ No newline at end of file diff --git a/lib/clover/clover.license b/lib/clover/clover.license deleted file mode 100644 index 0731f52df..000000000 --- a/lib/clover/clover.license +++ /dev/null @@ -1,164 +0,0 @@ -Product: Clover -License: Open Source License, 0.x, 1.x -Issued: Thu Oct 21 2004 21:27:21 CDT -Expiry: Never -Key: 7e1c2ed27ee858f42adedd953 -Name: Stefan Reuter -Org: asterisk-java -Certificate: AAABsm+Ow8B7/zEbxOMqqKwwrdpP+a1COmJGHco7sCNLjHkHnajPF+dQW -Ct12PMy0uml0s9xuus5wKngJ9OFk5XFeh01dzQF66bhXH1bvegLfvja3Kle6BYtDv4LZgE -gk3E0aJN4IbgTn+TgUckSevXDR4KzK77NWJfrVzkxV3/Jer0jWuM7QJbvwkyoXjNEVc/ye -OTlpI6MQPLOI4Og5zfT4dHD72UJcFEgGvSx6kEeWPn+RGX8xt3GVb8MJ1ywMWYUIcFWe2m -JfmT8OoDi6VDKGj/p0gCEpn+6zEmWuUoleg59zSy9cEHoJVDLjoVAqhUmFnDYl2Tk9LLP3 -3Gn0yLWqYQk2fzWw7d6BiJrcX/2seoMHkW4+l9l5JKzy0XyFHUIsTFzbjbeTmZpk24hkje -f9PFP3hFn89RVjsozstxYnbhGeHhQZNk/uG0ftnAR0bXdFv0ZYFU0t/597/Kxw9gpyss1w -r/rdMDm0c+7KgckZjxPrfvvFgAFuutYe//Ol8Be8lguE7Fkews81gIyc4d0NvU+gu7qUZo -WOOjTVMuDM7TJWIHlKT54UGPELrE8E/I7XICOJa8WipV+qmMXPXk/q2oiu1udzSy7Tmvyi -hZ85yCnuH9DBnpBZRbS88AtM6Lje56JhNykODYtRipYlvD8vlukR+/c4sBWNkJlYG7FU/o -SP8Hrnh8VSFASymIfLGF/6v+wzRsoiAyO3MlQPDajIsCnmFIFanUVG453AmktJwxbKU0= -License Agreement: CLOVER VERSION 1 (ONE) SOFTWARE LICENSE AGREEMENT - -1. Licenses and Software - -Cortex eBusiness Pty Ltd, an Australian Proprietary Limited Company -("CENQUA") hereby grants to the purchaser (the "LICENSEE") a limited, -revocable, worldwide, non-exclusive, non-transferable, -non-sublicensable license to use the Clover version 1 (one) software -(the "Software"), including any minor upgrades thereof during the Term -(hereinafter defined) up to, but not including the next major version -of the Software. The licensee shall not, or knowingly allow others to, -reverse engineer, decompile, disassemble, modify, adapt, create -derivative works from or otherwise attempt to derive source code from -the Software provided. And, in accordance with the terms and -conditions of this Software License Agreement (the "Agreement"), the -Software shall be used solely by the licensed users in accordance with -the following edition specific conditions: - -a) Server Edition - -A Server Edition license entitles the Licensee to execute one instance -of Clover Server Edition on one (1) machine for the purposes of -instrumenting source code and generating reports. There are no -limitations on the use of the instrumented source code or generated -reports produced by Server Edition. - -b) Workstation Edition - -A Workstation Edition license entitles the licensee to use Clover -Workstation Edition on one (1) machine by one (1) individual end -user. Workstation Edition does not permit the generation of reports -for distribution. - -c) Team Edition - -A Team Edition license entitles the licensee to use Clover Team -edition on any number of machines solely by the licensed number of -users. Reports generated by Clover Team Edition are strictly for use -only by the licensed number of individual end users. - -2. License Fee - -In exchange for the License(s), the Licensee shall pay to Cenqua a -one-time, up front, non-refundable license fee. At the sole discretion -of Cenqua this fee will be waived for non-commercial -projects. Notwithstanding the Licensee's payment of the License Fee, -Cenqua reserves the right to terminate the License if Cenqua discovers -that the Licensee and/or the Licensee's use of the Software is in -breach of this Agreement. - -3. Proprietary Rights - -Cenqua will retain all right, title and interest in and to the -Software, all copies thereof, and Cenqua website(s), software, and -other intellectual property, including, but not limited to, ownership -of all copyrights, look and feel, trademark rights, design rights, -trade secret rights and any and all other intellectual property and -other proprietary rights therein. The Licensee will not directly or -indirectly obtain or attempt to obtain at any time, any right, title -or interest by registration or otherwise in or to the trademarks, -service marks, copyrights, trade names, symbols, logos or designations -or other intellectual property rights owned or used by Cenqua. All -technical manuals or other information provided by Cenqua to the -Licensee shall be the sole property of Cenqua. - -4. Term and Termination - -Subject to the other provisions hereof, this Agreement shall commence -upon the Licensee's opting into this Agreement and continue until the -Licensee discontinues use of the Software or the Agreement terminates -automatically upon the Licensee's breach of any term or condition of -this Agreement (the "Term"). Upon any such termination, the Licensee -will delete the Software immediately. - -5. Copying & Transfer - -The Licensee may copy the Software for back-up purposes only. The -Licensee may not assign or otherwise transfer the Software to any -third party. - -6. Specific Disclaimer of Warranty and Limitation of Liability - -THE SOFTWARE IS PROVIDED WITHOUT WARRANTY OF ANY KIND. CENQUA -DISCLAIMS ALL WARRANTIES, EXPRESSED OR IMPLIED, INCLUDING BUT NOT -LIMITED TO THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE. CENQUA WILL NOT BE LIABLE FOR ANY DAMAGES -ASSOCIATED WITH THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ORDINARY, -INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING -BUT NOT LIMITED TO DAMAGES RELATING TO LOST DATA OR LOST PROFITS, EVEN -IF CENQUA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. Warranties and Representations - -Licensee Indemnification. CENQUA agrees to indemnify, defend and hold -the Licensee harmless from and against any and all liabilities, -damages, losses, claims, costs, and expenses (including reasonable -legal fees) arising out of or resulting from the Software or the use -thereof infringing upon, misappropriating or violating any patents, -copyrights, trademarks, or trade secret rights or other proprietary -rights of persons, firms or entities who are not parties to this -Agreement. - -CENQUA Indemnification. The Licensee warrants and represents that the -Licensee's actions with regard to the Software will be in compliance -with all applicable laws; and the Licensee agrees to indemnify, -defend, and hold CENQUA harmless from and against any and all -liabilities, damages, losses, claims, costs, and expenses (including -reasonable legal fees) arising out of or resulting from the -Licensee's failure to observe the use restrictions set forth herein. - -8. Publicity - -The Licensee grants permission for CENQUA to use Licensee's name -solely in customer lists. CENQUA shall not, without prior consent in -writing, use the Licensee's name, or that of its affiliates, in any -form with the specific exception of customer lists. CENQUA agrees to -remove Licensee's name from any and all materials within 7 days if -notified by the Licensee in writing. - -9. Governing Law - -This Agreement shall be governed by the laws of New South Wales, -Australia. - -10. Independent Contractors - -The parties are independent contractors with respect to each other, -and nothing in this Agreement shall be construed as creating an -employer-employee relationship, a partnership, agency relationship or -a joint venture between the parties. - -11. Assignment - -This Agreement is not assignable or transferable by the Licensee. -CENQUA in its sole discretion may transfer a license to a third party -at the written request of the Licensee. - -12. Entire Agreement - -This Agreement constitutes the entire agreement between the parties -concerning the Licensee's use of the Software. This Agreement -supersedes any prior verbal understanding between the parties and any -Licensee purchase order or other ordering document, regardless of -whether such document is received by CENQUA before or after execution -of this Agreement. This Agreement may be amended only in writing by -CENQUA. diff --git a/mvnw b/mvnw new file mode 100755 index 000000000..bd8896bf2 --- /dev/null +++ b/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.4 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 000000000..5761d9489 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,189 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml index 4ef4d4426..30bea761a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,15 +1,27 @@ 4.0.0 - - org.asteriskjava - asterisk-java-parent - 2 - + + org.asteriskjava asterisk-java + 3.43.0-SNAPSHOT + Asterisk-Java - 1.0.0.CI-SNAPSHOT The free Java library for Asterisk PBX integration. + https://github.com/asterisk-java/asterisk-java 2004 + + + + The Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + + + + + GitHub + https://github.com/asterisk-java/asterisk-java/issues + + Stefan Reuter @@ -37,191 +49,274 @@ Bureau of Economic and Business Research, University of Florida -5 + + S. Brett Sutton + bsutton + bsutton at noojee.com.au + Noojee Telephony Solutions Pty Ltd + +10 + + + Zoumana TRAORE + zoumhussein + github at zoumanatraore dot fr + +1 + + + Robert Sutton + rsutton + rsutton at noojee.com.au + +10 + + + Piotr Olaszewski + piotrooo + piotroo89 at gmail.com + +1 + + + Sean Bright + seanbright + sean at seanbright.com + -5 + + - scm:git:git://github.com/srt/asterisk-java.git - scm:git:git@github.com:srt/asterisk-java.git - + scm:git:git@github.com:asterisk-java/asterisk-java.git + scm:git:git@github.com:asterisk-java/asterisk-java.git + https://github.com/asterisk-java/asterisk-java + HEAD + + + + UTF-8 + + + + + com.google.guava + guava + 33.5.0-jre + + + org.slf4j + slf4j-api + 2.0.17 + + + org.apache.logging.log4j + log4j-core + 2.25.4 + + + org.reflections + reflections + 0.10.2 + + + + org.junit.jupiter + junit-jupiter + 5.14.3 + test + + + org.assertj + assertj-core + 3.27.7 + test + + + org.mockito + mockito-core + 4.10.0 + test + + + org.slf4j + slf4j-simple + 2.0.17 + test + + + org.apache.maven.plugins maven-jar-plugin - 2.3 + 3.5.0 + ${project.build.outputDirectory}/META-INF/MANIFEST.MF - org.asteriskjava.Cli + true - - . - 2 - org.asteriskjava - ${project.version} - ${project.name} - ${project.description} - reucon - ${project.url} - -org.asteriskjava;version="${project.version}", -org.asteriskjava.config;version="${project.version}", -org.asteriskjava.config.dialplan;version="${project.version}", -org.asteriskjava.fastagi;version="${project.version}", -org.asteriskjava.fastagi.command;version="${project.version}", -org.asteriskjava.fastagi.internal;version="${project.version}", -org.asteriskjava.fastagi.reply;version="${project.version}", -org.asteriskjava.manager;version="${project.version}", -org.asteriskjava.manager.action;version="${project.version}", -org.asteriskjava.manager.event;version="${project.version}", -org.asteriskjava.manager.internal;version="${project.version}", -org.asteriskjava.manager.response;version="${project.version}", -org.asteriskjava.manager.util;version="${project.version}", -org.asteriskjava.live;version="${project.version}", -org.asteriskjava.live.internal;version="${project.version}", -org.asteriskjava.util;version="${project.version}", -org.asteriskjava.util.internal;version="${project.version}" - - -javax.net, -org.slf4j;resolution:=optional, -org.apache.log4j;resolution:=optional - - - maven-assembly-plugin - 2.2-beta-5 - - - src/main/assembly/bin.xml - - + biz.aQute.bnd + bnd-maven-plugin + 6.4.0 - make-assembly - package - attached + bnd-process - org.codehaus.mojo - cobertura-maven-plugin - 2.3 - - - ${project.artifactId} - - - - org.easymock - easymock - 2.5.2 - test - - - junit - junit - 4.8.2 - test - - - log4j - log4j - 1.2.16 - compile - - - org.slf4j - slf4j-api - 1.5.11 - compile - - - ch.qos.logback - logback-classic - 0.9.20 - test - - - - - - maven-javadoc-plugin - 2.7 + org.apache.maven.plugins + maven-release-plugin + 3.3.1 - - - Core Packages - - org.asteriskjava:org.asteriskjava.fastagi:org.asteriskjava.fastagi.command:org.asteriskjava.fastagi.reply:org.asteriskjava.manager:org.asteriskjava.manager.action:org.asteriskjava.manager.response:org.asteriskjava.manager.event:org.asteriskjava.live:org.asteriskjava.util - - - - Internal Packages - - org.asteriskjava.fastagi.internal:org.asteriskjava.manager.internal:org.asteriskjava.live.internal:org.asteriskjava.util.internal - - - -
${project.name}
+ true + false + release + deploy
- org.codehaus.mojo - cobertura-maven-plugin - 2.3 + org.apache.maven.plugins + maven-compiler-plugin + 3.15.0 - - html - xml - + 1.8 + 1.8 org.apache.maven.plugins - maven-jxr-plugin - 2.2 - - - org.apache.maven.plugins - maven-surefire-report-plugin - 2.6 + maven-surefire-plugin + 3.5.5 org.apache.maven.plugins - maven-changelog-plugin - 2.2 - - - org.apache.maven.plugins - maven-pmd-plugin - 2.5 + maven-assembly-plugin + 3.8.0 - 1.6 - 100 - true - - /rulesets/basic.xml - + + ${project.basedir}/src/main/assembly/bin.xml + + + + make-assembly + package + + single + + + - - org.codehaus.mojo - findbugs-maven-plugin - 2.3.1 - -
-
+ ${project.artifactId} + + + + + deploy + + + + org.apache.maven.plugins + maven-source-plugin + 3.4.0 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.12.0 + + + attach-javadocs + + jar + + + + + none + -Xdoclint:none + + -Xdoclint:none + + + + + Core Packages + + org.asteriskjava:org.asteriskjava.fastagi:org.asteriskjava.fastagi.command:org.asteriskjava.fastagi.reply:org.asteriskjava.manager:org.asteriskjava.manager.action:org.asteriskjava.manager.response:org.asteriskjava.manager.event:org.asteriskjava.live:org.asteriskjava.util + + + + Internal Packages + + org.asteriskjava.fastagi.internal:org.asteriskjava.manager.internal:org.asteriskjava.live.internal:org.asteriskjava.util.internal + + + +
${project.name}
+
+
+ + + org.apache.maven.plugins + maven-gpg-plugin + 3.2.8 + + + sign-artifacts + verify + + sign + + + + + --pinentry-mode + loopback + + EA919AF2 + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.7.0 + true + + ossrh + https://ossrh-staging-api.central.sonatype.com/ + true + + +
+
+
+
+ + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2 + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + +
diff --git a/src/integrationtest/org/asteriskjava/fastagi/GetDataScript.java b/src/integrationtest/org/asteriskjava/fastagi/GetDataScript.java index d46c523ef..d6d3b1cb3 100644 --- a/src/integrationtest/org/asteriskjava/fastagi/GetDataScript.java +++ b/src/integrationtest/org/asteriskjava/fastagi/GetDataScript.java @@ -10,7 +10,7 @@ public class GetDataScript extends BaseAgiScript public void service(AgiRequest request, AgiChannel channel) throws AgiException { channel.streamFile("tt-monkeys"); - channel.sayDateTime(new Date().getTime()); + channel.sayDateTime(System.currentTimeMillis()); } public static void main(String[] args) throws Exception diff --git a/src/integrationtest/org/asteriskjava/fastagi/HangupTest.java b/src/integrationtest/org/asteriskjava/fastagi/HangupTest.java index 5b1ec320d..cb0abe5ec 100644 --- a/src/integrationtest/org/asteriskjava/fastagi/HangupTest.java +++ b/src/integrationtest/org/asteriskjava/fastagi/HangupTest.java @@ -10,7 +10,7 @@ public class HangupTest extends BaseAgiScript { - private Logger logger = Logger.getLogger(HangupTest.class); + private Logger logger = LogFactory.getLog(getClass()); public void service(AgiRequest request, AgiChannel channel) throws AgiException { diff --git a/src/integrationtest/org/asteriskjava/live/OriginateCauseTest.java b/src/integrationtest/org/asteriskjava/live/OriginateCauseTest.java index e8c696353..313b32911 100644 --- a/src/integrationtest/org/asteriskjava/live/OriginateCauseTest.java +++ b/src/integrationtest/org/asteriskjava/live/OriginateCauseTest.java @@ -84,8 +84,7 @@ public void run() } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); + e.printStackTrace(); } } }, 10, TimeUnit.SECONDS); diff --git a/src/integrationtest/org/asteriskjava/live/OriginateTest.java b/src/integrationtest/org/asteriskjava/live/OriginateTest.java index 33bdf8247..31c135efe 100644 --- a/src/integrationtest/org/asteriskjava/live/OriginateTest.java +++ b/src/integrationtest/org/asteriskjava/live/OriginateTest.java @@ -73,7 +73,6 @@ public void run() } catch (Exception e) { - // TODO Auto-generated catch block e.printStackTrace(); } } diff --git a/src/main/assembly/bin.xml b/src/main/assembly/bin.xml index 0a2f74335..68314d33e 100644 --- a/src/main/assembly/bin.xml +++ b/src/main/assembly/bin.xml @@ -15,11 +15,11 @@ dist - / + ./ target - / + ./ *.jar diff --git a/src/main/java/org/asteriskjava/AsteriskVersion.java b/src/main/java/org/asteriskjava/AsteriskVersion.java index 1c4c27ae8..051141420 100644 --- a/src/main/java/org/asteriskjava/AsteriskVersion.java +++ b/src/main/java/org/asteriskjava/AsteriskVersion.java @@ -17,6 +17,7 @@ package org.asteriskjava; import java.io.Serializable; +import java.util.regex.Pattern; /** * Represents the version of an Asterisk server. @@ -25,10 +26,30 @@ * @version $Id$ * @since 0.2 */ -public class AsteriskVersion implements Comparable, Serializable -{ +public class AsteriskVersion implements Comparable, Serializable { + private static final String VERSION_PATTERN_DEV = "^\\s*Asterisk GIT-master-.*"; + + private static final String VERSION_PATTERN_23 = "^\\s*Asterisk (GIT-)?23[-. ].*"; + private static final String VERSION_PATTERN_22 = "^\\s*Asterisk (GIT-)?22[-. ].*"; + private static final String VERSION_PATTERN_21 = "^\\s*Asterisk (GIT-)?21[-. ].*"; + private static final String VERSION_PATTERN_20 = "^\\s*Asterisk (GIT-)?20[-. ].*"; + private static final String VERSION_PATTERN_19 = "^\\s*Asterisk (GIT-)?19[-. ].*"; + private static final String VERSION_PATTERN_18 = "^\\s*Asterisk (GIT-)?18[-. ].*"; + private static final String VERSION_PATTERN_17 = "^\\s*Asterisk (GIT-)?17[-. ].*"; + private static final String VERSION_PATTERN_16 = "^\\s*Asterisk (GIT-)?16[-. ].*"; + private static final String VERSION_PATTERN_15 = "^\\s*Asterisk (GIT-)?15[-. ].*"; + private static final String VERSION_PATTERN_14 = "^\\s*Asterisk (GIT-)?14[-. ].*"; + private static final String VERSION_PATTERN_13 = "^\\s*Asterisk ((SVN-branch|GIT)-)?13[-. ].*"; private final int version; private final String versionString; + private final Pattern patterns[]; + + private static final String VERSION_PATTERN_CERTIFIED_22 = "^\\s*Asterisk certified-(GIT-)?22[-. ].*"; + private static final String VERSION_PATTERN_CERTIFIED_20 = "^\\s*Asterisk certified-(GIT-)?20[-. ].*"; + private static final String VERSION_PATTERN_CERTIFIED_18 = "^\\s*Asterisk certified[-/](GIT-)?18[-. ].*"; + private static final String VERSION_PATTERN_CERTIFIED_16 = "^\\s*Asterisk certified/(GIT-)?16[-. ].*"; + private static final String VERSION_PATTERN_CERTIFIED_13 = "^\\s*Asterisk certified/((SVN-branch|GIT)-)?13[-. ].*"; + /** * Represents the Asterisk 1.0 series. @@ -53,65 +74,159 @@ public class AsteriskVersion implements Comparable, Serializabl * @since 1.0.0 */ public static final AsteriskVersion ASTERISK_1_6 = new AsteriskVersion(160, "Asterisk 1.6"); - + /** * Represents the Asterisk 1.8 series. * * @since 1.0.0 */ public static final AsteriskVersion ASTERISK_1_8 = new AsteriskVersion(180, "Asterisk 1.8"); + + /** + * Represents the Asterisk 10 series. + * + * @since 1.0.0 + */ + public static final AsteriskVersion ASTERISK_10 = new AsteriskVersion(1000, "Asterisk 10"); + + /** + * Represents the Asterisk 11 series. + * + * @since 1.0.0 + */ + public static final AsteriskVersion ASTERISK_11 = new AsteriskVersion(1100, "Asterisk 11"); + + /** + * Represents the Asterisk 12 series. + * + * @since 1.0.0 + */ + public static final AsteriskVersion ASTERISK_12 = new AsteriskVersion(1200, "Asterisk 12"); + + /** + * Represents the Asterisk 13 series. + * + * @since 1.0.0 + */ + public static final AsteriskVersion ASTERISK_13 = new AsteriskVersion(1300, "Asterisk 13", VERSION_PATTERN_13, + VERSION_PATTERN_CERTIFIED_13); + + /** + * Represents the Asterisk 14 series. + * + * @since 1.1.0 + */ + public static final AsteriskVersion ASTERISK_14 = new AsteriskVersion(1400, "Asterisk 14", VERSION_PATTERN_14); + + /** + * Represents the Asterisk 15 series. + * + * @since 2.1.0 + */ + public static final AsteriskVersion ASTERISK_15 = new AsteriskVersion(1500, "Asterisk 15", VERSION_PATTERN_15); + + /** + * Represents the Asterisk 16 series. + * + * @since 2.1.0 + */ + public static final AsteriskVersion ASTERISK_16 = new AsteriskVersion(1600, "Asterisk 16", VERSION_PATTERN_16, VERSION_PATTERN_CERTIFIED_16); + + /** + * Represents the Asterisk 17 series. + * + * @since 3.7.0 + */ + public static final AsteriskVersion ASTERISK_17 = new AsteriskVersion(1700, "Asterisk 17", VERSION_PATTERN_17); + + /** + * Represents the Asterisk 18 series. + * + * @since 3.13.0 + */ + public static final AsteriskVersion ASTERISK_18 = new AsteriskVersion(1800, "Asterisk 18", VERSION_PATTERN_18, VERSION_PATTERN_CERTIFIED_18); + + /** + * Represents the Asterisk 19 series. + * + * @since 3.36.2 + */ + public static final AsteriskVersion ASTERISK_19 = new AsteriskVersion(1900, "Asterisk 19", VERSION_PATTERN_19); + + /** + * Represents the Asterisk 20 series. + * + * @since 3.36.2 + */ + public static final AsteriskVersion ASTERISK_20 = new AsteriskVersion(2000, "Asterisk 20", VERSION_PATTERN_20, VERSION_PATTERN_CERTIFIED_20); + + /** + * Represents the Asterisk 21 series. + * + * @since 3.40.0 + */ + public static final AsteriskVersion ASTERISK_21 = new AsteriskVersion(2100, "Asterisk 21", VERSION_PATTERN_21); + + /** + * Represents the Asterisk 22 series. + * + * @since 3.40.0 + */ + public static final AsteriskVersion ASTERISK_22 = new AsteriskVersion(2200, "Asterisk 22", VERSION_PATTERN_22, VERSION_PATTERN_CERTIFIED_22); + + /** + * Represents the Asterisk 23 series. + * + * @since 3.40.0 + */ + public static final AsteriskVersion ASTERISK_23 = new AsteriskVersion(2300, "Asterisk 23", VERSION_PATTERN_23, VERSION_PATTERN_DEV); + + private static final AsteriskVersion knownVersions[] = new AsteriskVersion[]{ + ASTERISK_23, ASTERISK_22, ASTERISK_21, ASTERISK_20, ASTERISK_19, ASTERISK_18, ASTERISK_17, ASTERISK_16, + ASTERISK_15, ASTERISK_14, ASTERISK_13, ASTERISK_12, ASTERISK_11, ASTERISK_10, ASTERISK_1_8, ASTERISK_1_6 + }; + + // current debian stable version, as of 09/10/2018 + public static final AsteriskVersion DEFAULT_VERSION = ASTERISK_16; + /** * Serial version identifier. */ private static final long serialVersionUID = 1L; - private AsteriskVersion(int version, String versionString) - { + private AsteriskVersion(int version, String versionString, String... patterns) { this.version = version; this.versionString = versionString; + + this.patterns = new Pattern[patterns.length]; + int i = 0; + for (String pattern : patterns) { + this.patterns[i++] = Pattern.compile(pattern); + } } /** - * Returns true if this version is equal to or higher than - * the given version. + * Returns true if this version is equal to or higher than the + * given version. * * @param o the version to compare to - * @return true if this version is equal to or higher than - * the given version, false otherwise. + * @return true if this version is equal to or higher than the + * given version, false otherwise. */ - public boolean isAtLeast(AsteriskVersion o) - { + public boolean isAtLeast(AsteriskVersion o) { return version >= o.version; } - public int compareTo(AsteriskVersion o) - { - int otherVersion; - - otherVersion = o.version; - if (version < otherVersion) - { - return -1; - } - else if (version > otherVersion) - { - return 1; - } - else - { - return 0; - } + public int compareTo(AsteriskVersion o) { + return Integer.compare(version, o.version); } @Override - public boolean equals(Object o) - { - if (this == o) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } @@ -121,14 +236,31 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { return version; } @Override - public String toString() - { + public String toString() { return versionString; } + + /** + * Determine the Asterisk version from the string returned by Asterisk. The + * string should contain "Asterisk " followed by a version number. + * + * @param coreLine + * @return the detected version, or null if unknown + */ + public static AsteriskVersion getDetermineVersionFromString(String coreLine) { + for (AsteriskVersion version : knownVersions) { + for (Pattern pattern : version.patterns) { + if (pattern.matcher(coreLine).matches()) { + return version; + } + } + } + + return null; + } } diff --git a/src/main/java/org/asteriskjava/Cli.java b/src/main/java/org/asteriskjava/Cli.java index b74e76ef0..56d2f2857 100644 --- a/src/main/java/org/asteriskjava/Cli.java +++ b/src/main/java/org/asteriskjava/Cli.java @@ -1,27 +1,29 @@ package org.asteriskjava; -import org.asteriskjava.fastagi.DefaultAgiServer; - import java.io.IOException; import java.io.InputStream; import java.util.Properties; +import org.asteriskjava.fastagi.DefaultAgiServer; + /** - * Simple command line interface for Asterisk-Java. This class is run when Asterisk-Java is started - * with {@code java -jar asterisk-java.jar}. It is configured as Main-Class in the manifest.

+ * Simple command line interface for Asterisk-Java. This class is run when + * Asterisk-Java is started with {@code java -jar asterisk-java.jar}. It is + * configured as Main-Class in the manifest. + *

* The command line interface supports the following options: *

- *
{@code -a}, {@code -agi [port]}
+ *
{@code -a}, {@code -agi [port]} + *
*
Starts a FastAGI server
- * - *
{@code -h}, {@code -help}
+ *
{@code -h}, {@code -help} + *
*
Displays the available options
- * *
{@code -v}, {@code -version}
*
Displays the version of Asterisk-Java
*
* If no option is given a FastAGI server is started on the default port. - * + * * @since 1.0.0 */ public class Cli @@ -50,7 +52,7 @@ else if ("-a".equals(arg) || "-agi".equals(arg)) Integer port = null; try { - port = new Integer(args[1]); + port = Integer.parseInt(args[1], 10); } catch (NumberFormatException e) { diff --git a/src/main/java/org/asteriskjava/config/Category.java b/src/main/java/org/asteriskjava/config/Category.java index 4ff376804..4ffd86036 100644 --- a/src/main/java/org/asteriskjava/config/Category.java +++ b/src/main/java/org/asteriskjava/config/Category.java @@ -1,35 +1,27 @@ package org.asteriskjava.config; -import java.util.List; -import java.util.Iterator; import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; -/** - * - */ -public class Category extends ConfigElement -{ +public class Category extends ConfigElement { private String name; private boolean template; - private final List baseCategories = new ArrayList(); - private final List elements = new ArrayList(); + private final List baseCategories = new ArrayList<>(); + private final List elements = new ArrayList<>(); /** * The last object in the list will get assigned any trailing comments when EOF is hit. */ //private String trailingComment; - - public Category(String name) - { - if (name == null) - { + public Category(String name) { + if (name == null) { throw new IllegalArgumentException("Name must not be null"); } this.name = name; } - public Category(String filename, int lineno, String name) - { + public Category(String filename, int lineno, String name) { super(filename, lineno); this.name = name; } @@ -39,8 +31,7 @@ public Category(String filename, int lineno, String name) * * @return the name of this category. */ - public String getName() - { + public String getName() { return name; } @@ -49,13 +40,11 @@ public String getName() * * @return true if this category is a template, false otherwise. */ - public boolean isTemplate() - { + public boolean isTemplate() { return template; } - void markAsTemplate() - { + void markAsTemplate() { template = true; } @@ -64,38 +53,31 @@ void markAsTemplate() * * @return a list of categories this category inherits from, never null. */ - public List getBaseCategories() - { + public List getBaseCategories() { return baseCategories; } - void addBaseCategory(Category baseCategory) - { + void addBaseCategory(Category baseCategory) { baseCategories.add(baseCategory); } - public List getElements() - { + public List getElements() { return elements; } - public void addElement(ConfigElement element) - { - if (element instanceof Category) - { + public void addElement(ConfigElement element) { + if (element instanceof Category) { throw new IllegalArgumentException("Nested categories are not allowed"); } elements.add(element); } - public String format() - { + public String format() { StringBuilder sb = new StringBuilder(); format(sb); - for (ConfigElement e : elements) - { + for (ConfigElement e : elements) { sb.append("\n"); e.format(sb); } @@ -103,26 +85,20 @@ public String format() } @Override - protected StringBuilder rawFormat(StringBuilder sb) - { + protected StringBuilder rawFormat(StringBuilder sb) { sb.append("[").append(name).append("]"); - if (isTemplate() || !getBaseCategories().isEmpty()) - { + if (isTemplate() || !getBaseCategories().isEmpty()) { sb.append("("); - if (isTemplate()) - { + if (isTemplate()) { sb.append("!"); - if (!getBaseCategories().isEmpty()) - { + if (!getBaseCategories().isEmpty()) { sb.append(","); } } Iterator inheritsFromIterator = getBaseCategories().iterator(); - while (inheritsFromIterator.hasNext()) - { + while (inheritsFromIterator.hasNext()) { sb.append(inheritsFromIterator.next().getName()); - if (inheritsFromIterator.hasNext()) - { + if (inheritsFromIterator.hasNext()) { sb.append(","); } } @@ -131,10 +107,9 @@ protected StringBuilder rawFormat(StringBuilder sb) return sb; } - + @Override - public String toString() - { + public String toString() { return name; } } diff --git a/src/main/java/org/asteriskjava/config/ConfigDirective.java b/src/main/java/org/asteriskjava/config/ConfigDirective.java index 0950027a8..289341bbd 100644 --- a/src/main/java/org/asteriskjava/config/ConfigDirective.java +++ b/src/main/java/org/asteriskjava/config/ConfigDirective.java @@ -1,13 +1,10 @@ package org.asteriskjava.config; -public abstract class ConfigDirective extends ConfigElement -{ - protected ConfigDirective() - { +public abstract class ConfigDirective extends ConfigElement { + protected ConfigDirective() { } - protected ConfigDirective(String filename, int lineno) - { + protected ConfigDirective(String filename, int lineno) { super(filename, lineno); } } diff --git a/src/main/java/org/asteriskjava/config/ConfigElement.java b/src/main/java/org/asteriskjava/config/ConfigElement.java index f1ccb80cf..3f6fbaac6 100644 --- a/src/main/java/org/asteriskjava/config/ConfigElement.java +++ b/src/main/java/org/asteriskjava/config/ConfigElement.java @@ -1,7 +1,6 @@ package org.asteriskjava.config; -public abstract class ConfigElement -{ +public abstract class ConfigElement { /** * Name of the file the category was read from. */ @@ -14,67 +13,54 @@ public abstract class ConfigElement private String preComment; private String samelineComment; - protected ConfigElement() - { + protected ConfigElement() { } - protected ConfigElement(String filename, int lineno) - { + protected ConfigElement(String filename, int lineno) { this.filename = filename; this.lineno = lineno; } - public String getFileName() - { + public String getFileName() { return filename; } - public void setFileName(String filename) - { + public void setFileName(String filename) { this.filename = filename; } - public int getLineNumber() - { + public int getLineNumber() { return lineno; } - void setLineNumber(int lineno) - { + void setLineNumber(int lineno) { this.lineno = lineno; } - public String getPreComment() - { + public String getPreComment() { return preComment; } - public void setPreComment(String preComment) - { + public void setPreComment(String preComment) { this.preComment = preComment; } - public String getComment() - { + public String getComment() { return samelineComment; } - public void setComment(String samelineComment) - { + public void setComment(String samelineComment) { this.samelineComment = samelineComment; } - protected StringBuilder format(StringBuilder sb) - { - if (preComment != null && preComment.length() != 0) - { + protected StringBuilder format(StringBuilder sb) { + if (preComment != null && preComment.length() != 0) { sb.append(preComment); } rawFormat(sb); - if (samelineComment != null && samelineComment.length() != 0) - { + if (samelineComment != null && samelineComment.length() != 0) { sb.append(" ; ").append(samelineComment); } diff --git a/src/main/java/org/asteriskjava/config/ConfigFile.java b/src/main/java/org/asteriskjava/config/ConfigFile.java index b77095b72..08ff6e474 100644 --- a/src/main/java/org/asteriskjava/config/ConfigFile.java +++ b/src/main/java/org/asteriskjava/config/ConfigFile.java @@ -16,8 +16,8 @@ */ package org.asteriskjava.config; -import java.util.Map; import java.util.List; +import java.util.Map; /** * An Asterisk configuration file. @@ -26,8 +26,7 @@ * @version $Id$ * @since 1.0.0 */ -public interface ConfigFile -{ +public interface ConfigFile { /** * Returns the filename. * @@ -45,4 +44,4 @@ public interface ConfigFile String getValue(String category, String key); List getValues(String category, String key); -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/config/ConfigFileImpl.java b/src/main/java/org/asteriskjava/config/ConfigFileImpl.java index 8cfd1e5ad..f4510d774 100644 --- a/src/main/java/org/asteriskjava/config/ConfigFileImpl.java +++ b/src/main/java/org/asteriskjava/config/ConfigFileImpl.java @@ -16,10 +16,13 @@ */ package org.asteriskjava.config; -import java.util.Map; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; + +import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.TreeMap; -import java.util.ArrayList; /** * An Asterisk configuration file read from the filesystem. @@ -28,39 +31,31 @@ * @version $Id$ * @since 1.0.0 */ -public class ConfigFileImpl implements ConfigFile -{ +public class ConfigFileImpl implements ConfigFile { private final String filename; - protected final Map categories; + protected final LockableMap categories; - public ConfigFileImpl(String filename, Map categories) - { + public ConfigFileImpl(String filename, Map categories) { this.filename = filename; - this.categories = categories; + this.categories = new LockableMap<>(categories); } - public String getFilename() - { + public String getFilename() { return filename; } - public Map> getCategories() - { + public Map> getCategories() { final Map> c; - c = new TreeMap>(); + c = new TreeMap<>(); - synchronized (categories) - { - for (Category category : categories.values()) - { + try (LockCloser closer = categories.withLock()) { + for (Category category : categories.values()) { List lines; - lines = new ArrayList(); - for (ConfigElement element : category.getElements()) - { - if (element instanceof ConfigVariable) - { + lines = new ArrayList<>(); + for (ConfigElement element : category.getElements()) { + if (element instanceof ConfigVariable) { ConfigVariable cv = (ConfigVariable) element; lines.add(cv.getName() + "=" + cv.getValue()); } @@ -72,24 +67,19 @@ public Map> getCategories() return c; } - public String getValue(String categoryName, String key) - { + public String getValue(String categoryName, String key) { final Category category; category = getCategory(categoryName); - if (category == null) - { + if (category == null) { return null; } - for (ConfigElement element : category.getElements()) - { - if (element instanceof ConfigVariable) - { + for (ConfigElement element : category.getElements()) { + if (element instanceof ConfigVariable) { ConfigVariable cv = (ConfigVariable) element; - if (cv.getName().equals(key)) - { + if (cv.getName().equals(key)) { return cv.getValue(); } } @@ -97,26 +87,21 @@ public String getValue(String categoryName, String key) return null; } - public List getValues(String categoryName, String key) - { + public List getValues(String categoryName, String key) { final Category category; final List result; category = getCategory(categoryName); - result = new ArrayList(); - if (category == null) - { + result = new ArrayList<>(); + if (category == null) { return result; } - for (ConfigElement element : category.getElements()) - { - if (element instanceof ConfigVariable) - { + for (ConfigElement element : category.getElements()) { + if (element instanceof ConfigVariable) { ConfigVariable cv = (ConfigVariable) element; - if (cv.getName().equals(key)) - { + if (cv.getName().equals(key)) { result.add(cv.getValue()); } } @@ -124,10 +109,8 @@ public List getValues(String categoryName, String key) return result; } - protected Category getCategory(String name) - { - synchronized (categories) - { + protected Category getCategory(String name) { + try (LockCloser closer = categories.withLock()) { return categories.get(name); } } diff --git a/src/main/java/org/asteriskjava/config/ConfigFileReader.java b/src/main/java/org/asteriskjava/config/ConfigFileReader.java index 86b5e54da..474266428 100644 --- a/src/main/java/org/asteriskjava/config/ConfigFileReader.java +++ b/src/main/java/org/asteriskjava/config/ConfigFileReader.java @@ -1,31 +1,29 @@ package org.asteriskjava.config; import java.io.BufferedReader; -import java.io.FileReader; +import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStreamReader; import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; import java.util.*; /** - * Reads and parses Asterisk configuration files. - *

- * See Asterisk's main/config.c. - *

+ * Reads and parses Asterisk configuration files.
+ * See Asterisk's main/config.c.
* Client code is not supposed to use this class. * * @author srt * @version $Id$ */ -public class ConfigFileReader -{ +public class ConfigFileReader { private static final int MAX_LINE_LENGTH = 8192; private static char COMMENT_META = ';'; private static char COMMENT_TAG = '-'; private static final Set> WARNING_CLASSES; - static - { - WARNING_CLASSES = new HashSet>(); + static { + WARNING_CLASSES = new HashSet<>(); WARNING_CLASSES.add(MissingEqualSignException.class); WARNING_CLASSES.add(UnknownDirectiveException.class); WARNING_CLASSES.add(MissingDirectiveParameterException.class); @@ -38,43 +36,28 @@ public class ConfigFileReader protected Category currentCategory; private int currentCommentLevel = 0; - public ConfigFileReader() - { + public ConfigFileReader() { this.commentBlock = new StringBuilder(); - this.categories = new LinkedHashMap(); - this.warnings = new ArrayList(); + this.categories = new LinkedHashMap<>(); + this.warnings = new ArrayList<>(); } - public ConfigFile readFile(String configfile) throws IOException, ConfigParseException - { + public ConfigFile readFile(String configfile) { final ConfigFile result; - final BufferedReader reader; - reader = new BufferedReader(new FileReader(configfile)); - try - { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(new FileInputStream(configfile), StandardCharsets.UTF_8))) { readFile(configfile, reader); + } catch (Exception e) { + // ignored } - finally - { - try - { - reader.close(); - } - catch (Exception e) // NOPMD - { - // ignore - } - } - - result = new ConfigFileImpl(configfile, new TreeMap(categories)); + result = new ConfigFileImpl(configfile, new TreeMap<>(categories)); return result; } - void reset() - { + void reset() { commentBlock = new StringBuilder(); categories.clear(); warnings.clear(); @@ -82,25 +65,21 @@ void reset() currentCommentLevel = 0; } - Collection getCategories() - { + Collection getCategories() { return categories.values(); } - public Collection getWarnings() - { - return new ArrayList(warnings); + public Collection getWarnings() { + return new ArrayList<>(warnings); } - void readFile(String configfile, BufferedReader reader) throws IOException, ConfigParseException - { + void readFile(String configfile, BufferedReader reader) throws IOException, ConfigParseException { String line; int lineno = 0; CharBuffer buffer = CharBuffer.allocate(MAX_LINE_LENGTH); reset(); - while ((line = reader.readLine()) != null) - { + while ((line = reader.readLine()) != null) { lineno++; buffer.clear(); buffer.put(line); @@ -111,8 +90,7 @@ void readFile(String configfile, BufferedReader reader) throws IOException, Conf } } - ConfigElement processLine(String configfile, int lineno, CharBuffer buffer) throws ConfigParseException - { + ConfigElement processLine(String configfile, int lineno, CharBuffer buffer) throws ConfigParseException { char c; final StringBuilder processLineBuilder; final StringBuilder lineCommentBuilder; @@ -121,97 +99,82 @@ ConfigElement processLine(String configfile, int lineno, CharBuffer buffer) thro lineCommentBuilder = new StringBuilder(MAX_LINE_LENGTH); buffer.mark(); - while (buffer.hasRemaining()) - { + while (buffer.hasRemaining()) { final int position; position = buffer.position(); c = buffer.get(); - //System.out.println(position + ": " + c); + // System.out.println(position + ": " + c); - if (c == COMMENT_META) - { - if (position >= 1 && buffer.get(position - 1) == '\\') - { + if (c == COMMENT_META) { + if (position >= 1 && buffer.get(position - 1) == '\\') { /* Escaped semicolons aren't comments. */ } // NOPMD - else if (buffer.remaining() >= 3 - && buffer.get(position + 1) == COMMENT_TAG - && buffer.get(position + 2) == COMMENT_TAG - && buffer.get(position + 3) != COMMENT_TAG) - { + else if (buffer.remaining() >= 3 && buffer.get(position + 1) == COMMENT_TAG + && buffer.get(position + 2) == COMMENT_TAG && buffer.get(position + 3) != COMMENT_TAG) { /* Meta-Comment start detected ";--" */ currentCommentLevel++; - //System.out.println("Comment start, new level: " + currentCommentLevel); + // System.out.println("Comment start, new level: " + + // currentCommentLevel); - if (!inComment()) - { + if (!inComment()) { commentBlock.append(";--"); buffer.position(position + 3); buffer.mark(); continue; } - } - else if (inComment() - && position >= 2 - && buffer.get(position - 1) == COMMENT_TAG - && buffer.get(position - 2) == COMMENT_TAG) - { + } else if (inComment() && position >= 2 && buffer.get(position - 1) == COMMENT_TAG + && buffer.get(position - 2) == COMMENT_TAG) { /* Meta-Comment end detected */ currentCommentLevel--; - if (!inComment()) - { + if (!inComment()) { buffer.reset(); - //int commentLength = (position + 1) - buffer.position(); + // int commentLength = (position + 1) - + // buffer.position(); - //buffer.reset(); - //for (int i = 0; i < commentLength; i++) - //{ - // commentBlock.append(buffer.get()); - //} + // buffer.reset(); + // for (int i = 0; i < commentLength; i++) + // { + // commentBlock.append(buffer.get()); + // } commentBlock.append(c); - //System.out.println("Comment end at " + position + ": '" + commentBlock.toString() + "'"); + // System.out.println("Comment end at " + position + ": + // '" + commentBlock.toString() + "'"); buffer.position(position + 1); buffer.compact(); buffer.flip(); - //System.out.println("Buffer compacted"); + // System.out.println("Buffer compacted"); continue; } - } - else - { - if (!inComment()) - { - /* If ; is found, and we are not nested in a comment, we immediately stop all comment processing */ - //System.out.println("Found ; while not in comment"); - while (buffer.hasRemaining()) - { + } else { + if (!inComment()) { + /* + * If ; is found, and we are not nested in a comment, we + * immediately stop all comment processing + */ + // System.out.println("Found ; while not in comment"); + while (buffer.hasRemaining()) { lineCommentBuilder.append(buffer.get()); } break; } - else - { - /* Found ';' while in comment */ - } // NOPMD + + /* Found ';' while in comment */ + // NOPMD } } - - if (inComment()) - { + if (inComment()) { commentBlock.append(c); - } - else - { - //System.out.println("Added '" + c + "' to processLine"); + } else { + // System.out.println("Added '" + c + "' to processLine"); processLineBuilder.append(c); } } @@ -223,46 +186,35 @@ else if (inComment() processLineString = processLineBuilder.toString().trim(); lineCommentString = lineCommentBuilder.toString().trim(); - //System.out.println("process line: '" + processLineString + "'"); - if (processLineString.length() == 0) - { - if (lineCommentString.length() != 0) - { + // System.out.println("process line: '" + processLineString + "'"); + if (processLineString.length() == 0) { + if (lineCommentString.length() != 0) { commentBlock.append(";"); commentBlock.append(lineCommentString); } - if (!inComment()) - { + if (!inComment()) { commentBlock.append("\n"); } return null; } - try - { + try { configElement = processTextLine(configfile, lineno, processLineString); - } - catch (ConfigParseException e) - { - // some parsing exceptions are treated as warnings by Asterisk, we mirror this behavior. - if (WARNING_CLASSES.contains(e.getClass())) - { + } catch (ConfigParseException e) { + // some parsing exceptions are treated as warnings by Asterisk, we + // mirror this behavior. + if (WARNING_CLASSES.contains(e.getClass())) { warnings.add(e); return null; } - else - { - throw e; - } + throw e; } - if (lineCommentString.length() != 0) - { + if (lineCommentString.length() != 0) { configElement.setComment(lineCommentString); } - if (commentBlock.length() != 0) - { + if (commentBlock.length() != 0) { configElement.setPreComment(commentBlock.toString()); commentBlock.delete(0, commentBlock.length()); } @@ -270,29 +222,24 @@ else if (inComment() return configElement; } - boolean inComment() - { + boolean inComment() { return currentCommentLevel != 0; } - protected ConfigElement processTextLine(String configfile, int lineno, String line) throws ConfigParseException - { + protected ConfigElement processTextLine(String configfile, int lineno, String line) throws ConfigParseException { ConfigElement configElement; if (line.charAt(0) == '[') // A category header { configElement = parseCategoryHeader(configfile, lineno, line); - } - else if (line.charAt(0) == '#') // a directive - #include or #exec + } else if (line.charAt(0) == '#') // a directive - #include or #exec { configElement = parseDirective(configfile, lineno, line); - } - else // just a line + } else // just a line { - if (currentCategory == null) - { - throw new ConfigParseException(configfile, lineno, - "parse error: No category context for line %d of %s", lineno, configfile); + if (currentCategory == null) { + throw new ConfigParseException(configfile, lineno, "parse error: No category context for line %d of %s", + lineno, configfile); } configElement = parseVariable(configfile, lineno, line); @@ -302,77 +249,67 @@ else if (line.charAt(0) == '#') // a directive - #include or #exec return configElement; } - protected Category parseCategoryHeader(String configfile, int lineno, String line) throws ConfigParseException - { + protected Category parseCategoryHeader(String configfile, int lineno, String line) throws ConfigParseException { final Category category; final String name; final int nameEndPos; - /* format is one of the following: - * [foo] define a new category named 'foo' - * [foo](!) define a new template category named 'foo' - * [foo](+) append to category 'foo', error if foo does not exist. - * [foo](a) define a new category and inherit from template a. - * You can put a comma-separated list of templates and '!' and '+' - * between parentheses, with obvious meaning. - */ + /* + * format is one of the following: [foo] define a new category named + * 'foo' [foo](!) define a new template category named 'foo' [foo](+) + * append to category 'foo', error if foo does not exist. [foo](a) + * define a new category and inherit from template a. You can put a + * comma-separated list of templates and '!' and '+' between + * parentheses, with obvious meaning. + */ nameEndPos = line.indexOf(']'); - if (nameEndPos == -1) - { - throw new ConfigParseException(configfile, lineno, - "parse error: no closing ']', line %d of %s", lineno, configfile); + if (nameEndPos == -1) { + throw new ConfigParseException(configfile, lineno, "parse error: no closing ']', line %d of %s", lineno, + configfile); } name = line.substring(1, nameEndPos); category = new Category(configfile, lineno, name); /* Handle options or categories to inherit from if available */ - if (line.length() > nameEndPos + 1 && line.charAt(nameEndPos + 1) == '(') - { + if (line.length() > nameEndPos + 1 && line.charAt(nameEndPos + 1) == '(') { final String[] options; final String optionsString; final int optionsEndPos; optionsString = line.substring(nameEndPos + 1); optionsEndPos = optionsString.indexOf(')'); - if (optionsEndPos == -1) - { - throw new ConfigParseException(configfile, lineno, - "parse error: no closing ')', line %d of %s", lineno, configfile); + if (optionsEndPos == -1) { + throw new ConfigParseException(configfile, lineno, "parse error: no closing ')', line %d of %s", lineno, + configfile); } options = optionsString.substring(1, optionsEndPos).split(","); - for (String cur : options) - { + for (String cur : options) { if ("!".equals(cur)) // category template { category.markAsTemplate(); - } - else if ("+".equals(cur)) // category addition + } else if ("+".equals(cur)) // category addition { final Category categoryToAddTo; categoryToAddTo = categories.get(name); - if (categoryToAddTo == null) - { + if (categoryToAddTo == null) { throw new ConfigParseException(configfile, lineno, - "Category addition requested, but category '%s' does not exist, line %d of %s", - name, lineno, configfile); + "Category addition requested, but category '%s' does not exist, line %d of %s", name, lineno, + configfile); } - //todo implement category addition - //category = categoryToAddTo; - } - else - { + // todo implement category addition + // category = categoryToAddTo; + } else { final Category baseCategory; baseCategory = categories.get(cur); - if (baseCategory == null) - { + if (baseCategory == null) { throw new ConfigParseException(configfile, lineno, - "Inheritance requested, but category '%s' does not exist, line %d of %s", - cur, lineno, configfile); + "Inheritance requested, but category '%s' does not exist, line %d of %s", cur, lineno, + configfile); } inheritCategory(category, baseCategory); } @@ -383,8 +320,7 @@ else if ("+".equals(cur)) // category addition return category; } - ConfigDirective parseDirective(String configfile, int lineno, String line) throws ConfigParseException - { + ConfigDirective parseDirective(String configfile, int lineno, String line) throws ConfigParseException { ConfigDirective directive; final StringBuilder nameBuilder; final StringBuilder paramBuilder; @@ -393,85 +329,68 @@ ConfigDirective parseDirective(String configfile, int lineno, String line) throw nameBuilder = new StringBuilder(); paramBuilder = new StringBuilder(); - for (int i = 1; i < line.length(); i++) - { + for (int i = 1; i < line.length(); i++) { final char c; c = line.charAt(i); - if (name == null) - { + if (name == null) { nameBuilder.append(c); - if (Character.isWhitespace(c) || i + 1 == line.length()) - { + if (Character.isWhitespace(c) || i + 1 == line.length()) { name = nameBuilder.toString().trim(); } - } - else - { + } else { paramBuilder.append(c); } } param = paramBuilder.toString().trim(); - if (param.length() != 0 && - (param.charAt(0) == '"' || param.charAt(0) == '<' || param.charAt(0) == '>')) - { + if (param.length() != 0 && (param.charAt(0) == '"' || param.charAt(0) == '<' || param.charAt(0) == '>')) { param = param.substring(1); } int endPos = param.length() - 1; - if (param.length() != 0 && - (param.charAt(endPos) == '"' || param.charAt(endPos) == '<' || param.charAt(endPos) == '>')) - { + if (param.length() != 0 + && (param.charAt(endPos) == '"' || param.charAt(endPos) == '<' || param.charAt(endPos) == '>')) { param = param.substring(0, endPos); } - if ("exec".equalsIgnoreCase(name)) - { + if ("exec".equalsIgnoreCase(name)) { directive = new ExecDirective(configfile, lineno, param); - } - else if ("include".equalsIgnoreCase(name)) - { + } else if ("include".equalsIgnoreCase(name)) { directive = new IncludeDirective(configfile, lineno, param); - } - else - { - throw new UnknownDirectiveException(configfile, lineno, - "Unknown directive '%s' at line %d of %s", name, lineno, configfile); + } else { + throw new UnknownDirectiveException(configfile, lineno, "Unknown directive '%s' at line %d of %s", name, lineno, + configfile); } - if (param.length() == 0) - { + if (param.length() == 0) { + if (name == null) { + name = ""; + } throw new MissingDirectiveParameterException(configfile, lineno, - "Directive '#%s' needs an argument (%s) at line %d of %s", - name.toLowerCase(Locale.US), - "include".equalsIgnoreCase(name) ? "filename" : "/path/to/executable", - lineno, - configfile); + "Directive '#%s' needs an argument (%s) at line %d of %s", name.toLowerCase(Locale.ENGLISH), + "include".equalsIgnoreCase(name) ? "filename" : "/path/to/executable", lineno, configfile); } return directive; } - protected ConfigVariable parseVariable(String configfile, int lineno, String line) throws ConfigParseException - { + protected ConfigVariable parseVariable(String configfile, int lineno, String line) throws ConfigParseException { int pos; String name; String value; pos = line.indexOf('='); - if (pos == -1) - { - throw new MissingEqualSignException(configfile, lineno, - "No '=' (equal sign) in line %d of %s", lineno, configfile); + if (pos == -1) { + throw new MissingEqualSignException(configfile, lineno, "No '=' (equal sign) in line %d of %s", lineno, + configfile); } name = line.substring(0, pos).trim(); // Ignore > in => - if (line.length() > pos + 1 && line.charAt(pos + 1) == '>') - { + if (line.length() > pos + 1 && line.charAt(pos + 1) == '>') { pos++; } @@ -479,13 +398,11 @@ protected ConfigVariable parseVariable(String configfile, int lineno, String lin return new ConfigVariable(configfile, lineno, name, value); } - void inheritCategory(Category category, Category baseCategory) - { + void inheritCategory(Category category, Category baseCategory) { category.addBaseCategory(baseCategory); } - void appendCategory(Category category) - { + void appendCategory(Category category) { categories.put(category.getName(), category); currentCategory = category; } diff --git a/src/main/java/org/asteriskjava/config/ConfigParseException.java b/src/main/java/org/asteriskjava/config/ConfigParseException.java index 8ef078f2a..28bd8a5b8 100644 --- a/src/main/java/org/asteriskjava/config/ConfigParseException.java +++ b/src/main/java/org/asteriskjava/config/ConfigParseException.java @@ -1,35 +1,27 @@ package org.asteriskjava.config; -/** - * - */ -public class ConfigParseException extends Exception -{ +public class ConfigParseException extends Exception { private static final long serialVersionUID = 4346366210261425734L; - private String filename; - private int lineno; + private final String filename; + private final int lineno; - public ConfigParseException(String filename, int lineno, String message) - { + public ConfigParseException(String filename, int lineno, String message) { super(message); this.filename = filename; this.lineno = lineno; } - public ConfigParseException(String filename, int lineno, String format, Object... params) - { + public ConfigParseException(String filename, int lineno, String format, Object... params) { super(String.format(format, params)); this.filename = filename; this.lineno = lineno; } - public String getFileName() - { + public String getFileName() { return filename; } - public int getLineNumber() - { + public int getLineNumber() { return lineno; } } diff --git a/src/main/java/org/asteriskjava/config/ConfigVariable.java b/src/main/java/org/asteriskjava/config/ConfigVariable.java index 7f72567b6..fefe8f7f5 100644 --- a/src/main/java/org/asteriskjava/config/ConfigVariable.java +++ b/src/main/java/org/asteriskjava/config/ConfigVariable.java @@ -1,64 +1,50 @@ package org.asteriskjava.config; -/** - * - */ -public class ConfigVariable extends ConfigElement -{ +public class ConfigVariable extends ConfigElement { private String name; private String value; - public ConfigVariable(String name, String value) - { + public ConfigVariable(String name, String value) { setName(name); setValue(value); } - public ConfigVariable(String filename, int lineno, String name, String value) - { + public ConfigVariable(String filename, int lineno, String name, String value) { super(filename, lineno); setName(name); setValue(value); } - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { - if (name == null) - { + public void setName(String name) { + if (name == null) { throw new IllegalArgumentException("Variable name must not be null"); } this.name = name; } - public String getValue() - { + public String getValue() { return value; } - public void setValue(String value) - { + public void setValue(String value) { this.value = value; } @Override - protected StringBuilder rawFormat(StringBuilder sb) - { + protected StringBuilder rawFormat(StringBuilder sb) { sb.append(name).append(" = "); - if (value != null) - { + if (value != null) { sb.append(value); } return sb; } - + @Override - public String toString() - { - return name+"="+value; + public String toString() { + return name + "=" + value; } } diff --git a/src/main/java/org/asteriskjava/config/ExecDirective.java b/src/main/java/org/asteriskjava/config/ExecDirective.java index 18c59800b..3d9e75d46 100644 --- a/src/main/java/org/asteriskjava/config/ExecDirective.java +++ b/src/main/java/org/asteriskjava/config/ExecDirective.java @@ -1,33 +1,28 @@ package org.asteriskjava.config; -public class ExecDirective extends ConfigDirective -{ +public class ExecDirective extends ConfigDirective { /** * file name of the executable. */ private final String execFile; - public ExecDirective(String execFile) - { + public ExecDirective(String execFile) { super(); this.execFile = execFile; } - public ExecDirective(String filename, int lineno, String execFile) - { + public ExecDirective(String filename, int lineno, String execFile) { super(filename, lineno); this.execFile = execFile; } - public String getExecFile() - { + public String getExecFile() { return execFile; } @Override - protected StringBuilder rawFormat(StringBuilder sb) - { + protected StringBuilder rawFormat(StringBuilder sb) { sb.append("#exec \"").append(execFile).append("\""); return sb; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/config/IncludeDirective.java b/src/main/java/org/asteriskjava/config/IncludeDirective.java index 3d315b656..2da0da996 100644 --- a/src/main/java/org/asteriskjava/config/IncludeDirective.java +++ b/src/main/java/org/asteriskjava/config/IncludeDirective.java @@ -1,33 +1,28 @@ package org.asteriskjava.config; -public class IncludeDirective extends ConfigDirective -{ +public class IncludeDirective extends ConfigDirective { /** * file name included. */ private final String includeFile; - public IncludeDirective(String includeFile) - { + public IncludeDirective(String includeFile) { super(); this.includeFile = includeFile; } - public IncludeDirective(String filename, int lineno, String includeFile) - { + public IncludeDirective(String filename, int lineno, String includeFile) { super(filename, lineno); this.includeFile = includeFile; } - public String getIncludeFile() - { + public String getIncludeFile() { return includeFile; } @Override - protected StringBuilder rawFormat(StringBuilder sb) - { + protected StringBuilder rawFormat(StringBuilder sb) { sb.append("#include \"").append(includeFile).append("\""); return sb; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/config/MissingDirectiveParameterException.java b/src/main/java/org/asteriskjava/config/MissingDirectiveParameterException.java index cd3adab03..3e4e583a2 100644 --- a/src/main/java/org/asteriskjava/config/MissingDirectiveParameterException.java +++ b/src/main/java/org/asteriskjava/config/MissingDirectiveParameterException.java @@ -4,11 +4,10 @@ * A required parameter to a directive is missing.

* The #include and #exec directives require a parameter (include file or command to execute). */ -public class MissingDirectiveParameterException extends ConfigParseException -{ +public class MissingDirectiveParameterException extends ConfigParseException { private static final long serialVersionUID = -3802754628756681515L; - public MissingDirectiveParameterException(String filename, int lineno, String format, Object... params) - { + + public MissingDirectiveParameterException(String filename, int lineno, String format, Object... params) { super(filename, lineno, format, params); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/config/MissingEqualSignException.java b/src/main/java/org/asteriskjava/config/MissingEqualSignException.java index 99a42f746..10b4190e2 100644 --- a/src/main/java/org/asteriskjava/config/MissingEqualSignException.java +++ b/src/main/java/org/asteriskjava/config/MissingEqualSignException.java @@ -4,11 +4,10 @@ * The equal sign on a variable assignment line is missing.

* A variable line must include an equal sign. */ -public class MissingEqualSignException extends ConfigParseException -{ +public class MissingEqualSignException extends ConfigParseException { private static final long serialVersionUID = 2694490330074765342L; - public MissingEqualSignException(String filename, int lineno, String format, Object... params) - { + + public MissingEqualSignException(String filename, int lineno, String format, Object... params) { super(filename, lineno, format, params); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/config/UnknownDirectiveException.java b/src/main/java/org/asteriskjava/config/UnknownDirectiveException.java index 54ae2a8cf..59c7f633e 100644 --- a/src/main/java/org/asteriskjava/config/UnknownDirectiveException.java +++ b/src/main/java/org/asteriskjava/config/UnknownDirectiveException.java @@ -4,11 +4,10 @@ * An unknown directive has been encountered.

* Asterisk only supports #include and #exec directives. */ -public class UnknownDirectiveException extends ConfigParseException -{ +public class UnknownDirectiveException extends ConfigParseException { private static final long serialVersionUID = 4356355066633810196L; - public UnknownDirectiveException(String filename, int lineno, String format, Object... params) - { + + public UnknownDirectiveException(String filename, int lineno, String format, Object... params) { super(filename, lineno, format, params); } } diff --git a/src/main/java/org/asteriskjava/config/dialplan/ConfigExtension.java b/src/main/java/org/asteriskjava/config/dialplan/ConfigExtension.java index ad9843d65..73561425d 100644 --- a/src/main/java/org/asteriskjava/config/dialplan/ConfigExtension.java +++ b/src/main/java/org/asteriskjava/config/dialplan/ConfigExtension.java @@ -1,57 +1,50 @@ package org.asteriskjava.config.dialplan; -import java.util.Arrays; - import org.asteriskjava.config.ConfigElement; +import java.util.Arrays; + /** * Represents the dial plan extension as a specific kind of configuration * directive This class makes no interpretation of syntax checking of names, * priorities, or application (for now). - * + * * @author martins */ -public class ConfigExtension extends ConfigElement -{ +public class ConfigExtension extends ConfigElement { String name, priority; - + /** - * Holds the application in the first element, and arguments in all subsequent elements. Similar to command line arguments array. + * Holds the application in the first element, and arguments in all subsequent elements. Similar to command line arguments array. */ - String [] application; - - public ConfigExtension(String filename, int lineno, String name, String priority, String [] application) - { - super(filename,lineno); + String[] application; + + public ConfigExtension(String filename, int lineno, String name, String priority, String[] application) { + super(filename, lineno); this.name = name; this.priority = priority; this.application = application; } @Override - protected StringBuilder rawFormat(StringBuilder sb) - { + protected StringBuilder rawFormat(StringBuilder sb) { return sb.append(toString()); } - + @Override - public String toString() - { - return "exten => " + name + "," + priority + "," + Arrays.asList(application); + public String toString() { + return "exten => " + name + "," + priority + "," + Arrays.asList(application); } - public String getName() - { + public String getName() { return name; } - public String getPriority() - { + public String getPriority() { return priority; } - public String[] getApplication() - { + public String[] getApplication() { return application; } diff --git a/src/main/java/org/asteriskjava/config/dialplan/ConfigInclude.java b/src/main/java/org/asteriskjava/config/dialplan/ConfigInclude.java index 80ee07187..abdee6cb9 100644 --- a/src/main/java/org/asteriskjava/config/dialplan/ConfigInclude.java +++ b/src/main/java/org/asteriskjava/config/dialplan/ConfigInclude.java @@ -2,30 +2,25 @@ import org.asteriskjava.config.ConfigElement; -public class ConfigInclude extends ConfigElement -{ +public class ConfigInclude extends ConfigElement { String category; - - public ConfigInclude(String filename, int lineno, String category) - { + + public ConfigInclude(String filename, int lineno, String category) { super(filename, lineno); this.category = category; } - + @Override - protected StringBuilder rawFormat(StringBuilder sb) - { + protected StringBuilder rawFormat(StringBuilder sb) { return sb.append(toString()); } - + @Override - public String toString() - { + public String toString() { return "include => " + category; } - public String getName() - { + public String getName() { return category; } diff --git a/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFile.java b/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFile.java index cba0d75a8..49c8f1912 100644 --- a/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFile.java +++ b/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFile.java @@ -1,20 +1,17 @@ package org.asteriskjava.config.dialplan; -import java.util.Collection; -import java.util.Map; - import org.asteriskjava.config.Category; import org.asteriskjava.config.ConfigFileImpl; -public class ExtensionsConfigFile extends ConfigFileImpl -{ - public ExtensionsConfigFile(String filename, Map categories) - { +import java.util.Collection; +import java.util.Map; + +public class ExtensionsConfigFile extends ConfigFileImpl { + public ExtensionsConfigFile(String filename, Map categories) { super(filename, categories); } - public Collection getContexts() - { + public Collection getContexts() { return categories.values(); } } diff --git a/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFileReader.java b/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFileReader.java index 98914a8e5..65593428f 100644 --- a/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFileReader.java +++ b/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFileReader.java @@ -1,182 +1,158 @@ package org.asteriskjava.config.dialplan; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - import org.asteriskjava.config.ConfigElement; import org.asteriskjava.config.ConfigFileReader; import org.asteriskjava.config.ConfigParseException; import org.asteriskjava.config.ConfigVariable; +import java.util.ArrayList; +import java.util.List; + /* * Interprets extensions.conf as a special kind of config file, the dialplan. * - Line numbers correspond with pbx_config.c, tags/1.4.19 revision 96024 */ -public class ExtensionsConfigFileReader extends ConfigFileReader -{ +public class ExtensionsConfigFileReader extends ConfigFileReader { /* * This method corresponds to an iteration of the loop at line 2212 Notes: - * 1. [general] and [globals] are allowed to be a context here if they contain only configvariables - * 2. switch and ignorepat are treated like regular ConfigVariable. + * 1. [general] and [globals] are allowed to be a context here if they + * contain only configvariables 2. switch and ignorepat are treated like + * regular ConfigVariable. */ @Override - protected ConfigElement processTextLine(String configfile, int lineno, String line) throws ConfigParseException - { + protected ConfigElement processTextLine(String configfile, int lineno, String line) throws ConfigParseException { ConfigElement configElement; - - if( - (line.trim().startsWith("exten") || line.trim().startsWith("include")) && - currentCategory != null && - (currentCategory.getName().equals("general") || currentCategory.getName().equals("globals")) - ) - throw new ConfigParseException(configfile, lineno, "cannot have 'exten' or 'include' in global or general sections"); - - + + if ((line.trim().startsWith("exten") || line.trim().startsWith("include")) && currentCategory != null + && (currentCategory.getName().equals("general") || currentCategory.getName().equals("globals"))) + throw new ConfigParseException(configfile, lineno, + "cannot have 'exten' or 'include' in global or general sections"); + /* - * Goal here is to break out anything unique that we might want to - * look at and parse separately. For now, only exten and include fit - * that criteria. Eventually, I could see parsing sections for things - * from macros, contexts to differentiate them from categories, switch - * for realtime, and more. + * Goal here is to break out anything unique that we might want to look + * at and parse separately. For now, only exten and include fit that + * criteria. Eventually, I could see parsing sections for things from + * macros, contexts to differentiate them from categories, switch for + * realtime, and more. */ - if (line.trim().startsWith("exten")) - { + if (line.trim().startsWith("exten")) { configElement = parseExtension(configfile, lineno, line); currentCategory.addElement(configElement); return configElement; - } - else if(line.trim().startsWith("include")) - { + } else if (line.trim().startsWith("include")) { // use parseVariable since we have access to it ConfigVariable configvar = parseVariable(configfile, lineno, line); configElement = new ConfigInclude(configfile, lineno, configvar.getValue()); currentCategory.addElement(configElement); return configElement; } - + // leave everything else the same configElement = super.processTextLine(configfile, lineno, line); - + return configElement; } - + /* Roughly corresponds to pbx_config.c:2222 */ - protected ConfigExtension parseExtension(String configfile, int lineno, String line) throws ConfigParseException - { + protected ConfigExtension parseExtension(String configfile, int lineno, String line) throws ConfigParseException { ConfigVariable initialVariable = parseVariable(configfile, lineno, line); - - if(!initialVariable.getName().equals("exten")) + + if (!initialVariable.getName().equals("exten")) throw new ConfigParseException(configfile, lineno, "missing 'exten' near " + line); line = initialVariable.getValue().trim(); int nameIndex = line.indexOf(",", 0); - if(nameIndex == -1) + if (nameIndex == -1) throw new ConfigParseException(configfile, lineno, "missing extension name near " + line); String name = line.substring(0, nameIndex); - line = line.substring(name.length()+1, line.length()).trim(); - + line = line.substring(name.length() + 1, line.length()).trim(); + int priorityDelimiter = line.indexOf(",", 0); - if(priorityDelimiter == -1) + if (priorityDelimiter == -1) throw new ConfigParseException(configfile, lineno, "missing extension priority near " + line); String priority = line.substring(0, priorityDelimiter); - line = line.substring(priority.length()+1, line.length()).trim(); + line = line.substring(priority.length() + 1, line.length()).trim(); - String [] application = harvestApplicationWithArguments(line); - - return new ConfigExtension(configfile,lineno,name,priority,application); + String[] application = harvestApplicationWithArguments(line); + + return new ConfigExtension(configfile, lineno, name, priority, application); } - + /* Roughly corresponds to pbx_config.c:2276 */ - private static String [] harvestApplicationWithArguments(String arg) - { - List args = new ArrayList(); - - if(args != null && arg.trim().length() >= 0) - { + private static String[] harvestApplicationWithArguments(String arg) { + List args = new ArrayList<>(); + + if (arg.trim().length() >= 0) { String appl = "", data = ""; - + /* Find the first occurrence of either '(' or ',' */ int firstc = arg.indexOf(','); int firstp = arg.indexOf('('); - + if (firstc != -1 && (firstp == -1 || firstc < firstp)) { /* comma found, no parenthesis */ /* or both found, but comma found first */ - String [] split = arg.split(","); + String[] split = arg.split(","); appl = split[0]; - for(int i = 1; i < split.length; i++) - data += split[i] + (i+1 - +

Provides classes to manage the dialplan of an Asterisk server.

- \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/config/package.html b/src/main/java/org/asteriskjava/config/package.html index 0fca39daa..37556adfe 100644 --- a/src/main/java/org/asteriskjava/config/package.html +++ b/src/main/java/org/asteriskjava/config/package.html @@ -1,27 +1,27 @@ - +

Provides classes to manage the configuration of an Asterisk server.

- \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/examples/activities/BlindTransfer.java b/src/main/java/org/asteriskjava/examples/activities/BlindTransfer.java new file mode 100644 index 000000000..3a25b60f2 --- /dev/null +++ b/src/main/java/org/asteriskjava/examples/activities/BlindTransfer.java @@ -0,0 +1,90 @@ +package org.asteriskjava.examples.activities; + +import org.asteriskjava.manager.AuthenticationFailedException; +import org.asteriskjava.manager.TimeoutException; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.Call.OperandChannel; +import org.asteriskjava.pbx.activities.BlindTransferActivity; +import org.asteriskjava.pbx.activities.DialActivity; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +import java.io.IOException; + +/** + * dial somebody and then blind transfer the call to a third party. + * + * @author bsutton + */ +public class BlindTransfer { + + static public void main(String[] args) throws IOException, AuthenticationFailedException, TimeoutException { + /** + * Initialise the PBX Factory. You need to implement your own + * AsteriskSettings class. + */ + PBXFactory.init(new ExamplesAsteriskSettings()); + + /** + * Activities utilise an agi entry point in your dial plan. You can + * create your own entry point in dialplan or have asterisk-java add it + * automatically + */ + AsteriskPBX asteriskPbx = (AsteriskPBX) PBXFactory.getActivePBX(); + asteriskPbx.createAgiEntryPoint(); + + // We are all configured lets try and do a blind transfer. + blindTransfer(); + } + + static private void blindTransfer() { + String dialOptions = ""; + + PBX pbx = PBXFactory.getActivePBX(); + + // The trunk MUST match the section header (e.g. [default]) that appears + // in your /etc/asterisk/sip.d file (assuming you are using a SIP + // trunk). + // The trunk is used to select which SIP trunk to dial through. + Trunk trunk = pbx.buildTrunk("default"); + + // We are going to dial from extension 100 + EndPoint from = pbx.buildEndPoint(TechType.SIP, "100"); + // The caller ID to show on extension 100. + CallerID fromCallerID = pbx.buildCallerID("100", "My Phone"); + + // The caller ID to display on the called parties phone + CallerID toCallerID = pbx.buildCallerID("83208100", "Asterisk Java is calling"); + // The party we are going to call. + EndPoint to = pbx.buildEndPoint(TechType.SIP, trunk, "5551234"); + + // Start the dial and return immediately. + // progress is provided via the ActivityCallback. + pbx.dial(from, fromCallerID, to, toCallerID, new ActivityCallback() { + + @Override + public void progress(DialActivity activity, ActivityStatusEnum status, String message) { + if (status == ActivityStatusEnum.SUCCESS) { + System.out.println("Dial all good so lets do a blind transfer"); + PBX pbx = PBXFactory.getActivePBX(); + // Call is up + Call call = activity.getNewCall(); + CallerID toCallerID = pbx.buildCallerID("101", "I'm calling you"); + EndPoint transferTarget = pbx.buildEndPoint(TechType.SIP, "101"); + pbx.blindTransfer(call, OperandChannel.REMOTE_PARTY, transferTarget, toCallerID, false, 30L, + new ActivityCallback() { + + @Override + public void progress(BlindTransferActivity activity, ActivityStatusEnum status, + String message) { + // if success the blind transfer completed. + } + }, ""); + } + if (status == ActivityStatusEnum.FAILURE) + System.out.println("Oops something bad happened when we dialed."); + } + }, dialOptions); + + } + +} diff --git a/src/main/java/org/asteriskjava/examples/activities/Dial.java b/src/main/java/org/asteriskjava/examples/activities/Dial.java new file mode 100644 index 000000000..06e5821cf --- /dev/null +++ b/src/main/java/org/asteriskjava/examples/activities/Dial.java @@ -0,0 +1,100 @@ +package org.asteriskjava.examples.activities; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.activities.DialActivity; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class Dial { + static private Log logger = LogFactory.getLog(Dial.class); + + static public void main(String[] args) { + syncDial(); + asyncDial(); + + } + + /** + * Simple synchronous dial. The dial method won't return until the dial + * starts. Using this method will lockup your UI until the dial starts. For + * better control use the async Dial method below. + */ + static private void syncDial() { + try { + String dialOptions = ""; + + PBX pbx = PBXFactory.getActivePBX(); + + // The trunk MUST match the section header (e.g. [default]) that + // appears + // in your /etc/asterisk/sip.d file (assuming you are using a SIP + // trunk). + // The trunk is used to select which SIP trunk to dial through. + Trunk trunk = pbx.buildTrunk("default"); + + // We are going to dial from extension 100 + EndPoint from = pbx.buildEndPoint(TechType.SIP, "100"); + // The caller ID to show on extension 100. + CallerID fromCallerID = pbx.buildCallerID("100", "My Phone"); + + // The caller ID to display on the called parties phone + CallerID toCallerID = pbx.buildCallerID("83208100", "Asterisk Java is calling"); + // The party we are going to call. + EndPoint to = pbx.buildEndPoint(TechType.SIP, trunk, "5551234"); + + // Trunk is currently ignored so set to null + // The call is dialed and only returns when the call comes up (it + // doesn't wait for the remote end to answer). + DialActivity dial = pbx.dial(from, fromCallerID, to, toCallerID, dialOptions); + + Call call = dial.getNewCall(); + + Thread.sleep(20000); + + logger.warn("Hanging up"); + pbx.hangup(call); + } catch (PBXException | InterruptedException e) { + System.out.println(e); + } + } + + static private void asyncDial() { + String dialOptions = ""; + PBX pbx = PBXFactory.getActivePBX(); + + // We are going to dial from extension 100 + EndPoint from = pbx.buildEndPoint(TechType.SIP, "100"); + // The caller ID to show on extension 100. + CallerID fromCallerID = pbx.buildCallerID("100", "My Phone"); + + // The caller ID to display on the called parties phone + CallerID toCallerID = pbx.buildCallerID("83208100", "Asterisk Java is calling"); + // The party we are going to call. + EndPoint to = pbx.buildEndPoint(TechType.SIP, pbx.buildTrunk("default"), "5551234"); + + // Start the dial and return immediately. + // progress is provided via the ActivityCallback. + pbx.dial(from, fromCallerID, to, toCallerID, new ActivityCallback() { + + @Override + public void progress(DialActivity activity, ActivityStatusEnum status, String message) { + if (status == ActivityStatusEnum.SUCCESS) { + System.out.println("Dial all good"); + try { + // Call is up + Call call = activity.getNewCall(); + // So lets just hangup the call + logger.warn("Hanging up"); + PBXFactory.getActivePBX().hangup(call.getOriginatingParty()); + } catch (PBXException e) { + System.out.println(e); + } + } + if (status == ActivityStatusEnum.FAILURE) + System.out.println("Oops something bad happened when we dialed."); + } + }, dialOptions); + + } + +} diff --git a/src/main/java/org/asteriskjava/examples/activities/ExamplesAsteriskSettings.java b/src/main/java/org/asteriskjava/examples/activities/ExamplesAsteriskSettings.java new file mode 100644 index 000000000..bcaa2a672 --- /dev/null +++ b/src/main/java/org/asteriskjava/examples/activities/ExamplesAsteriskSettings.java @@ -0,0 +1,31 @@ +package org.asteriskjava.examples.activities; + +import org.asteriskjava.pbx.DefaultAsteriskSettings; + +public class ExamplesAsteriskSettings extends DefaultAsteriskSettings { + + @Override + public String getManagerPassword() { + // this password MUST match the password (secret=) in manager.conf + return "a good password"; + } + + @Override + public String getManagerUsername() { + // this MUST match the section header '[myconnection]' in manager.conf + return "myconnection"; + } + + @Override + public String getAsteriskIP() { + // The IP address or FQDN of your Asterisk server. + return "2.2.2.2"; + } + + @Override + public String getAgiHost() { + // The IP Address of FQDN of you asterisk-java application. + return "1.1.1.1"; + } + +} diff --git a/src/main/java/org/asteriskjava/examples/activities/Hold.java b/src/main/java/org/asteriskjava/examples/activities/Hold.java new file mode 100644 index 000000000..c13b998be --- /dev/null +++ b/src/main/java/org/asteriskjava/examples/activities/Hold.java @@ -0,0 +1,58 @@ +package org.asteriskjava.examples.activities; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.activities.DialActivity; +import org.asteriskjava.pbx.activities.HoldActivity; + +/** + * dial somebody and then put them on hold. + * + * @author bsutton + */ +public class Hold { + + static public void main(String[] args) { + hold(); + } + + static private void hold() { + String dialOptions = ""; + PBX pbx = PBXFactory.getActivePBX(); + + // We are going to dial from extension 100 + EndPoint from = pbx.buildEndPoint(TechType.SIP, "100"); + // The caller ID to show on extension 100. + CallerID fromCallerID = pbx.buildCallerID("100", "My Phone"); + + // The caller ID to display on the called parties phone + CallerID toCallerID = pbx.buildCallerID("83208100", "Asterisk Java is calling"); + // The party we are going to call. + EndPoint to = pbx.buildEndPoint("SIP/default/5551234"); + + // Start the dial and return immediately. + // progress is provided via the ActivityCallback. + pbx.dial(from, fromCallerID, to, toCallerID, new ActivityCallback() { + + @Override + public void progress(DialActivity activity, ActivityStatusEnum status, String message) { + if (status == ActivityStatusEnum.SUCCESS) { + System.out.println("Dial all good so lets place them on hold"); + PBX pbx = PBXFactory.getActivePBX(); + // Call is up + Call call = activity.getNewCall(); + + // Place the remote party on hold. + HoldActivity hold = pbx.hold(call.getRemoteParty()); + + Channel heldChannel = hold.getChannel(); + + System.out.println("Held channel is " + heldChannel); + } + if (status == ActivityStatusEnum.FAILURE) + System.out.println("Oops something bad happened when we dialed."); + } + }, dialOptions); + + } + +} diff --git a/examples/ExampleCallin.java b/src/main/java/org/asteriskjava/examples/fastagi/ExampleCallIn.java similarity index 69% rename from examples/ExampleCallin.java rename to src/main/java/org/asteriskjava/examples/fastagi/ExampleCallIn.java index 041b666a2..66e8dd8ab 100644 --- a/examples/ExampleCallin.java +++ b/src/main/java/org/asteriskjava/examples/fastagi/ExampleCallIn.java @@ -1,21 +1,23 @@ +package org.asteriskjava.examples.fastagi; + /* Cloudvox - answer and control a phone call with Java Place and receive phone calls via open API: http://cloudvox.com/ -Learn about call scripting, Asterisk/AGI, voice apps: http://help.cloudvox.com/ +Learn about call scripting, Asterisk/AGI, voice apps: http://help.cloudvox.com/ Added to the project and modified by Tropo: http://tropo.com */ - + import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiRequest; import org.asteriskjava.fastagi.BaseAgiScript; - + /* Example incoming call handler Answer call, speak message */ public class ExampleCallIn extends BaseAgiScript { - public void service(AgiRequest request, AgiChannel channel) throws AgiException { - answer(); - - exec("Playback", "tt-monkeys"); - - hangup(); - } -} \ No newline at end of file + public void service(AgiRequest request, AgiChannel channel) throws AgiException { + answer(); + + exec("Playback", "tt-monkeys"); + + hangup(); + } +} diff --git a/src/main/java/org/asteriskjava/examples/fastagi/fastagi.properties b/src/main/java/org/asteriskjava/examples/fastagi/fastagi.properties new file mode 100644 index 000000000..ec313ea80 --- /dev/null +++ b/src/main/java/org/asteriskjava/examples/fastagi/fastagi.properties @@ -0,0 +1 @@ +callin.agi=ExampleCallIn diff --git a/src/main/java/org/asteriskjava/fastagi/AbstractAgiServer.java b/src/main/java/org/asteriskjava/fastagi/AbstractAgiServer.java index 0e4bcb00c..7085a3b41 100644 --- a/src/main/java/org/asteriskjava/fastagi/AbstractAgiServer.java +++ b/src/main/java/org/asteriskjava/fastagi/AbstractAgiServer.java @@ -1,23 +1,21 @@ package org.asteriskjava.fastagi; +import org.asteriskjava.fastagi.internal.DefaultAgiChannelFactory; import org.asteriskjava.util.DaemonThreadFactory; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -import org.asteriskjava.fastagi.internal.AgiChannelFactory; -import org.asteriskjava.fastagi.internal.DefaultAgiChannelFactory; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.concurrent.SynchronousQueue; /** * Abstract base class for FastAGI and AsyncAGI servers. * * @since 1.0.0 */ -public abstract class AbstractAgiServer -{ +public abstract class AbstractAgiServer { private final Log logger = LogFactory.getLog(getClass()); /** @@ -28,7 +26,7 @@ public abstract class AbstractAgiServer /** * The default thread pool size. */ - private static final int DEFAULT_MAXIMUM_POOL_SIZE = 100; + private static final int DEFAULT_MAXIMUM_POOL_SIZE = 500; /** * The minimum number of worker threads in the thread pool. @@ -36,18 +34,20 @@ public abstract class AbstractAgiServer private int poolSize = DEFAULT_POOL_SIZE; /** - * The maximum number of worker threads in the thread pool. This equals the maximum number of - * concurrent requests this AgiServer can serve. + * The maximum number of worker threads in the thread pool. This equals the + * maximum number of concurrent requests this AgiServer can serve. */ private int maximumPoolSize = DEFAULT_MAXIMUM_POOL_SIZE; /** - * The thread pool that contains the worker threads to process incoming requests. + * The thread pool that contains the worker threads to process incoming + * requests. */ private ThreadPoolExecutor pool; /** - * The strategy to use for mapping AgiRequests to AgiScripts that serve them. + * The strategy to use for mapping AgiRequests to AgiScripts that serve + * them. */ private MappingStrategy mappingStrategy; @@ -58,21 +58,19 @@ public abstract class AbstractAgiServer private volatile boolean die = false; - public AbstractAgiServer() - { + public AbstractAgiServer() { this(new DefaultAgiChannelFactory()); } /** * Creates a new AbstractAgiServer with the given channel factory. * - * @param agiChannelFactory the AgiChannelFactory to use for creating new AgiChannel instances. + * @param agiChannelFactory the AgiChannelFactory to use for creating new + * AgiChannel instances. * @since 1.0.0 */ - public AbstractAgiServer(AgiChannelFactory agiChannelFactory) - { - if (agiChannelFactory == null) - { + public AbstractAgiServer(AgiChannelFactory agiChannelFactory) { + if (agiChannelFactory == null) { throw new IllegalArgumentException("AgiChannelFactory must not be null"); } @@ -81,12 +79,13 @@ public AbstractAgiServer(AgiChannelFactory agiChannelFactory) } /** - * Returns the AgiChannelFactory to use for creating new AgiChannel instances. + * Returns the AgiChannelFactory to use for creating new AgiChannel + * instances. * - * @return the AgiChannelFactory to use for creating new AgiChannel instances. + * @return the AgiChannelFactory to use for creating new AgiChannel + * instances. */ - protected AgiChannelFactory getAgiChannelFactory() - { + protected AgiChannelFactory getAgiChannelFactory() { return this.agiChannelFactory; } @@ -96,31 +95,26 @@ protected AgiChannelFactory getAgiChannelFactory() * @return the default number of worker threads in the thread pool. * @since 1.0.0 */ - public int getPoolSize() - { + public synchronized int getPoolSize() { return poolSize; } /** - * Sets the default number of worker threads in the thread pool. - *

+ * Sets the default number of worker threads in the thread pool.
* This is the number of threads that are available even if they are idle. - *

+ *
* The default pool size is 10. * * @param poolSize the size of the worker thread pool. * @throws IllegalArgumentException if the new pool size is negative - * @see {@link java.util.concurrent.ThreadPoolExecutor#setCorePoolSize(int)} + * @see java.util.concurrent.ThreadPoolExecutor#setCorePoolSize(int) */ - public synchronized void setPoolSize(int poolSize) - { - if (poolSize < 0) - { + public synchronized void setPoolSize(int poolSize) { + if (poolSize < 0) { throw new IllegalArgumentException("New poolSize (" + poolSize + ") is must not be negative"); } - if (pool != null) - { + if (pool != null) { pool.setCorePoolSize(poolSize); } this.poolSize = poolSize; @@ -132,92 +126,81 @@ public synchronized void setPoolSize(int poolSize) * @return the maximum number of worker threads in the thread pool. * @since 1.0.0 */ - public int getMaximumPoolSize() - { + public synchronized int getMaximumPoolSize() { return maximumPoolSize; } /** - * Sets the maximum number of worker threads in the thread pool. - *

- * This equals the maximum number of concurrent requests this AgiServer can serve. - *

+ * Sets the maximum number of worker threads in the thread pool.
+ * This equals the maximum number of concurrent requests this AgiServer can + * serve.
* The default maximum pool size is 100. * * @param maximumPoolSize the maximum size of the worker thread pool. - * @throws IllegalArgumentException if maximumPoolSize is less than current pool size or less than or equal to 0. - * @see {@link java.util.concurrent.ThreadPoolExecutor#setMaximumPoolSize(int)} + * @throws IllegalArgumentException if maximumPoolSize is less than current + * pool size or less than or equal to 0. + * @see java.util.concurrent.ThreadPoolExecutor#setMaximumPoolSize(int) */ - public synchronized void setMaximumPoolSize(int maximumPoolSize) - { - if (maximumPoolSize <= 0) - { + public synchronized void setMaximumPoolSize(int maximumPoolSize) { + if (maximumPoolSize <= 0) { throw new IllegalArgumentException("New maximumPoolSize (" + maximumPoolSize + ") is must be positive"); } - if (maximumPoolSize < poolSize) - { - throw new IllegalArgumentException("New maximumPoolSize (" + maximumPoolSize + ") is less than current pool size (" + poolSize + ")"); + if (maximumPoolSize < poolSize) { + throw new IllegalArgumentException( + "New maximumPoolSize (" + maximumPoolSize + ") is less than current pool size (" + poolSize + ")"); } - if (pool != null) - { + if (pool != null) { pool.setMaximumPoolSize(maximumPoolSize); } this.maximumPoolSize = maximumPoolSize; } /** - * Sets the strategy to use for mapping AgiRequests to AgiScripts that serve them. + * Sets the strategy to use for mapping AgiRequests to AgiScripts that serve + * them. * * @param mappingStrategy the mapping strategy to use. */ - public void setMappingStrategy(MappingStrategy mappingStrategy) - { + public void setMappingStrategy(MappingStrategy mappingStrategy) { this.mappingStrategy = mappingStrategy; } - protected MappingStrategy getMappingStrategy() - { + protected MappingStrategy getMappingStrategy() { return mappingStrategy; } - protected boolean isDie() - { + protected boolean isDie() { return die; } - protected synchronized void shutdown() - { + protected synchronized void shutdown() { this.die = true; - if (pool != null) - { + if (pool != null) { pool.shutdown(); } } @Override - protected void finalize() throws Throwable - { - super.finalize(); - + protected void finalize() throws Throwable { this.die = true; - if (pool != null) - { + if (pool != null) { pool.shutdown(); } + + super.finalize(); } /** - * Execute the runnable using the configured ThreadPoolExecutor obtained from {@link #getPool()}. + * Execute the runnable using the configured ThreadPoolExecutor obtained + * from {@link #getPool()}. * * @param command the command to run. * @throws RejectedExecutionException if the runnable can't be executed */ - protected void execute(Runnable command) throws RejectedExecutionException - { - if (isDie()) - { + protected void execute(Runnable command) throws RejectedExecutionException { + if (isDie()) { logger.warn("AgiServer is shutting down: Refused to execute AgiScript"); return; } @@ -225,15 +208,12 @@ protected void execute(Runnable command) throws RejectedExecutionException getPool().execute(command); } - protected void handleException(String message, Exception e) - { + protected void handleException(String message, Exception e) { logger.warn(message, e); } - private synchronized ThreadPoolExecutor getPool() - { - if (pool == null) - { + private synchronized ThreadPoolExecutor getPool() { + if (pool == null) { pool = createPool(); logger.info("Thread pool started."); } @@ -242,11 +222,36 @@ private synchronized ThreadPoolExecutor getPool() } /** - * Creates a new ThreadPoolExecutor to serve the AGI requests. The nature of this pool - * defines how many concurrent requests can be handled. The default implementation - * returns a dynamic thread pool defined by the poolSize and maximumPoolSize properties.

- * You can override this method to change this behavior. For example you can use a cached - * pool with + * Returns the approximate number of AgiConnectionHandler threads that are + * actively executing tasks. + * + * @see ThreadPoolExecutor#getActiveCount() + * @see #getPoolActiveThreadCount() + * @see org.asteriskjava.fastagi.internal.AgiConnectionHandler#AGI_CONNECTION_HANDLERS + */ + public int getPoolActiveTaskCount() { + if (pool != null) { + return pool.getActiveCount(); + } + return -1; + }// getPoolActiveCount + + public int getPoolActiveThreadCount() { + if (pool != null) { + return pool.getPoolSize(); + } + return -1; + }// getPoolActiveThreadCount + + /** + * Creates a new ThreadPoolExecutor to serve the AGI requests. The nature of + * this pool defines how many concurrent requests can be handled. The + * default implementation returns a dynamic thread pool defined by the + * poolSize and maximumPoolSize properties. + *

+ * You can override this method to change this behavior. For example you can + * use a cached pool with + * *

      * return Executors.newCachedThreadPool(new DaemonThreadFactory());
      * 
@@ -255,14 +260,8 @@ private synchronized ThreadPoolExecutor getPool() * @see #setPoolSize(int) * @see #setMaximumPoolSize(int) */ - protected ThreadPoolExecutor createPool() - { - return new ThreadPoolExecutor( - poolSize, - (maximumPoolSize < poolSize) ? poolSize : maximumPoolSize, - 50000L, TimeUnit.MILLISECONDS, - new SynchronousQueue(), - new DaemonThreadFactory() - ); + protected ThreadPoolExecutor createPool() { + return new ThreadPoolExecutor(poolSize, (maximumPoolSize < poolSize) ? poolSize : maximumPoolSize, 50000L, + TimeUnit.MILLISECONDS, new SynchronousQueue(), new DaemonThreadFactory()); } } diff --git a/src/main/java/org/asteriskjava/fastagi/AbstractMappingStrategy.java b/src/main/java/org/asteriskjava/fastagi/AbstractMappingStrategy.java index 6131698e3..333a65c5f 100644 --- a/src/main/java/org/asteriskjava/fastagi/AbstractMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/AbstractMappingStrategy.java @@ -16,38 +16,36 @@ */ package org.asteriskjava.fastagi; +import org.asteriskjava.lock.Lockable; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.io.File; import java.lang.reflect.Constructor; +import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; -import java.net.MalformedURLException; -import java.util.List; import java.util.ArrayList; -import java.io.File; - -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; +import java.util.List; /** - * Abstract base class for common mapping strategies. - *

+ * Abstract base class for common mapping strategies.
* If you implement your own mapping strategy you can derive from this class. * * @author srt * @since 0.3 */ -public abstract class AbstractMappingStrategy implements MappingStrategy -{ +public abstract class AbstractMappingStrategy extends Lockable implements MappingStrategy { /** * Reference to Asterisk-Java's logging subsystem. */ protected Log logger = LogFactory.getLog(getClass()); private static final String[] DEFAULT_SCRIPT_PATH = new String[]{"agi"}; - + private ClassLoader defaultClassLoader = null; @Override - public AgiScript determineScript(AgiRequest request, AgiChannel channel) - { + public AgiScript determineScript(AgiRequest request, AgiChannel channel) { return determineScript(request); } @@ -55,43 +53,38 @@ public AgiScript determineScript(AgiRequest request, AgiChannel channel) /** * Returns the ClassLoader to use for loading AgiScript classes and load - * other resources like the mapping properties file.

- * By default this method returns a class loader that searches for classes in the - * "agi" subdirectory (if it exists) and uses the context class loader of the - * current thread as the parent class loader.

- * You can override this method if you prefer using a different class loader. + * other resources like the mapping properties file. + *

+ * By default this method returns a class loader that searches for classes + * in the "agi" subdirectory (if it exists) and uses the context class + * loader of the current thread as the parent class loader. + *

+ * You can override this method if you prefer using a different class + * loader. * * @return the ClassLoader to use for loading AgiScript classes and load - * other resources like the mapping properties file. + * other resources like the mapping properties file. * @since 1.0.0 */ - protected synchronized ClassLoader getClassLoader() - { - if (defaultClassLoader == null) - { + protected synchronized ClassLoader getClassLoader() { + if (defaultClassLoader == null) { final ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader(); - final List dirUrls = new ArrayList(); + final List dirUrls = new ArrayList<>(); - for (String scriptPathEntry : DEFAULT_SCRIPT_PATH) - { + for (String scriptPathEntry : DEFAULT_SCRIPT_PATH) { final File scriptDir = new File(scriptPathEntry); - if (! scriptDir.isDirectory()) - { + if (!scriptDir.isDirectory()) { continue; } - try - { + try { dirUrls.add(scriptDir.toURI().toURL()); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { // should not happen } } - if (dirUrls.size() == 0) - { + if (dirUrls.isEmpty()) { return parentClassLoader; } @@ -107,12 +100,11 @@ protected synchronized ClassLoader getClassLoader() * @param className Class name of the AGI script. The class must implement * {@link AgiScript}. * @return the created instance of the AGI script class. If the instance - * can't be created an error is logged and null is - * returned. + * can't be created an error is logged and null is + * returned. */ @SuppressWarnings("unchecked") - protected AgiScript createAgiScriptInstance(String className) - { + protected AgiScript createAgiScriptInstance(String className) { Class tmpClass; Class agiScriptClass; Constructor constructor; @@ -120,32 +112,25 @@ protected AgiScript createAgiScriptInstance(String className) agiScript = null; - try - { + try { tmpClass = getClassLoader().loadClass(className); - } - catch (ClassNotFoundException e1) - { + } catch (ClassNotFoundException e1) { logger.debug("Unable to create AgiScript instance of type " + className + ": Class not found, make sure the class exists and is available on the CLASSPATH"); return null; } - if (!AgiScript.class.isAssignableFrom(tmpClass)) - { + if (!AgiScript.class.isAssignableFrom(tmpClass)) { logger.warn("Unable to create AgiScript instance of type " + className + ": Class does not implement the AgiScript interface"); return null; } agiScriptClass = (Class) tmpClass; - try - { + try { constructor = agiScriptClass.getConstructor(); agiScript = constructor.newInstance(); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Unable to create AgiScript instance of type " + className, e); } diff --git a/src/main/java/org/asteriskjava/fastagi/AgiChannel.java b/src/main/java/org/asteriskjava/fastagi/AgiChannel.java index 9229e583b..4a0398b73 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiChannel.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiChannel.java @@ -16,22 +16,20 @@ */ package org.asteriskjava.fastagi; +import org.asteriskjava.AsteriskVersion; import org.asteriskjava.fastagi.command.AgiCommand; import org.asteriskjava.fastagi.reply.AgiReply; - /** * Provides the functionality to send AgiCommands to Asterisk while handling an - * AgiRequest. - *

+ * AgiRequest.
* This interface is supposed to be used by AgiScripts for interaction with the * Asterisk server. * * @author srt * @version $Id$ */ -public interface AgiChannel -{ +public interface AgiChannel { /** * Returns the name of the channel. * @@ -47,17 +45,18 @@ public interface AgiChannel String getUniqueId(); /** - * Returns the reply received in response to the last command sent to Asterisk. + * Returns the reply received in response to the last command sent to + * Asterisk. * - * @return the reply received in response to the last command sent to Asterisk - * or null if none has yet been received. + * @return the reply received in response to the last command sent to + * Asterisk or null if none has yet been received. * @since 1.0.0 */ AgiReply getLastReply(); /** - * Sends a command to asterisk and returns the corresponding reply. The reply is also - * available through {@link #getLastReply()}. + * Sends a command to asterisk and returns the corresponding reply. The + * reply is also available through {@link #getLastReply()}. * * @param command the command to send. * @return the reply of the asterisk server containing the return value. @@ -85,7 +84,8 @@ public interface AgiChannel * in the future. * * @param time the number of seconds before this channel is automatically - * hung up.

+ * hung up. + *

* 0 disables the autohangup feature. * @since 0.2 */ @@ -94,7 +94,8 @@ public interface AgiChannel /** * Sets the caller id on the current channel. * - * @param callerId the raw caller id to set, for example "John Doe<1234>". + * @param callerId the raw caller id to set, for example + * "John Doe<1234>". * @since 0.2 */ void setCallerId(String callerId) throws AgiException; @@ -110,7 +111,7 @@ public interface AgiChannel * Plays music on hold from the given music on hold class. * * @param musicOnHoldClass the music on hold class to play music from as - * configures in Asterisk's . + * configures in Asterisk's musiconhold.conf. * @since 0.2 */ void playMusicOnHold(String musicOnHoldClass) throws AgiException; @@ -123,7 +124,8 @@ public interface AgiChannel void stopMusicOnHold() throws AgiException; /** - * Returns the status of the channel.

+ * Returns the status of the channel. + *

* Return values: *

    *
  • 0 Channel is down and available @@ -158,7 +160,8 @@ public interface AgiChannel * by starting to enter digits. * * @param file the name of the file to play - * @param timeout the timeout in milliseconds to wait for user input.

    + * @param timeout the timeout in milliseconds to wait for user input. + *

    * 0 means standard timeout value, -1 means "ludicrous time" * (essentially never times out). * @return a String containing the DTMF the user entered @@ -173,7 +176,8 @@ public interface AgiChannel * digits. * * @param file the name of the file to play - * @param timeout the timeout in milliseconds to wait for user input.

    + * @param timeout the timeout in milliseconds to wait for user input. + *

    * 0 means standard timeout value, -1 means "ludicrous time" * (essentially never times out). * @param maxDigits the maximum number of digits the user is allowed to @@ -181,12 +185,11 @@ public interface AgiChannel * @return a String containing the DTMF the user entered * @since 0.2 */ - String getData(String file, long timeout, int maxDigits) - throws AgiException; + String getData(String file, long timeout, int maxDigits) throws AgiException; /** * Plays the given file, and waits for the user to press one of the given - * digits. If none of the esacpe digits is pressed while streaming the file + * digits. If none of the escape digits is pressed while streaming the file * it waits for the default timeout of 5 seconds still waiting for the user * to press a digit. * @@ -200,7 +203,7 @@ String getData(String file, long timeout, int maxDigits) /** * Plays the given file, and waits for the user to press one of the given - * digits. If none of the esacpe digits is pressed while streaming the file + * digits. If none of the escape digits is pressed while streaming the file * it waits for the specified timeout still waiting for the user to press a * digit. * @@ -212,8 +215,25 @@ String getData(String file, long timeout, int maxDigits) * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ - char getOption(String file, String escapeDigits, long timeout) - throws AgiException; + char getOption(String file, String escapeDigits, long timeout) throws AgiException; + + /** + * since at least asterisk 13 + * + * @param room + * @param profile + * @throws AgiException + */ + void confbridge(String room, String profile) throws AgiException; + + /** + * since at least asterisk 1.4 + * + * @param room + * @param options + * @throws AgiException + */ + void meetme(String room, String options) throws AgiException; /** * Executes the given command. @@ -221,7 +241,7 @@ char getOption(String file, String escapeDigits, long timeout) * @param application the name of the application to execute, for example * "Dial". * @return the return code of the application of -2 if the application was - * not found. + * not found. * @since 0.2 */ int exec(String application) throws AgiException; @@ -234,7 +254,7 @@ char getOption(String file, String escapeDigits, long timeout) * @param options the parameters to pass to the application, for example * "SIP/123". * @return the return code of the application of -2 if the application was - * not found. + * not found. * @since 0.2 */ int exec(String application, String... options) throws AgiException; @@ -286,8 +306,8 @@ char getOption(String file, String escapeDigits, long timeout) char streamFile(String file, String escapeDigits) throws AgiException; /** - * Plays the given file starting at the specified offset and allows the - * user to escape by pressing one of the given digit. + * Plays the given file starting at the specified offset and allows the user + * to escape by pressing one of the given digit. * * @param file name of the file to play. * @param escapeDigits a String containing the DTMF digits that allow the @@ -399,22 +419,23 @@ char getOption(String file, String escapeDigits, long timeout) char sayTime(long time, String escapeDigits) throws AgiException; /** - * Returns the value of the current channel or global variable.

    - * Supports functions and builtin variables. To retrieve - * the caller id you can use getVariable("CALLERID(name)");

    - * Does not support expression parsing, use {@link #getFullVariable(String)} in those cases. + * Returns the value of the current channel or global variable.
    + * Supports functions and builtin variables. To retrieve the caller id you + * can use getVariable("CALLERID(name)");
    + * Does not support expression parsing, use {@link #getFullVariable(String)} + * in those cases. * * @param name the name of the variable (or function call) to retrieve. - * @return the value of the given variable or null if not - * set. + * @return the value of the given variable or null if not set. * @since 0.2 */ String getVariable(String name) throws AgiException; /** - * Sets the value of the current channel or global variable to a new value.

    - * Supports functions and builtin variables. To set the caller id - * you can use setVariable("CALLERID(name)", "John Doe"); + * Sets the value of the current channel or global variable to a new value. + *
    + * Supports functions and builtin variables. To set the caller id you can + * use setVariable("CALLERID(name)", "John Doe"); * * @param name the name of the variable (or function call) to set. * @param value the new value to set. @@ -433,33 +454,37 @@ char getOption(String file, String escapeDigits, long timeout) char waitForDigit(int timeout) throws AgiException; /** - * Evaluates a channel expression for the current channel. To extract - * the caller id use getFullVariable("${CALLERID(name)}");.

    + * Evaluates a channel expression for the current channel. To extract the + * caller id use getFullVariable("${CALLERID(name)}");. + *

    * Available since Asterisk 1.2. * * @param expr the expression to evaluate. * @return the value of the given expression or null if not - * set. + * set. * @see #getVariable(String) * @since 0.2 */ String getFullVariable(String expr) throws AgiException; /** - * Evaluates a channel expression for the given channel.To extract - * the caller id of channel use getFullVariable("${CALLERID(name)}", "SIP/john-0085d860");.

    + * Evaluates a channel expression for the given channel.To extract the + * caller id of channel use + * getFullVariable("${CALLERID(name)}", "SIP/john-0085d860");. + *

    * Available since Asterisk 1.2. * * @param expr the the expression to evaluate. * @param channel the name of the channel. * @return the value of the given expression or null if not - * set. + * set. * @since 0.2 */ String getFullVariable(String expr, String channel) throws AgiException; /** - * Says the given time.

    + * Says the given time. + *

    * Available since Asterisk 1.2. * * @param time the time to say in seconds elapsed since 00:00:00 on January @@ -470,7 +495,8 @@ char getOption(String file, String escapeDigits, long timeout) /** * Says the given time and allows interruption by one of the given escape - * digits.

    + * digits. + *

    * Available since Asterisk 1.2. * * @param time the time to say in seconds elapsed since 00:00:00 on January @@ -484,7 +510,8 @@ char getOption(String file, String escapeDigits, long timeout) /** * Says the given time in the given format and allows interruption by one of - * the given escape digits.

    + * the given escape digits. + *

    * Available since Asterisk 1.2. * * @param time the time to say in seconds elapsed since 00:00:00 on January @@ -499,7 +526,8 @@ char getOption(String file, String escapeDigits, long timeout) /** * Says the given time in the given format and timezone and allows - * interruption by one of the given escape digits.

    + * interruption by one of the given escape digits. + *

    * Available since Asterisk 1.2. * * @param time the time to say in seconds elapsed since 00:00:00 on January @@ -512,23 +540,22 @@ char getOption(String file, String escapeDigits, long timeout) * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ - char sayDateTime(long time, String escapeDigits, String format, - String timezone) throws AgiException; + char sayDateTime(long time, String escapeDigits, String format, String timezone) throws AgiException; /** * Retrieves an entry in the Asterisk database for a given family and key. * * @param family the family of the entry to retrieve. * @param key the key of the entry to retrieve. - * @return the value of the given family and key or null if there - * is no such value. + * @return the value of the given family and key or null if + * there is no such value. * @since 0.3 */ String databaseGet(String family, String key) throws AgiException; /** - * Adds or updates an entry in the Asterisk database for a given family, key, - * and value. + * Adds or updates an entry in the Asterisk database for a given family, + * key, and value. * * @param family the family of the entry to add or update. * @param key the key of the entry to add or update. @@ -555,8 +582,8 @@ char sayDateTime(long time, String escapeDigits, String format, void databaseDelTree(String family) throws AgiException; /** - * Deletes all entries of a given family in the Asterisk database that have a key - * that starts with a given prefix. + * Deletes all entries of a given family in the Asterisk database that have + * a key that starts with a given prefix. * * @param family the family of the entries to delete. * @param keytree the prefix of the keys of the entries to delete. @@ -585,8 +612,7 @@ char sayDateTime(long time, String escapeDigits, String format, * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.3 */ - char recordFile(String file, String format, String escapeDigits, - int timeout) throws AgiException; + char recordFile(String file, String format, String escapeDigits, int timeout) throws AgiException; /** * Record to a file until a given dtmf digit in the sequence is received. @@ -605,12 +631,12 @@ char recordFile(String file, String format, String escapeDigits, * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.3 */ - char recordFile(String file, String format, String escapeDigits, - int timeout, int offset, boolean beep, int maxSilence) throws AgiException; + char recordFile(String file, String format, String escapeDigits, int timeout, int offset, boolean beep, int maxSilence) + throws AgiException; /** - * Plays the given file allowing the user to control the streaming by - * using "#" for forward and "*" for rewind. + * Plays the given file allowing the user to control the streaming by using + * "#" for forward and "*" for rewind. * * @param file the name of the file to stream, must not include extension. * @since 0.3 @@ -618,9 +644,9 @@ char recordFile(String file, String format, String escapeDigits, void controlStreamFile(String file) throws AgiException; /** - * Plays the given file allowing the user to control the streaming by - * using "#" for forward and "*" for rewind. Pressing one of the escape - * digits stops streaming. + * Plays the given file allowing the user to control the streaming by using + * "#" for forward and "*" for rewind. Pressing one of the escape digits + * stops streaming. * * @param file the name of the file to stream, must not include extension. * @param escapeDigits contains the digits that allow the user to interrupt @@ -631,10 +657,9 @@ char recordFile(String file, String format, String escapeDigits, char controlStreamFile(String file, String escapeDigits) throws AgiException; /** - * Plays the given file allowing the user to control the streaming by - * using "#" for forward and "*" for rewind. Pressing one of the escape - * digits stops streaming. The file is played starting at the indicated - * offset. + * Plays the given file allowing the user to control the streaming by using + * "#" for forward and "*" for rewind. Pressing one of the escape digits + * stops streaming. The file is played starting at the indicated offset. * * @param file the name of the file to stream, must not include extension. * @param escapeDigits contains the digits that allow the user to interrupt @@ -647,30 +672,30 @@ char recordFile(String file, String format, String escapeDigits, char controlStreamFile(String file, String escapeDigits, int offset) throws AgiException; /** - * Plays the given file allowing the user to control the streaming by - * using forwardDigit for forward, rewindDigit for rewind and pauseDigit for pause. - * Pressing one of the escape digits stops streaming. - * The file is played starting at the indicated - * offset, use 0 to start at the beginning. + * Plays the given file allowing the user to control the streaming by using + * forwardDigit for forward, rewindDigit for rewind and pauseDigit for + * pause. Pressing one of the escape digits stops streaming. The file is + * played starting at the indicated offset, use 0 to start at the beginning. * * @param file the name of the file to stream, must not include extension. * @param escapeDigits contains the digits that allow the user to interrupt * this command. May be null if you don't want the * user to interrupt. - * @param offset the offset samples to skip before streaming, use 0 to start at the beginning. + * @param offset the offset samples to skip before streaming, use 0 to start + * at the beginning. * @param forwardDigit the digit for fast forward. * @param rewindDigit the digit for rewind. * @param pauseDigit the digit for pause and unpause. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.3 */ - char controlStreamFile(String file, String escapeDigits, - int offset, String forwardDigit, String rewindDigit, + char controlStreamFile(String file, String escapeDigits, int offset, String forwardDigit, String rewindDigit, String pauseDigit) throws AgiException; /** - * Creates a speech object that uses the default speech engine. The speech object is - * used by the other speech methods and must be created before they are called. + * Creates a speech object that uses the default speech engine. The speech + * object is used by the other speech methods and must be created before + * they are called. * * @throws AgiSpeechException if the speech object cannot be created. * @see #speechDestroy() @@ -679,8 +704,9 @@ char controlStreamFile(String file, String escapeDigits, void speechCreate() throws AgiException; /** - * Creates a speech object that uses the given speech engine. The speech object is - * used by the other speech methods and must be created before they are called. + * Creates a speech object that uses the given speech engine. The speech + * object is used by the other speech methods and must be created before + * they are called. * * @param engine the name of the speech engine. For example "lumenvox". * @throws AgiSpeechException if the speech object cannot be created. @@ -709,12 +735,16 @@ char controlStreamFile(String file, String escapeDigits, void speechDestroy() throws AgiException; /** - * Loads the specified grammar. The grammer is then available for calls to {@link #speechActivateGrammar(String)} - * under the given name. Eplicitly loading a grammer is only required if the grammer has not been defined in the - * speech engine configuration, e.g. the [grammars] section of lumenvox.conf. + * Loads the specified grammar. The grammer is then available for calls to + * {@link #speechActivateGrammar(String)} under the given name. Eplicitly + * loading a grammer is only required if the grammer has not been defined in + * the speech engine configuration, e.g. the [grammars] section + * of lumenvox.conf. * - * @param label the name of the grammar, used for subsequent calls to {@link #speechActivateGrammar(String)}, - * {@link #speechDeactivateGrammar(String)} and {@link #speechUnloadGrammar(String)}. + * @param label the name of the grammar, used for subsequent calls to + * {@link #speechActivateGrammar(String)}, + * {@link #speechDeactivateGrammar(String)} and + * {@link #speechUnloadGrammar(String)}. * @param path the path to the grammar to load. * @throws AgiSpeechException if the grammar cannot be loaded. * @see #speechUnloadGrammar(String) @@ -758,7 +788,8 @@ char controlStreamFile(String file, String escapeDigits, * Plays the given prompt while listening for speech and DTMF. * * @param prompt the name of the file to stream, must not include extension. - * @param timeout the timeout in milliseconds to wait for user input.

    + * @param timeout the timeout in milliseconds to wait for user input. + *

    * 0 means standard timeout value, -1 means "ludicrous time" * (essentially never times out). * @return the recognition result @@ -770,20 +801,23 @@ char controlStreamFile(String file, String escapeDigits, * Plays the given prompt while listening for speech and DTMF. * * @param prompt the name of the file to stream, must not include extension. - * @param timeout the timeout in milliseconds to wait for user input.

    + * @param timeout the timeout in milliseconds to wait for user input. + *

    * 0 means standard timeout value, -1 means "ludicrous time" * (essentially never times out). - * @param offset the offset samples to skip before streaming, use 0 to start at the beginning. + * @param offset the offset samples to skip before streaming, use 0 to start + * at the beginning. * @return the recognition result * @since 1.0.0 */ SpeechRecognitionResult speechRecognize(String prompt, int timeout, int offset) throws AgiException, AgiSpeechException; /** - * Defines the point in the dialplan where the call will continue when the AGI script - * returns.

    - * This is a shortcut for calling {@link #setContext(String)}, {@link #setExtension(String)} - * and {@link #setPriority(String)} in series. + * Defines the point in the dialplan where the call will continue when the + * AGI script returns. + *

    + * This is a shortcut for calling {@link #setContext(String)}, + * {@link #setExtension(String)} and {@link #setPriority(String)} in series. * * @param context the context for continuation upon exiting the application. * @param extension the extension for continuation upon exiting the @@ -798,8 +832,7 @@ char controlStreamFile(String file, String escapeDigits, void continueAt(String context, String extension, String priority) throws AgiException; /** - * Calls a subroutine in the dialplan - *

    + * Calls a subroutine in the dialplan
    * This method is available since Asterisk 1.6. * * @param context the context of the called subroutine. @@ -807,20 +840,45 @@ char controlStreamFile(String file, String escapeDigits, * @param priority the priority of the called extension. * @since 1.0.0 */ - public void gosub(String context, String extension, String priority) throws AgiException; + void gosub(String context, String extension, String priority) throws AgiException; /** - * Calls a subroutine in the dialplan

    - *

    + * Calls a subroutine in the dialplan + *

    + *
    * This method is available since Asterisk 1.6. * * @param context the context of the called subroutine. * @param extension the extension in the called context. * @param priority the priority of the called extension. - * @param arguments optional arguments to be passed to the subroutine. They should be separated by comma. - * They will accessible in the form of ${ARG1}, ${ARG2}, etc in the subroutine body. + * @param arguments optional arguments to be passed to the subroutine. They + * should be separated by comma. They will accessible in the form + * of ${ARG1}, ${ARG2}, etc in the subroutine body. * @since 1.0.0 */ - public void gosub(String context, String extension, String priority, String... arguments) throws AgiException; + void gosub(String context, String extension, String priority, String... arguments) throws AgiException; + + /** + * invoke the dial command + * + * @param target + * @param timeout + * @param options + * @throws AgiException + */ + void dial(String target, int timeout, String options) throws AgiException; + + /** + * invoke the bridge command + * + * @param channelName + * @param options + * @throws AgiException + */ + void bridge(String channelName, String options) throws AgiException; + + void queue(String queue) throws AgiException; + + AsteriskVersion getAsteriskVersion(); } diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelFactory.java b/src/main/java/org/asteriskjava/fastagi/AgiChannelFactory.java old mode 100755 new mode 100644 similarity index 73% rename from src/main/java/org/asteriskjava/fastagi/internal/AgiChannelFactory.java rename to src/main/java/org/asteriskjava/fastagi/AgiChannelFactory.java index 01a221f25..362031f4c --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelFactory.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiChannelFactory.java @@ -1,26 +1,22 @@ -package org.asteriskjava.fastagi.internal; - -import org.asteriskjava.fastagi.AgiChannel; -import org.asteriskjava.fastagi.AgiRequest; - -/** - * An AgiChannelFactory creates instances of AgiChannels, - * that are passed to agi scripts. - *

    - * An instance of the AgiChannelFactory can be passed to the - * DefaultAgiServer's constructor. - * - * @since 1.0.0 - */ -public interface AgiChannelFactory -{ - /** - * Creates a new AgiChannel. - * - * @param request the request to build the channel for. - * @param agiWriter the writer. - * @param agiReader the reader. - * @return the created channel. - */ - AgiChannel createAgiChannel(AgiRequest request, AgiWriter agiWriter, AgiReader agiReader); -} +package org.asteriskjava.fastagi; + +/** + * An AgiChannelFactory creates instances of AgiChannels, + * that are passed to agi scripts. + *

    + * An instance of the AgiChannelFactory can be passed to the + * DefaultAgiServer's constructor. + * + * @since 1.0.0 + */ +public interface AgiChannelFactory { + /** + * Creates a new AgiChannel. + * + * @param request the request to build the channel for. + * @param agiWriter the writer. + * @param agiReader the reader. + * @return the created channel. + */ + AgiChannel createAgiChannel(AgiRequest request, AgiWriter agiWriter, AgiReader agiReader); +} diff --git a/src/main/java/org/asteriskjava/fastagi/AgiException.java b/src/main/java/org/asteriskjava/fastagi/AgiException.java index 5aa33eb30..812f647b3 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiException.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiException.java @@ -18,12 +18,11 @@ /** * Base class for all AGI specific exceptions. - * + * * @author srt * @version $Id$ */ -public class AgiException extends Exception -{ +public class AgiException extends Exception { /** * Serial version identifier. */ @@ -31,22 +30,20 @@ public class AgiException extends Exception /** * Creates a new AgiException with the given message. - * + * * @param message a message describing the AgiException. */ - public AgiException(String message) - { + public AgiException(String message) { super(message); } /** * Creates a new AgiException with the given message and cause. - * + * * @param message a message describing the AgiException. - * @param cause the throwable that caused this exception. + * @param cause the throwable that caused this exception. */ - public AgiException(String message, Throwable cause) - { + public AgiException(String message, Throwable cause) { super(message, cause); } } diff --git a/src/main/java/org/asteriskjava/fastagi/AgiHangupException.java b/src/main/java/org/asteriskjava/fastagi/AgiHangupException.java index f9a37b831..cc7715695 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiHangupException.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiHangupException.java @@ -21,25 +21,23 @@ * processing the {@link org.asteriskjava.fastagi.AgiRequest}.

    * Up to Asterisk 1.4 hanging up the channel also closes the TCP connection, * since Asterisk 1.6 the connection is kept alive but commands that - * require an active channel return status code + * require an active channel return status code * {@link org.asteriskjava.fastagi.reply.AgiReply#SC_DEAD_CHANNEL}. Both events * are translated to an AgiHangupException. - * + * * @author srt * @version $Id$ */ -public class AgiHangupException extends AgiException -{ +public class AgiHangupException extends AgiException { /** * Serial version identifier. */ private static final long serialVersionUID = 3256444698691252274L; - + /** * Creates a new AgiHangupException. */ - public AgiHangupException() - { + public AgiHangupException() { super("Channel was hung up."); } } diff --git a/src/main/java/org/asteriskjava/fastagi/AgiNetworkException.java b/src/main/java/org/asteriskjava/fastagi/AgiNetworkException.java index b6d566009..eeeb9a55a 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiNetworkException.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiNetworkException.java @@ -19,12 +19,11 @@ /** * The AgiNetworkException usally wraps an IOException denoting a network * problem while talking to the Asterisk server. - * + * * @author srt * @version $Id$ */ -public class AgiNetworkException extends AgiException -{ +public class AgiNetworkException extends AgiException { /** * Serial version identifier. */ @@ -32,12 +31,11 @@ public class AgiNetworkException extends AgiException /** * Creates a new AgiNetworkException with the given message and cause. - * + * * @param message a message describing the AgiException. - * @param cause the throwable that caused this exception. + * @param cause the throwable that caused this exception. */ - public AgiNetworkException(String message, Throwable cause) - { + public AgiNetworkException(String message, Throwable cause) { super(message, cause); } } diff --git a/src/main/java/org/asteriskjava/fastagi/AgiOperations.java b/src/main/java/org/asteriskjava/fastagi/AgiOperations.java index b94820039..a33b58ac5 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiOperations.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiOperations.java @@ -16,6 +16,7 @@ */ package org.asteriskjava.fastagi; +import org.asteriskjava.AsteriskVersion; import org.asteriskjava.fastagi.command.AgiCommand; import org.asteriskjava.fastagi.internal.AgiConnectionHandler; import org.asteriskjava.fastagi.reply.AgiReply; @@ -23,54 +24,48 @@ /** * AgiOperations provides some convinience methods that wrap the various * {@link AgiCommand AgiCommands}. - * - * @since 0.3 + * * @author srt * @version $Id$ + * @since 0.3 */ -public class AgiOperations implements AgiChannel -{ +public class AgiOperations implements AgiChannel { private final AgiChannel channel; /** * Creates a new instance that operates on the channel attached to the * current thread. */ - public AgiOperations() - { + public AgiOperations() { this.channel = null; } /** * Creates a new instance that operates on the given channel. - * + * * @param channel the channel to operate on. */ - public AgiOperations(AgiChannel channel) - { + public AgiOperations(AgiChannel channel) { this.channel = channel; } /** * Returns the channel to operate on. - * + * * @return the channel to operate on. * @throws IllegalStateException if no {@link AgiChannel} is bound to the - * current channel and no channel has been passed to the - * constructor. + * current channel and no channel has been passed to the + * constructor. */ - protected AgiChannel getChannel() - { + protected AgiChannel getChannel() { AgiChannel threadBoundChannel; - if (channel != null) - { + if (channel != null) { return channel; } threadBoundChannel = AgiConnectionHandler.getChannel(); - if (threadBoundChannel == null) - { + if (threadBoundChannel == null) { throw new IllegalStateException("Trying to send command from an invalid thread"); } @@ -79,410 +74,316 @@ protected AgiChannel getChannel() /* The following methods simply delegate to #getChannel() */ - public String getName() - { + public String getName() { return getChannel().getName(); } - public String getUniqueId() - { + public String getUniqueId() { return getChannel().getUniqueId(); } - public AgiReply getLastReply() - { + public AgiReply getLastReply() { return getChannel().getLastReply(); } - public AgiReply sendCommand(AgiCommand command) - throws AgiException - { + public AgiReply sendCommand(AgiCommand command) throws AgiException { return getChannel().sendCommand(command); } - public void answer() - throws AgiException - { + public void answer() throws AgiException { getChannel().answer(); } - public void hangup() - throws AgiException - { + public void hangup() throws AgiException { getChannel().hangup(); } - public void setAutoHangup(int time) - throws AgiException - { + public void setAutoHangup(int time) throws AgiException { getChannel().setAutoHangup(time); } - public void setCallerId(String callerId) - throws AgiException - { + public void setCallerId(String callerId) throws AgiException { getChannel().setCallerId(callerId); } - public void playMusicOnHold() - throws AgiException - { + public void playMusicOnHold() throws AgiException { getChannel().playMusicOnHold(); } - public void playMusicOnHold(String musicOnHoldClass) - throws AgiException - { + public void playMusicOnHold(String musicOnHoldClass) throws AgiException { getChannel().playMusicOnHold(musicOnHoldClass); } - public void stopMusicOnHold() - throws AgiException - { + public void stopMusicOnHold() throws AgiException { getChannel().stopMusicOnHold(); } - public int getChannelStatus() - throws AgiException - { + public int getChannelStatus() throws AgiException { return getChannel().getChannelStatus(); } - public String getData(String file) - throws AgiException - { + public String getData(String file) throws AgiException { return getChannel().getData(file); } - public String getData(String file, long timeout) - throws AgiException - { + public String getData(String file, long timeout) throws AgiException { return getChannel().getData(file, timeout); } - public String getData(String file, long timeout, int maxDigits) - throws AgiException - { + public String getData(String file, long timeout, int maxDigits) throws AgiException { return getChannel().getData(file, timeout, maxDigits); } - public char getOption(String file, String escapeDigits) - throws AgiException - { + public char getOption(String file, String escapeDigits) throws AgiException { return getChannel().getOption(file, escapeDigits); } - public char getOption(String file, String escapeDigits, long timeout) - throws AgiException - { + public char getOption(String file, String escapeDigits, long timeout) throws AgiException { return getChannel().getOption(file, escapeDigits, timeout); } - public int exec(String application) - throws AgiException - { + public int exec(String application) throws AgiException { return getChannel().exec(application); } - public int exec(String application, String... options) - throws AgiException - { + public int exec(String application, String... options) throws AgiException { return getChannel().exec(application, options); } - public void setContext(String context) - throws AgiException - { + public void setContext(String context) throws AgiException { getChannel().setContext(context); } - public void setExtension(String extension) - throws AgiException - { + public void setExtension(String extension) throws AgiException { getChannel().setExtension(extension); } - public void setPriority(String priority) - throws AgiException - { + public void setPriority(String priority) throws AgiException { getChannel().setPriority(priority); } - public void streamFile(String file) - throws AgiException - { + public void streamFile(String file) throws AgiException { getChannel().streamFile(file); } - public char streamFile(String file, String escapeDigits) - throws AgiException - { + public char streamFile(String file, String escapeDigits) throws AgiException { return getChannel().streamFile(file, escapeDigits); } - public char streamFile(String file, String escapeDigits, int offset) - throws AgiException - { + public char streamFile(String file, String escapeDigits, int offset) throws AgiException { return getChannel().streamFile(file, escapeDigits, offset); } - public void sayDigits(String digits) - throws AgiException - { + public void sayDigits(String digits) throws AgiException { getChannel().sayDigits(digits); } - public char sayDigits(String digits, String escapeDigits) - throws AgiException - { + public char sayDigits(String digits, String escapeDigits) throws AgiException { return getChannel().sayDigits(digits, escapeDigits); } - public void sayNumber(String number) - throws AgiException - { + public void sayNumber(String number) throws AgiException { getChannel().sayNumber(number); } - public char sayNumber(String number, String escapeDigits) - throws AgiException - { + public char sayNumber(String number, String escapeDigits) throws AgiException { return getChannel().sayNumber(number, escapeDigits); } - public void sayPhonetic(String text) - throws AgiException - { + public void sayPhonetic(String text) throws AgiException { getChannel().sayPhonetic(text); } - public char sayPhonetic(String text, String escapeDigits) - throws AgiException - { + public char sayPhonetic(String text, String escapeDigits) throws AgiException { return getChannel().sayPhonetic(text, escapeDigits); } - public void sayAlpha(String text) - throws AgiException - { + public void sayAlpha(String text) throws AgiException { getChannel().sayAlpha(text); } - public char sayAlpha(String text, String escapeDigits) - throws AgiException - { + public char sayAlpha(String text, String escapeDigits) throws AgiException { return getChannel().sayAlpha(text, escapeDigits); } - public void sayTime(long time) - throws AgiException - { + public void sayTime(long time) throws AgiException { getChannel().sayTime(time); } - public char sayTime(long time, String escapeDigits) - throws AgiException - { + public char sayTime(long time, String escapeDigits) throws AgiException { return getChannel().sayTime(time, escapeDigits); } - public String getVariable(String name) - throws AgiException - { + public String getVariable(String name) throws AgiException { return getChannel().getVariable(name); } - public void setVariable(String name, String value) - throws AgiException - { + public void setVariable(String name, String value) throws AgiException { getChannel().setVariable(name, value); } - public char waitForDigit(int timeout) - throws AgiException - { + public char waitForDigit(int timeout) throws AgiException { return getChannel().waitForDigit(timeout); } - public String getFullVariable(String name) - throws AgiException - { + public String getFullVariable(String name) throws AgiException { return getChannel().getFullVariable(name); } - public String getFullVariable(String name, String channel) - throws AgiException - { + public String getFullVariable(String name, String channel) throws AgiException { return getChannel().getFullVariable(name, channel); } - public void sayDateTime(long time) - throws AgiException - { + public void sayDateTime(long time) throws AgiException { getChannel().sayDateTime(time); } - public char sayDateTime(long time, String escapeDigits) - throws AgiException - { + public char sayDateTime(long time, String escapeDigits) throws AgiException { return getChannel().sayDateTime(time, escapeDigits); } - public char sayDateTime(long time, String escapeDigits, String format) - throws AgiException - { + public char sayDateTime(long time, String escapeDigits, String format) throws AgiException { return getChannel().sayDateTime(time, escapeDigits, format); } - public char sayDateTime(long time, String escapeDigits, String format, String timezone) - throws AgiException - { + public char sayDateTime(long time, String escapeDigits, String format, String timezone) throws AgiException { return getChannel().sayDateTime(time, escapeDigits, format, timezone); } - public String databaseGet(String family, String key) - throws AgiException - { + public String databaseGet(String family, String key) throws AgiException { return getChannel().databaseGet(family, key); } - public void databasePut(String family, String key, String value) - throws AgiException - { + public void databasePut(String family, String key, String value) throws AgiException { getChannel().databasePut(family, key, value); } - public void databaseDel(String family, String key) - throws AgiException - { + public void databaseDel(String family, String key) throws AgiException { getChannel().databaseDel(family, key); } - public void databaseDelTree(String family) - throws AgiException - { + public void databaseDelTree(String family) throws AgiException { getChannel().databaseDelTree(family); } - public void databaseDelTree(String family, String keytree) - throws AgiException - { + public void databaseDelTree(String family, String keytree) throws AgiException { getChannel().databaseDelTree(family, keytree); } - public void verbose(String message, int level) - throws AgiException - { + public void verbose(String message, int level) throws AgiException { getChannel().verbose(message, level); } - public char recordFile(String file, String format, String escapeDigits, int timeout) - throws AgiException - { + public char recordFile(String file, String format, String escapeDigits, int timeout) throws AgiException { return getChannel().recordFile(file, format, escapeDigits, timeout); } - public char recordFile(String file, String format, String escapeDigits, int timeout, int offset, boolean beep, int maxSilence) - throws AgiException - { + public char recordFile(String file, String format, String escapeDigits, int timeout, int offset, boolean beep, + int maxSilence) throws AgiException { return getChannel().recordFile(file, format, escapeDigits, timeout, offset, beep, maxSilence); } - public void controlStreamFile(String file) - throws AgiException - { + public void controlStreamFile(String file) throws AgiException { getChannel().controlStreamFile(file); } - public char controlStreamFile(String file, String escapeDigits) - throws AgiException - { + public char controlStreamFile(String file, String escapeDigits) throws AgiException { return getChannel().controlStreamFile(file, escapeDigits); } - public char controlStreamFile(String file, String escapeDigits, int offset) - throws AgiException - { + public char controlStreamFile(String file, String escapeDigits, int offset) throws AgiException { return getChannel().controlStreamFile(file, escapeDigits, offset); } - public char controlStreamFile(String file, String escapeDigits, int offset, String forwardDigit, String rewindDigit, String pauseDigit) - throws AgiException - { + public char controlStreamFile(String file, String escapeDigits, int offset, String forwardDigit, String rewindDigit, + String pauseDigit) throws AgiException { return getChannel().controlStreamFile(file, escapeDigits, offset, forwardDigit, rewindDigit, pauseDigit); } - public void speechCreate() throws AgiException - { + public void speechCreate() throws AgiException { getChannel().speechCreate(); } - public void speechCreate(String engine) - throws AgiException - { + public void speechCreate(String engine) throws AgiException { getChannel().speechCreate(engine); } - public void speechSet(String name, String value) - throws AgiException - { + public void speechSet(String name, String value) throws AgiException { getChannel().speechSet(name, value); } - public void speechDestroy() - throws AgiException - { + public void speechDestroy() throws AgiException { getChannel().speechDestroy(); } - public void speechLoadGrammar(String name, String path) - throws AgiException - { + public void speechLoadGrammar(String name, String path) throws AgiException { getChannel().speechLoadGrammar(name, path); } - public void speechUnloadGrammar(String name) - throws AgiException - { + public void speechUnloadGrammar(String name) throws AgiException { getChannel().speechUnloadGrammar(name); } - public void speechActivateGrammar(String name) - throws AgiException - { + public void speechActivateGrammar(String name) throws AgiException { getChannel().speechActivateGrammar(name); } - public void speechDeactivateGrammar(String name) - throws AgiException - { + public void speechDeactivateGrammar(String name) throws AgiException { getChannel().speechDeactivateGrammar(name); } - public SpeechRecognitionResult speechRecognize(String prompt, int timeout) - throws AgiException - { + public SpeechRecognitionResult speechRecognize(String prompt, int timeout) throws AgiException { return getChannel().speechRecognize(prompt, timeout); } - public SpeechRecognitionResult speechRecognize(String prompt, int timeout, int offset) - throws AgiException - { + public SpeechRecognitionResult speechRecognize(String prompt, int timeout, int offset) throws AgiException { return getChannel().speechRecognize(prompt, timeout, offset); } - public void continueAt(String context, String extension, String priority) throws AgiException - { + public void continueAt(String context, String extension, String priority) throws AgiException { getChannel().continueAt(context, extension, priority); } - - public void gosub(String context, String extension, String priority) throws AgiException - { - getChannel().gosub(context, extension, priority); + + public void gosub(String context, String extension, String priority) throws AgiException { + getChannel().gosub(context, extension, priority); + } + + public void gosub(String context, String extension, String priority, String... arguments) throws AgiException { + getChannel().gosub(context, extension, priority, arguments); + } + + @Override + public void confbridge(String room, String profile) throws AgiException { + getChannel().confbridge(room, profile); + + } + + @Override + public void meetme(String room, String options) throws AgiException { + getChannel().meetme(room, options); + + } + + @Override + public void dial(String target, int timeout, String options) throws AgiException { + getChannel().dial(target, timeout, options); + } - - public void gosub(String context, String extension, String priority, String... arguments) throws AgiException - { - getChannel().gosub(context, extension, priority, arguments); + + @Override + public void bridge(String channelName, String options) throws AgiException { + getChannel().bridge(channelName, options); + + } + + @Override + public void queue(String queue) throws AgiException { + getChannel().queue(queue); + + } + + @Override + public AsteriskVersion getAsteriskVersion() { + return getChannel().getAsteriskVersion(); } } diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AgiReader.java b/src/main/java/org/asteriskjava/fastagi/AgiReader.java similarity index 86% rename from src/main/java/org/asteriskjava/fastagi/internal/AgiReader.java rename to src/main/java/org/asteriskjava/fastagi/AgiReader.java index a29623ec9..0a50f7ae1 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiReader.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiReader.java @@ -14,24 +14,21 @@ * limitations under the License. * */ -package org.asteriskjava.fastagi.internal; +package org.asteriskjava.fastagi; -import org.asteriskjava.fastagi.AgiException; -import org.asteriskjava.fastagi.AgiRequest; import org.asteriskjava.fastagi.reply.AgiReply; /** * The AgiReader reads the replies from the network and parses them using a * ReplyBuilder. - * + * * @author srt * @version $Id$ */ -public interface AgiReader -{ +public interface AgiReader { /** * Reads the initial request data from Asterisk. - * + * * @return the request read. * @throws AgiException if the request can't be read. */ @@ -39,7 +36,7 @@ public interface AgiReader /** * Reads one reply to an AgiCommand from Asterisk. - * + * * @return the reply read. * @throws AgiException if the reply can't be read. */ diff --git a/src/main/java/org/asteriskjava/fastagi/AgiRequest.java b/src/main/java/org/asteriskjava/fastagi/AgiRequest.java index 20de53f15..d98b5b47c 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiRequest.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiRequest.java @@ -16,6 +16,8 @@ */ package org.asteriskjava.fastagi; +import org.asteriskjava.AsteriskVersion; + import java.net.InetAddress; import java.util.Map; @@ -23,15 +25,14 @@ * Provides client request information to an {@link org.asteriskjava.fastagi.AgiScript}.

    * This includes information about the channel the script is invoked on and * parameters passed from the dialplan. - * + * * @author srt * @version $Id$ */ -public interface AgiRequest -{ +public interface AgiRequest { /** * Returns a Map containing the raw request name/value pairs. - * + * * @return Map contain raw request name/value pairs. */ Map getRequest(); @@ -42,44 +43,44 @@ public interface AgiRequest * parameters stripped off.

    * As Async AGI does not yet pass a script parameter this property will * be null for requests received through Async AGI. - * + * * @return the name of the script to execute. */ String getScript(); /** * Returns the full URL of the requestURL in the form - * agi://host[:port][/script][?param1=value1¶m2=value2]. - * + * agi://host[:port][/script][?param1=value1&param2=value2]. + * * @return the full URL of the requestURL in the form - * agi://host[:port][/script][?param1=value1¶m2=value2]. + * agi://host[:port][/script][?param1=value1&param2=value2]. */ String getRequestURL(); /** * Returns the name of the channel. - * + * * @return the name of the channel. */ String getChannel(); /** * Returns the unqiue id of the channel. - * + * * @return the unqiue id of the channel. */ String getUniqueId(); /** * Returns the type of the channel, for example "SIP". - * + * * @return the type of the channel, for example "SIP". */ String getType(); /** * Returns the language set for the current channel, for example "en". - * + * * @return the language set for the current channel, for example "en". */ String getLanguage(); @@ -88,36 +89,37 @@ public interface AgiRequest * Returns the Caller*ID number, for example "1234".

    * Note: even with Asterisk 1.0 is contains only the numerical part * of the Caller ID. - * + * * @return the Caller*ID number, for example "1234", if no Caller*ID is set or it - * is "unknown" null is returned. + * is "unknown" null is returned. * @deprecated as of 0.3, use {@link #getCallerIdNumber()} instead. */ - @Deprecated String getCallerId(); + @Deprecated + String getCallerId(); /** * Returns the Caller*ID number, for example "1234".

    * Note: even with Asterisk 1.0 is contains only the numerical part * of the Caller ID. - * + * * @return the Caller*ID number, for example "1234", if no Caller*ID is set or it - * is "unknown" null is returned. + * is "unknown" null is returned. */ String getCallerIdNumber(); /** * Returns the the Caller*ID Name, for example "John Doe". - * + * * @return the the Caller*ID Name, for example "John Doe", if no Caller*ID - * Name is set or it is "unknown" null is returned. + * Name is set or it is "unknown" null is returned. */ String getCallerIdName(); /** * Returns the number, that has been dialed by the user. - * + * * @return the dialed number, if no DNID is available or it is "unknown" - * null is returned. + * null is returned. */ String getDnid(); @@ -125,51 +127,51 @@ public interface AgiRequest * If this call has been forwared, the number of the person doing the * redirect is returned (Redirected dialed number identification service).

    * This is usally only only available on PRI. - * + * * @return the number of the person doing the redirect, , if no RDNIS is - * available or it is "unknown" null is returned. + * available or it is "unknown" null is returned. */ String getRdnis(); /** * Returns the context in the dial plan from which the AGI script was * called. - * + * * @return the context in the dial plan from which the AGI script was - * called. + * called. */ String getContext(); /** * Returns the extension in the dial plan from which the AGI script was * called. - * + * * @return the extension in the dial plan from which the AGI script was - * called. + * called. */ String getExtension(); /** * Returns the priority of the dial plan entry the AGI script was * called from. - * + * * @return the priority of the dial plan entry the AGI script was - * called from. + * called from. */ Integer getPriority(); /** * Returns wheather this agi is passed audio (EAGI - Enhanced AGI).

    * Enhanced AGI is currently not supported on FastAGI. - * + * * @return Boolean.TRUE if this agi is passed audio, Boolean.FALSE - * otherwise. + * otherwise. */ Boolean getEnhanced(); /** * Returns the account code set for the call. - * + * * @return the account code set for the call. */ String getAccountCode(); @@ -177,7 +179,7 @@ public interface AgiRequest /** * Returns the Callerid presentation/screening.

    * Available since Asterisk 1.2. - * + * * @return the Callerid presentation/screening. * @since 0.2 */ @@ -186,7 +188,7 @@ public interface AgiRequest /** * Returns the Callerid ANI 2 (Info digits).

    * Available since Asterisk 1.2. - * + * * @return the Callerid ANI 2 (Info digits). * @since 0.2 */ @@ -195,7 +197,7 @@ public interface AgiRequest /** * Returns the Callerid Type of Number.

    * Available since Asterisk 1.2. - * + * * @return the Callerid Type of Number. * @since 0.2 */ @@ -204,7 +206,7 @@ public interface AgiRequest /** * Returns the Callerid Transit Network Select.

    * Available since Asterisk 1.2. - * + * * @return the Callerid Transit Network Select. * @since 0.2 */ @@ -219,9 +221,9 @@ public interface AgiRequest * If you use this method with a multivalued parameter, the value returned * is equal to the first value in the array returned by * getParameterValues. - * + * * @param name a String containing the name of the parameter whose value is - * requested. + * requested. * @return a String representing the single value of the parameter. * @see #getParameterValues(String) */ @@ -232,7 +234,7 @@ public interface AgiRequest * request parameter has, or * an empty array if the parameter does not exist.

    * If the parameter has a single value, the array has a length of 1. - * + * * @param name a String containing the name of the parameter whose value is requested. * @return an array of String objects containing the parameter's values. */ @@ -240,10 +242,10 @@ public interface AgiRequest /** * Returns a Map of the parameters of this request. - * + * * @return a java.util.Map containing parameter names as keys and parameter - * values as map values. The keys in the parameter map are of type - * String. The values in the parameter map are of type String array. + * values as map values. The keys in the parameter map are of type + * String. The values in the parameter map are of type String array. */ Map getParameterMap(); @@ -262,7 +264,7 @@ public interface AgiRequest /** * Returns the local address this channel, that is the IP address of the AGI * server. - * + * * @return the local address this channel. * @since 0.2 */ @@ -271,7 +273,7 @@ public interface AgiRequest /** * Returns the local port of this channel, that is the port the AGI server * is listening on. - * + * * @return the local port of this socket channel. * @since 0.2 */ @@ -280,7 +282,7 @@ public interface AgiRequest /** * Returns the remote address of this channel, that is the IP address of the * Asterisk server. - * + * * @return the remote address of this channel. * @since 0.2 */ @@ -289,9 +291,11 @@ public interface AgiRequest /** * Returns the remote port of this channel, that is the client port the * Asterisk server is using for the AGI connection. - * + * * @return the remote port of this channel. * @since 0.2 */ int getRemotePort(); + + AsteriskVersion getAsteriskVersion(); } diff --git a/src/main/java/org/asteriskjava/fastagi/AgiScript.java b/src/main/java/org/asteriskjava/fastagi/AgiScript.java index ee72d12a5..a5383cf80 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiScript.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiScript.java @@ -23,21 +23,19 @@ * interface.

    * Note: The implementation of AgiScript must be threadsafe as only one instance * is used by AsteriskServer to handle all requests to a resource. - * + * * @author srt * @version $Id$ */ -public interface AgiScript -{ +public interface AgiScript { /** * The service method is called by the AsteriskServer whenever this * AgiScript should handle an incoming AgiRequest. - * + * * @param request the initial data received from Asterisk when requesting - * this script. + * this script. * @param channel a handle to communicate with Asterisk such as sending - * commands to the channel sending the request. - * + * commands to the channel sending the request. * @throws AgiException any exception thrown by your script will be logged. */ void service(final AgiRequest request, final AgiChannel channel) throws AgiException; diff --git a/src/main/java/org/asteriskjava/fastagi/AgiServer.java b/src/main/java/org/asteriskjava/fastagi/AgiServer.java index c5a0261bb..24e9c9fe3 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiServer.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiServer.java @@ -20,7 +20,7 @@ /** * Listens for incoming FastAGI connections, reads the inital data and builds an - * {@link AgiRequest} that is then handed over to the appropriate + * {@link AgiRequest} that is then handed over to the appropriate * {@link org.asteriskjava.fastagi.AgiScript} for processing.

    * To pass a call from Asterisk to the AGI server add an extension to your * dialplan that makes use of the AGI() application. For example: @@ -33,44 +33,53 @@ *

      *
    • NOT_FOUND if no AGI script had been configured to * handle the request. - *
    • SUCCESS if the AGI script was executed successfully. + *
    • SUCCESS if the AGI script was executed successfully. *
    • FAILED if the AGI script terminated abnormally by * throwing an exception or there was an internal error processing it. *
    * If Asterisk-Java was not able to process the request because its thread - * pool was exhausted the AJ_AGISTATUS variable is not set. + * pool was exhausted the AJ_AGISTATUS variable is not set. *

    * The AJ_AGISTATUS variable complements the AGISTATUS * variable that is set by Asterisk to SUCCESS, FAILURE - * or HANGUP and is available since Asterisk 1.4. - * - * @see org.asteriskjava.fastagi.AgiServerThread + * or HANGUP and is available since Asterisk 1.4. + * * @author srt * @version $Id$ + * @see org.asteriskjava.fastagi.AgiServerThread */ -public interface AgiServer -{ +public interface AgiServer { /** * Starts this AgiServer.

    * After calling startup() this AgiServer is ready to receive requests from * Asterisk servers and process them.

    * Note that this method will not return until the AgiServer has been shut down. - * If you want to run the AgiServer in the background use wrap it with an + * If you want to run the AgiServer in the background use wrap it with an * {@link AgiServerThread}. - * - * @throws IOException if the server socket cannot be bound. + * + * @throws IOException if the server socket cannot be bound. * @throws IllegalStateException if this AgiServer is already running. */ void startup() throws IOException, IllegalStateException; /** * Stops this AgiServer.

    - * The server socket is closed, new connections are refused and resources + * The server socket is closed, new connections are refused and resources * are freed. Any running {@link AgiScript}s are finish before shutdown * completes. - * + * * @throws IllegalStateException if this AgiServer is already shut down or - * has not yet been started. + * has not yet been started. */ void shutdown() throws IllegalStateException; + + /** + * Connection is dropped if it stales on read longer than the timeout. + * + * @param socketReadTimeout the read timeout value to be used in + * milliseconds. + * @see java.net.Socket#setSoTimeout(int) + * @since 3.0.0 + */ + void setSocketReadTimeout(int socketReadTimeout); } diff --git a/src/main/java/org/asteriskjava/fastagi/AgiServerThread.java b/src/main/java/org/asteriskjava/fastagi/AgiServerThread.java index 0799b8301..f7c46b929 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiServerThread.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiServerThread.java @@ -16,12 +16,12 @@ */ package org.asteriskjava.fastagi; -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.concurrent.atomic.AtomicLong; - import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.concurrent.atomic.AtomicLong; + /** * Runs an AgiServer in a separate Thread. *

    @@ -30,13 +30,12 @@ *

    * By default the thread used by this class is marked as daemon thread, that * means it will be destroyed when the last user thread has finished. - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class AgiServerThread -{ +public class AgiServerThread { private final Log logger = LogFactory.getLog(getClass()); private static AtomicLong idCounter = new AtomicLong(); private AgiServer agiServer; @@ -52,18 +51,16 @@ public class AgiServerThread * This constructor is mainly intended for use with setter based dependency * injection. */ - public AgiServerThread() - { + public AgiServerThread() { super(); } /** * Creates a new AgiServerThread that runs the given {@link AgiServer}. - * + * * @param agiServer the AgiServer to run. */ - public AgiServerThread(AgiServer agiServer) - { + public AgiServerThread(AgiServer agiServer) { super(); this.agiServer = agiServer; } @@ -73,11 +70,10 @@ public AgiServerThread(AgiServer agiServer) *

    * This property must be set before starting the AgiServerThread by calling * startup. - * + * * @param agiServer the AgiServer to run. */ - public void setAgiServer(AgiServer agiServer) - { + public synchronized void setAgiServer(AgiServer agiServer) { this.agiServer = agiServer; } @@ -85,14 +81,13 @@ public void setAgiServer(AgiServer agiServer) * Marks the thread as either a daemon thread or a user thread. *

    * Default is true. - * + * * @param daemon if false, marks the thread as a user - * thread. + * thread. * @see Thread#setDaemon(boolean) * @since 0.3 */ - public void setDaemon(boolean daemon) - { + public void setDaemon(boolean daemon) { this.daemon = daemon; } @@ -102,22 +97,19 @@ public void setDaemon(boolean daemon) * Note: The AgiServerThread is designed to handle one AgiServer instance at * a time so calling this method twice without stopping the AgiServer in * between will result in a RuntimeException. - * + * * @throws IllegalStateException if the mandatory property agiServer has not - * been set or the AgiServer had already been started. - * @throws RuntimeException if the AgiServer can't be started due to IO - * problems, for example because the socket has already been - * bound by another process. + * been set or the AgiServer had already been started. + * @throws RuntimeException if the AgiServer can't be started due to IO + * problems, for example because the socket has already been + * bound by another process. */ - public synchronized void startup() throws IllegalStateException, RuntimeException - { - if (agiServer == null) - { + public synchronized void startup() throws IllegalStateException, RuntimeException { + if (agiServer == null) { throw new IllegalStateException("Mandatory property agiServer is not set."); } - if (thread != null) - { + if (thread != null) { throw new IllegalStateException("AgiServer is already started"); } @@ -125,20 +117,14 @@ public synchronized void startup() throws IllegalStateException, RuntimeExceptio thread.start(); } - protected Thread createThread() - { + protected Thread createThread() { Thread t; - t = new Thread(new Runnable() - { - public void run() - { - try - { + t = new Thread(new Runnable() { + public void run() { + try { agiServer.startup(); - } - catch (Throwable e) - { + } catch (Throwable e) { throw new RuntimeException("Exception running AgiServer.", e); } } @@ -155,28 +141,22 @@ public void run() *

    * The AgiServer must have been started by calling {@link #startup()} before * you can stop it. - * - * @see AgiServer#shutdown() + * * @throws IllegalStateException if the mandatory property agiServer has not - * been set or the AgiServer had already been shut down. + * been set or the AgiServer had already been shut down. + * @see AgiServer#shutdown() */ - public synchronized void shutdown() throws IllegalStateException - { - if (agiServer == null) - { + public synchronized void shutdown() throws IllegalStateException { + if (agiServer == null) { throw new IllegalStateException("Mandatory property agiServer is not set."); } agiServer.shutdown(); - if (thread != null) - { - try - { + if (thread != null) { + try { thread.join(); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { logger.warn("Interrupted while waiting for AgiServer to shutdown."); Thread.currentThread().interrupt(); } @@ -184,10 +164,8 @@ public synchronized void shutdown() throws IllegalStateException } } - class AgiThreadUncaughtExceptionHanlder implements UncaughtExceptionHandler - { - public void uncaughtException(Thread t, Throwable e) - { + class AgiThreadUncaughtExceptionHanlder implements UncaughtExceptionHandler { + public void uncaughtException(Thread t, Throwable e) { logger.error("Uncaught exception in AgiServerThread", e); } } diff --git a/src/main/java/org/asteriskjava/fastagi/AgiSpeechException.java b/src/main/java/org/asteriskjava/fastagi/AgiSpeechException.java index 9eb711cce..059870253 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiSpeechException.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiSpeechException.java @@ -26,8 +26,7 @@ * @version $Id$ * @since 1.0.0 */ -public class AgiSpeechException extends AgiException -{ +public class AgiSpeechException extends AgiException { /** * Serial version identifier. */ @@ -38,8 +37,7 @@ public class AgiSpeechException extends AgiException * * @param message the message */ - public AgiSpeechException(String message) - { + public AgiSpeechException(String message) { super(message); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AgiWriter.java b/src/main/java/org/asteriskjava/fastagi/AgiWriter.java similarity index 88% rename from src/main/java/org/asteriskjava/fastagi/internal/AgiWriter.java rename to src/main/java/org/asteriskjava/fastagi/AgiWriter.java index 59d602f2e..29746eef2 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiWriter.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiWriter.java @@ -14,22 +14,20 @@ * limitations under the License. * */ -package org.asteriskjava.fastagi.internal; +package org.asteriskjava.fastagi; -import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.command.AgiCommand; /** * The AgiWriter sends commands to Asterisk. - * + * * @author srt * @version $Id$ */ -public interface AgiWriter -{ +public interface AgiWriter { /** * Sends the given command to the Asterisk server. - * + * * @param command the command to send. * @throws AgiException if the command can't be sent. */ diff --git a/src/main/java/org/asteriskjava/fastagi/AsyncAgiServer.java b/src/main/java/org/asteriskjava/fastagi/AsyncAgiServer.java index 1fd49716c..bbb136a41 100644 --- a/src/main/java/org/asteriskjava/fastagi/AsyncAgiServer.java +++ b/src/main/java/org/asteriskjava/fastagi/AsyncAgiServer.java @@ -1,129 +1,132 @@ package org.asteriskjava.fastagi; -import org.asteriskjava.manager.ManagerEventListener; +import org.asteriskjava.fastagi.internal.AsyncAgiConnectionHandler; +import org.asteriskjava.fastagi.internal.DefaultAgiChannelFactory; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.ManagerConnection; -import org.asteriskjava.manager.event.ManagerEvent; +import org.asteriskjava.manager.ManagerEventListener; import org.asteriskjava.manager.event.AsyncAgiEvent; +import org.asteriskjava.manager.event.ManagerEvent; import org.asteriskjava.manager.event.RenameEvent; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -import org.asteriskjava.fastagi.internal.AgiChannelFactory; -import org.asteriskjava.fastagi.internal.AsyncAgiConnectionHandler; -import org.asteriskjava.fastagi.internal.DefaultAgiChannelFactory; -import java.util.Map; import java.util.HashMap; import java.util.concurrent.RejectedExecutionException; /** - * AGI server for AGI over the Manager API (AsyncAGI).

    + * AGI server for AGI over the Manager API (AsyncAGI). + *

    * AsyncAGI is available since Asterisk 1.6. * * @since 1.0.0 */ -public class AsyncAgiServer extends AbstractAgiServer implements ManagerEventListener -{ +public class AsyncAgiServer extends AbstractAgiServer implements ManagerEventListener { private final Log logger = LogFactory.getLog(getClass()); - private final Map connectionHandlers; + private final LockableMap connectionHandlers; /** - * Creates a new AsyncAgiServer with a {@link DefaultAgiChannelFactory}.

    - * Note that you must set a {@link org.asteriskjava.fastagi.MappingStrategy} before using it. + * Creates a new AsyncAgiServer with a {@link DefaultAgiChannelFactory}. + *

    + * Note that you must set a {@link org.asteriskjava.fastagi.MappingStrategy} + * before using it. * * @see #setMappingStrategy(MappingStrategy) */ - public AsyncAgiServer() - { + public AsyncAgiServer() { this(new DefaultAgiChannelFactory()); } /** - * Creates a new AsyncAgiServer with a custom {@link AgiChannelFactory}.

    - * Note that you must set a {@link org.asteriskjava.fastagi.MappingStrategy} before using it. + * Creates a new AsyncAgiServer with a custom {@link AgiChannelFactory}. + *

    + * Note that you must set a {@link org.asteriskjava.fastagi.MappingStrategy} + * before using it. * - * @param agiChannelFactory The factory to use for creating new AgiChannel instances. + * @param agiChannelFactory The factory to use for creating new AgiChannel + * instances. * @see #setMappingStrategy(MappingStrategy) * @since 1.0.0 */ - public AsyncAgiServer(AgiChannelFactory agiChannelFactory) - { + public AsyncAgiServer(AgiChannelFactory agiChannelFactory) { super(agiChannelFactory); - this.connectionHandlers = new HashMap(); + this.connectionHandlers = new LockableMap<>(new HashMap<>()); } /** - * Creates a new AsyncAgiServer with the given MappingStrategy.

    - * Please note that Async AGI does not currently support passing a script name, so your - * MappingStrategy must be aware that the {@link org.asteriskjava.fastagi.AgiRequest#getScript() script} - * property of the AgiRequests will likely be null. + * Creates a new AsyncAgiServer with the given MappingStrategy. + *

    + * Please note that Async AGI does not currently support passing a script + * name, so your MappingStrategy must be aware that the + * {@link org.asteriskjava.fastagi.AgiRequest#getScript() script} property + * of the AgiRequests will likely be null. * - * @param mappingStrategy the MappingStrategy to use to determine which AGI script to run - * for a certain request. + * @param mappingStrategy the MappingStrategy to use to determine which AGI + * script to run for a certain request. */ - public AsyncAgiServer(MappingStrategy mappingStrategy) - { + public AsyncAgiServer(MappingStrategy mappingStrategy) { this(mappingStrategy, new DefaultAgiChannelFactory()); logger.debug("use default AgiChannelFactory"); } /** - * Creates a new AsyncAgiServer with the given MappingStrategy.

    - * Please note that Async AGI does not currently support passing a script name, so your - * MappingStrategy must be aware that the {@link org.asteriskjava.fastagi.AgiRequest#getScript() script} - * property of the AgiRequests will likely be null. + * Creates a new AsyncAgiServer with the given MappingStrategy. + *

    + * Please note that Async AGI does not currently support passing a script + * name, so your MappingStrategy must be aware that the + * {@link org.asteriskjava.fastagi.AgiRequest#getScript() script} property + * of the AgiRequests will likely be null. * - * @param mappingStrategy the MappingStrategy to use to determine which AGI script to run - * for a certain request. - * @param agiChannelFactory The factory to use for creating new AgiChannel instances. + * @param mappingStrategy the MappingStrategy to use to determine which AGI + * script to run for a certain request. + * @param agiChannelFactory The factory to use for creating new AgiChannel + * instances. */ - public AsyncAgiServer(MappingStrategy mappingStrategy, AgiChannelFactory agiChannelFactory) - { + public AsyncAgiServer(MappingStrategy mappingStrategy, AgiChannelFactory agiChannelFactory) { this(agiChannelFactory); setMappingStrategy(mappingStrategy); } /** - * Creates a new AsyncAgiServer that will execute the given AGI script for every - * request.

    - * Internally this constructor uses a {@link org.asteriskjava.fastagi.StaticMappingStrategy}. + * Creates a new AsyncAgiServer that will execute the given AGI script for + * every request. + *

    + * Internally this constructor uses a + * {@link org.asteriskjava.fastagi.StaticMappingStrategy}. * * @param agiScript the AGI script to execute. - * @param agiChannelFactory The factory to use for creating new AgiChannel instances. + * @param agiChannelFactory The factory to use for creating new AgiChannel + * instances. */ - public AsyncAgiServer(AgiScript agiScript, AgiChannelFactory agiChannelFactory) - { + public AsyncAgiServer(AgiScript agiScript, AgiChannelFactory agiChannelFactory) { this(agiChannelFactory); setMappingStrategy(new StaticMappingStrategy(agiScript)); } /** - * Creates a new AsyncAgiServer that will execute the given AGI script for every - * request.

    - * Internally this constructor uses a {@link org.asteriskjava.fastagi.StaticMappingStrategy}. + * Creates a new AsyncAgiServer that will execute the given AGI script for + * every request. + *

    + * Internally this constructor uses a + * {@link org.asteriskjava.fastagi.StaticMappingStrategy}. * * @param agiScript the AGI script to execute. */ - public AsyncAgiServer(AgiScript agiScript) - { + public AsyncAgiServer(AgiScript agiScript) { this(agiScript, new DefaultAgiChannelFactory()); logger.debug("use default AgiChannelFactory"); } - - public void onManagerEvent(ManagerEvent event) - { - if (event instanceof AsyncAgiEvent) - { + public void onManagerEvent(ManagerEvent event) { + if (event instanceof AsyncAgiEvent) { handleAsyncAgiEvent((AsyncAgiEvent) event); - } - else if (event instanceof RenameEvent) - { + } else if (event instanceof RenameEvent) { handleRenameEvent((RenameEvent) event); } } - private void handleAsyncAgiEvent(AsyncAgiEvent asyncAgiEvent) - { + private void handleAsyncAgiEvent(AsyncAgiEvent asyncAgiEvent) { final ManagerConnection connection; final String channelName; final AsyncAgiConnectionHandler connectionHandler; @@ -131,53 +134,42 @@ private void handleAsyncAgiEvent(AsyncAgiEvent asyncAgiEvent) connection = (ManagerConnection) asyncAgiEvent.getSource(); channelName = asyncAgiEvent.getChannel(); - if (asyncAgiEvent.isStart()) - { - connectionHandler = new AsyncAgiConnectionHandler(getMappingStrategy(), asyncAgiEvent, this.getAgiChannelFactory()); + if (asyncAgiEvent.isStart()) { + connectionHandler = new AsyncAgiConnectionHandler(getMappingStrategy(), asyncAgiEvent, + this.getAgiChannelFactory()); setConnectionHandler(connection, channelName, connectionHandler); - try - { + try { execute(connectionHandler); - } - catch (RejectedExecutionException e) - { + } catch (RejectedExecutionException e) { logger.warn("Execution was rejected by pool. Try to increase the pool size."); - // release resources if execution was rejected due to the pool size + // release resources if execution was rejected due to the pool + // size connectionHandler.release(); } - } - else - { + } else { connectionHandler = getConnectionHandler(connection, channelName); - if (connectionHandler == null) - { - logger.info("No AsyncAgiConnectionHandler registered for channel " + channelName + ": Ignoring AsyncAgiEvent"); + if (connectionHandler == null) { + logger.info( + "No AsyncAgiConnectionHandler registered for channel " + channelName + ": Ignoring AsyncAgiEvent"); return; } - if (asyncAgiEvent.isExec()) - { + if (asyncAgiEvent.isExec()) { connectionHandler.onAsyncAgiExecEvent(asyncAgiEvent); - } - else if (asyncAgiEvent.isEnd()) - { + } else if (asyncAgiEvent.isEnd()) { connectionHandler.onAsyncAgiEndEvent(asyncAgiEvent); removeConnectionHandler(connection, channelName); - } - else - { + } else { logger.warn("Ignored unknown AsyncAgiEvent of sub type '" + asyncAgiEvent.getSubEvent() + "'"); } } } - private void handleRenameEvent(RenameEvent renameEvent) - { + private void handleRenameEvent(RenameEvent renameEvent) { final ManagerConnection connection = (ManagerConnection) renameEvent.getSource(); final AsyncAgiConnectionHandler connectionHandler = getConnectionHandler(connection, renameEvent.getChannel()); - if (connectionHandler == null) - { + if (connectionHandler == null) { return; } @@ -187,32 +179,26 @@ private void handleRenameEvent(RenameEvent renameEvent) connectionHandler.updateChannelName(renameEvent.getNewname()); } - private AsyncAgiConnectionHandler getConnectionHandler(ManagerConnection connection, String channelName) - { - synchronized (connectionHandlers) - { + private AsyncAgiConnectionHandler getConnectionHandler(ManagerConnection connection, String channelName) { + try (LockCloser closer = connectionHandlers.withLock()) { return connectionHandlers.get(calculateHashKey(connection, channelName)); } } - private void setConnectionHandler(ManagerConnection connection, String channelName, AsyncAgiConnectionHandler connectionHandler) - { - synchronized (connectionHandlers) - { + private void setConnectionHandler(ManagerConnection connection, String channelName, + AsyncAgiConnectionHandler connectionHandler) { + try (LockCloser closer = connectionHandlers.withLock()) { connectionHandlers.put(calculateHashKey(connection, channelName), connectionHandler); } } - private void removeConnectionHandler(ManagerConnection connection, String channelName) - { - synchronized (connectionHandlers) - { + private void removeConnectionHandler(ManagerConnection connection, String channelName) { + try (LockCloser closer = connectionHandlers.withLock()) { connectionHandlers.remove(calculateHashKey(connection, channelName)); } } - private Integer calculateHashKey(ManagerConnection connection, String channelName) - { + private Integer calculateHashKey(ManagerConnection connection, String channelName) { return connection.hashCode() * 31 + channelName.hashCode(); } } diff --git a/src/main/java/org/asteriskjava/fastagi/BaseAgiScript.java b/src/main/java/org/asteriskjava/fastagi/BaseAgiScript.java index 417adbe3a..8c04f16cd 100644 --- a/src/main/java/org/asteriskjava/fastagi/BaseAgiScript.java +++ b/src/main/java/org/asteriskjava/fastagi/BaseAgiScript.java @@ -21,15 +21,13 @@ * write custom {@link org.asteriskjava.fastagi.AgiScript}s. *

    * Just extend it by your own script classes. - * - * @since 0.2 + * * @author srt * @version $Id$ + * @since 0.2 */ -public abstract class BaseAgiScript extends AgiOperations implements AgiScript -{ - public BaseAgiScript() - { +public abstract class BaseAgiScript extends AgiOperations implements AgiScript { + public BaseAgiScript() { super(); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/ClassNameMappingStrategy.java b/src/main/java/org/asteriskjava/fastagi/ClassNameMappingStrategy.java index 25eb455ee..d68af3550 100644 --- a/src/main/java/org/asteriskjava/fastagi/ClassNameMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/ClassNameMappingStrategy.java @@ -22,44 +22,41 @@ /** * A MappingStrategy that determines the AGIScript based on the fully * qualified class name given in the AGI URL.

    - * To use this ClassNameMappingStrategy the calls to your + * To use this ClassNameMappingStrategy the calls to your * {@link org.asteriskjava.fastagi.AgiScript} in * your dialplan should look like this: *

    - * exten => 123,1,AGI(agi://your.server.com/com.example.agi.MyScript)
    + * exten => 123,1,AGI(agi://your.server.com/com.example.agi.MyScript)
      * 
    * Where com.example.agi.MyScript is the fully qualified name of your * AgiScript. - * + * * @author srt * @version $Id$ */ -public class ClassNameMappingStrategy extends AbstractMappingStrategy -{ +public class ClassNameMappingStrategy extends AbstractMappingStrategy { private Map instances; private boolean shareInstances; /** * Creates a new ClassNameMappingStrategy using shared instances. */ - public ClassNameMappingStrategy() - { + public ClassNameMappingStrategy() { this(true); } /** * Creates a new ClassNameMappingStrategy indicating whether to use shared * instances or not. - * + * * @param shareInstances true to use shared instances, * false to create a new instance for * each request. * @since 0.3 */ - public ClassNameMappingStrategy(boolean shareInstances) - { + public ClassNameMappingStrategy(boolean shareInstances) { super(); - this.instances = new HashMap(); + this.instances = new HashMap<>(); this.shareInstances = shareInstances; } @@ -69,38 +66,32 @@ public ClassNameMappingStrategy(boolean shareInstances) * AGIScript, if set to false a new instance is created for * each request.

    * Default is true. - * + * * @param shareInstances true to use shared instances, * false to create a new instance for * each request. * @since 0.3 */ - public synchronized void setShareInstances(boolean shareInstances) - { + public synchronized void setShareInstances(boolean shareInstances) { this.shareInstances = shareInstances; } - public synchronized AgiScript determineScript(AgiRequest request) - { + public synchronized AgiScript determineScript(AgiRequest request) { AgiScript script; - if (shareInstances) - { + if (shareInstances) { script = instances.get(request.getScript()); - if (script != null) - { + if (script != null) { return script; } } script = createAgiScriptInstance(request.getScript()); - if (script == null) - { + if (script == null) { return null; } - if (shareInstances) - { + if (shareInstances) { instances.put(request.getScript(), script); } diff --git a/src/main/java/org/asteriskjava/fastagi/CompositeMappingStrategy.java b/src/main/java/org/asteriskjava/fastagi/CompositeMappingStrategy.java index a408710e8..8c9b6e6c9 100644 --- a/src/main/java/org/asteriskjava/fastagi/CompositeMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/CompositeMappingStrategy.java @@ -17,8 +17,8 @@ package org.asteriskjava.fastagi; import java.util.ArrayList; -import java.util.List; import java.util.Arrays; +import java.util.List; /** * A mapping strategy that tries a sequence of other mapping strategies to find @@ -35,86 +35,75 @@ * in fastagi-mapping.properties and - if the properties file is * not present on the classpath or contains no mapping for the request - uses * a {@link ClassNameMappingStrategy} to get the script. - * + * + * @author srt + * @version $Id$ * @see ResourceBundleMappingStrategy * @see ClassNameMappingStrategy - * @author srt * @since 0.3 - * @version $Id$ */ -public class CompositeMappingStrategy implements MappingStrategy -{ +public class CompositeMappingStrategy implements MappingStrategy { private List strategies; /** * Creates a new empty CompositeMappingStrategy. */ - public CompositeMappingStrategy() - { + public CompositeMappingStrategy() { super(); } /** * Creates a new CompositeMappingStrategy. - * + * * @param strategies the strategies to use. */ - public CompositeMappingStrategy(MappingStrategy... strategies) - { + public CompositeMappingStrategy(MappingStrategy... strategies) { super(); - this.strategies = new ArrayList(Arrays.asList(strategies)); + this.strategies = new ArrayList<>(Arrays.asList(strategies)); } /** * Creates a new CompositeMappingStrategy. - * + * * @param strategies the strategies to use. */ - public CompositeMappingStrategy(List strategies) - { + public CompositeMappingStrategy(List strategies) { super(); - this.strategies = new ArrayList(strategies); + this.strategies = new ArrayList<>(strategies); } /** * Adds a strategy (at the end of the list). - * + * * @param strategy the strategy to add. */ - public void addStrategy(MappingStrategy strategy) - { - if (strategies == null) - { - strategies = new ArrayList(); + public void addStrategy(MappingStrategy strategy) { + if (strategies == null) { + strategies = new ArrayList<>(); } strategies.add(strategy); } /** * Sets the strategies to use. - * + * * @param strategies the strategies to use. */ - public void setStrategies(List strategies) - { - this.strategies = new ArrayList(strategies); + public void setStrategies(List strategies) { + this.strategies = new ArrayList<>(strategies); } @Override - public AgiScript determineScript(AgiRequest request, AgiChannel channel) - { + public AgiScript determineScript(AgiRequest request, AgiChannel channel) { AgiScript script = null; - if (strategies == null) - { + if (strategies == null) { return null; } - for (MappingStrategy strategy : strategies) - { + for (MappingStrategy strategy : strategies) { script = strategy.determineScript(request, channel); - if (script != null) - { + if (script != null) { break; } } diff --git a/src/main/java/org/asteriskjava/fastagi/DefaultAgiServer.java b/src/main/java/org/asteriskjava/fastagi/DefaultAgiServer.java index f695e72b4..48f0560d6 100644 --- a/src/main/java/org/asteriskjava/fastagi/DefaultAgiServer.java +++ b/src/main/java/org/asteriskjava/fastagi/DefaultAgiServer.java @@ -16,26 +16,28 @@ */ package org.asteriskjava.fastagi; -import org.asteriskjava.fastagi.internal.AgiChannelFactory; import org.asteriskjava.fastagi.internal.AgiConnectionHandler; import org.asteriskjava.fastagi.internal.DefaultAgiChannelFactory; import org.asteriskjava.fastagi.internal.FastAgiConnectionHandler; import org.asteriskjava.util.*; import org.asteriskjava.util.internal.ServerSocketFacadeImpl; +import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.concurrent.RejectedExecutionException; /** - * Default implementation of the {@link org.asteriskjava.fastagi.AgiServer} interface for FastAGI. + * Default implementation of the {@link org.asteriskjava.fastagi.AgiServer} + * interface for FastAGI. * * @author srt * @version $Id$ */ -public class DefaultAgiServer extends AbstractAgiServer implements AgiServer -{ +public class DefaultAgiServer extends AbstractAgiServer implements AgiServer { private final Log logger = LogFactory.getLog(getClass()); /** @@ -48,148 +50,155 @@ public class DefaultAgiServer extends AbstractAgiServer implements AgiServer */ private static final int DEFAULT_BIND_PORT = 4573; + /** + * Default 50? Windows server max 200? + */ + private static final int BACKLOG = 200; + private ServerSocketFacade serverSocket; private String configResourceBundleName = DEFAULT_CONFIG_RESOURCE_BUNDLE_NAME; private int port = DEFAULT_BIND_PORT; + private InetAddress address = null; + + /** + * Closes the connection if no input has been read for the given amount of + * milliseconds. + * + * @see Socket#setSoTimeout(int) + */ + private int socketReadTimeout = SocketConnectionFacadeImpl.MAX_SOCKET_READ_TIMEOUT_MILLIS; /** * Creates a new DefaultAgiServer. */ - public DefaultAgiServer() - { + public DefaultAgiServer() { this(null, null); } /** - * Creates a new DefaultAgiServer and set a custom factory for creating AgiChannels + * Creates a new DefaultAgiServer and set a custom factory for creating + * AgiChannels * - * @param agiChannelFactory The factory to use for creating new AgiChannel instances. + * @param agiChannelFactory The factory to use for creating new AgiChannel + * instances. */ - public DefaultAgiServer(AgiChannelFactory agiChannelFactory) - { + public DefaultAgiServer(AgiChannelFactory agiChannelFactory) { this(null, null, agiChannelFactory); } /** - * Creates a new DefaultAgiServer and loads its configuration from an alternative resource bundle. + * Creates a new DefaultAgiServer and loads its configuration from an + * alternative resource bundle. * - * @param configResourceBundleName the name of the conifiguration resource bundle (default is "fastagi"). + * @param configResourceBundleName the name of the conifiguration resource + * bundle (default is "fastagi"). */ - public DefaultAgiServer(String configResourceBundleName) - { + public DefaultAgiServer(String configResourceBundleName) { this(configResourceBundleName, null); } /** - * Creates a new DefaultAgiServer that uses the given {@link MappingStrategy}. + * Creates a new DefaultAgiServer that uses the given + * {@link MappingStrategy}. * - * @param mappingStrategy the MappingStrategy to use to determine the AgiScript to run. + * @param mappingStrategy the MappingStrategy to use to determine the + * AgiScript to run. * @since 1.0.0 */ - public DefaultAgiServer(MappingStrategy mappingStrategy) - { + public DefaultAgiServer(MappingStrategy mappingStrategy) { this(null, mappingStrategy); } /** - * Creates a new DefaultAgiServer that runs the given {@link AgiScript} for all requests. + * Creates a new DefaultAgiServer that runs the given {@link AgiScript} for + * all requests. * * @param agiScript the AgiScript to run. * @since 1.0.0 */ - public DefaultAgiServer(AgiScript agiScript) - { + public DefaultAgiServer(AgiScript agiScript) { this(null, new StaticMappingStrategy(agiScript)); } /** - * Creates a new DefaultAgiServer and loads its configuration from an alternative resource bundle and - * uses the given {@link MappingStrategy}. + * Creates a new DefaultAgiServer and loads its configuration from an + * alternative resource bundle and uses the given {@link MappingStrategy}. * - * @param configResourceBundleName the name of the conifiguration resource bundle (default is "fastagi"). - * @param mappingStrategy the MappingStrategy to use to determine the AgiScript to run. + * @param configResourceBundleName the name of the conifiguration resource + * bundle (default is "fastagi"). + * @param mappingStrategy the MappingStrategy to use to determine the + * AgiScript to run. * @since 1.0.0 */ - public DefaultAgiServer(String configResourceBundleName, MappingStrategy mappingStrategy) - { + public DefaultAgiServer(String configResourceBundleName, MappingStrategy mappingStrategy) { this(configResourceBundleName, mappingStrategy, new DefaultAgiChannelFactory()); } /** - * Creates a new DefaultAgiServer and loads its configuration from an alternative resource bundle and - * uses the given {@link MappingStrategy}. + * Creates a new DefaultAgiServer and loads its configuration from an + * alternative resource bundle and uses the given {@link MappingStrategy}. * - * @param configResourceBundleName the name of the conifiguration resource bundle (default is "fastagi"). - * @param mappingStrategy the MappingStrategy to use to determine the AgiScript to run. - * @param agiChannelFactory The factory to use for creating new AgiChannel instances. + * @param configResourceBundleName the name of the conifiguration resource + * bundle (default is "fastagi"). + * @param mappingStrategy the MappingStrategy to use to determine the + * AgiScript to run. + * @param agiChannelFactory The factory to use for creating new AgiChannel + * instances. * @since 1.0.0 */ - public DefaultAgiServer(String configResourceBundleName, MappingStrategy mappingStrategy, AgiChannelFactory agiChannelFactory) - { + public DefaultAgiServer(String configResourceBundleName, MappingStrategy mappingStrategy, + AgiChannelFactory agiChannelFactory) { super(agiChannelFactory); - if (mappingStrategy == null) - { + if (mappingStrategy == null) { final CompositeMappingStrategy compositeMappingStrategy = new CompositeMappingStrategy(); compositeMappingStrategy.addStrategy(new ResourceBundleMappingStrategy()); compositeMappingStrategy.addStrategy(new ClassNameMappingStrategy()); - if (ReflectionUtil.isClassAvailable("javax.script.ScriptEngineManager")) - { - MappingStrategy scriptEngineMappingStrategy = - (MappingStrategy) ReflectionUtil.newInstance("org.asteriskjava.fastagi.ScriptEngineMappingStrategy"); - if (scriptEngineMappingStrategy != null) - { + if (ReflectionUtil.isClassAvailable("javax.script.ScriptEngineManager")) { + MappingStrategy scriptEngineMappingStrategy = (MappingStrategy) ReflectionUtil + .newInstance("org.asteriskjava.fastagi.ScriptEngineMappingStrategy"); + if (scriptEngineMappingStrategy != null) { compositeMappingStrategy.addStrategy(scriptEngineMappingStrategy); } - } - else - { + } else { logger.warn("ScriptEngine support disabled: It is only availble when running at least Java 6"); } setMappingStrategy(compositeMappingStrategy); - } - else - { + } else { setMappingStrategy(mappingStrategy); } - if (configResourceBundleName != null) - { + if (configResourceBundleName != null) { this.configResourceBundleName = configResourceBundleName; } loadConfig(); } - /** - * Sets the TCP port to listen on for new connections. - *

    + * Sets the TCP port to listen on for new connections.
    * The default port is 4573. * * @param bindPort the port to bind to. - * @deprecated use {@see #setPort(int)} instead + * @deprecated use {@link #setPort(int)} instead */ @Deprecated - public void setBindPort(int bindPort) - { + public void setBindPort(int bindPort) { this.port = bindPort; } /** - * Sets the TCP port to listen on for new connections. - *

    + * Sets the TCP port to listen on for new connections.
    * The default port is 4573. * * @param port the port to bind to. * @since 0.2 */ - public void setPort(int port) - { + public void setPort(int port) { this.port = port; } @@ -199,120 +208,125 @@ public void setPort(int port) * @return the TCP port this server is configured to bind to. * @since 1.0.0 */ - public int getPort() - { + public int getPort() { return port; } - private void loadConfig() - { + /** + * Returns the address this server is configured to bind to. + * + * @return the address this server is configured to bind to. + */ + public InetAddress getAddress() { + return address; + } + + /** + * Sets the address to bind server. + * + * @param address the address to bind to. + */ + public void setAddress(InetAddress address) { + this.address = address; + } + + private void loadConfig() { final ResourceBundle resourceBundle; - try - { + try { resourceBundle = ResourceBundle.getBundle(configResourceBundleName); - } - catch (MissingResourceException e) - { + } catch (MissingResourceException e) { return; } - try - { + try { String portString; - try - { + try { portString = resourceBundle.getString("port"); - } - catch (MissingResourceException e) - { + } catch (MissingResourceException e) { // for backward compatibility only portString = resourceBundle.getString("bindPort"); } port = Integer.parseInt(portString); - } - catch (Exception e) // NOPMD + } catch (Exception e) // NOPMD { // swallow } - try - { + try { setPoolSize(Integer.parseInt(resourceBundle.getString("poolSize"))); - } - catch (Exception e) // NOPMD + } catch (Exception e) // NOPMD { // swallow } - try - { + try { setMaximumPoolSize(Integer.parseInt(resourceBundle.getString("maximumPoolSize"))); - } - catch (Exception e) // NOPMD + } catch (Exception e) // NOPMD { // swallow } } - protected ServerSocketFacade createServerSocket() throws IOException - { - return new ServerSocketFacadeImpl(port, 0, null); + public void setSocketReadTimeout(int socketReadTimeout) { + this.socketReadTimeout = socketReadTimeout; } - public void startup() throws IOException, IllegalStateException - { - try - { + protected ServerSocketFacade createServerSocket() throws IOException { + // referred to the address by getAddress(), so that overloading the + // getAddress() method works as expected + ServerSocketFacade serverSocketFacade = new ServerSocketFacadeImpl(port, BACKLOG, getAddress()); + serverSocketFacade.setSocketReadTimeout(socketReadTimeout); + return serverSocketFacade; + } + + public void startup() throws IOException, IllegalStateException { + try { serverSocket = createServerSocket(); - } - catch (IOException e) - { + } catch (IOException e) { logger.error("Unable start AgiServer: cannot to bind to *:" + port + ".", e); throw e; } - - logger.info("Listening on *:" + port + "."); + // referred to the address by getAddress(), so that overloading the + // getAddress() method works as expected + if (getAddress() != null) { + // referred to the address by getAddress(), so that overloading the + // getAddress() method works as expected + logger.info("Listening on " + getAddress() + ":" + port + "."); + } else { + logger.info("Listening on *:" + port + "."); + } // loop will be terminated by accept() throwing an IOException when the // ServerSocket is closed. - while (true) - { + while (true) { final SocketConnectionFacade socket; // accept connection - try - { + try { socket = serverSocket.accept(); - } - catch (IOException e) - { + } catch (IOException e) { // swallow only if shutdown - if (isDie()) - { + if (isDie()) { break; } - else - { - // handle exception but continue to run - handleException("IOException while waiting for connections.", e); - continue; - } + // handle exception but continue to run + handleException("IOException while waiting for connections.", e); + continue; } - logger.info("Received connection from " + socket.getRemoteAddress()); + logger.debug("Received connection from " + socket.getRemoteAddress()); // execute connection handler - final AgiConnectionHandler connectionHandler = new FastAgiConnectionHandler(getMappingStrategy(), socket, this.getAgiChannelFactory()); - try - { + final AgiConnectionHandler connectionHandler = new FastAgiConnectionHandler(getMappingStrategy(), socket, + this.getAgiChannelFactory()); + try { execute(connectionHandler); - } - catch (RejectedExecutionException e) - { + } catch (RejectedExecutionException e) { logger.warn("Execution was rejected by pool. Try to increase the pool size."); - // release resources like closing the socket if execution was rejected due to the pool size + // release resources like closing the socket if execution was + // rejected due to the pool size connectionHandler.release(); } } @@ -323,57 +337,47 @@ public void startup() throws IOException, IllegalStateException * @deprecated use {@link #startup()} instead. */ @Deprecated - public void run() - { - try - { + public void run() { + try { startup(); - } - catch (IOException e) // NOPMD + } catch (IOException e) // NOPMD { - // nothing we can do about that and exceptions have already been logged + // nothing we can do about that and exceptions have already been + // logged // by startup(). } } @Override - public void shutdown() throws IllegalStateException - { + public synchronized void shutdown() throws IllegalStateException { // setting the death flag causes the accept() loop to exit when a // SocketException occurs. super.shutdown(); - if (serverSocket != null) - { - try - { + if (serverSocket != null) { + try { // closes the server socket and throws a SocketException on // Threads waiting in accept() serverSocket.close(); - } - catch (IOException e) - { + } catch (IOException e) { logger.warn("IOException while closing server socket.", e); } } } @Override - protected void finalize() throws Throwable - { - super.finalize(); + protected void finalize() throws Throwable { - if (serverSocket != null) - { - try - { + if (serverSocket != null) { + try { serverSocket.close(); - } - catch (IOException e) // NOPMD + } catch (IOException e) // NOPMD { // swallow } } + + super.finalize(); } /** @@ -384,8 +388,7 @@ protected void finalize() throws Throwable * @deprecated since 1.0.0 use {@link org.asteriskjava.Cli} instead. */ @Deprecated - public static void main(String[] args) throws Exception - { + public static void main(String[] args) throws Exception { final AgiServer server; server = new DefaultAgiServer(); diff --git a/src/main/java/org/asteriskjava/fastagi/InvalidCommandSyntaxException.java b/src/main/java/org/asteriskjava/fastagi/InvalidCommandSyntaxException.java index adde6786a..6ea091f45 100644 --- a/src/main/java/org/asteriskjava/fastagi/InvalidCommandSyntaxException.java +++ b/src/main/java/org/asteriskjava/fastagi/InvalidCommandSyntaxException.java @@ -19,12 +19,11 @@ /** * An InvalidCommandSyntaxException is thrown when the reader receives a reply * with status code 520. - * + * * @author srt * @version $Id$ */ -public class InvalidCommandSyntaxException extends AgiException -{ +public class InvalidCommandSyntaxException extends AgiException { /** * Serial version identifier. */ @@ -36,12 +35,11 @@ public class InvalidCommandSyntaxException extends AgiException /** * Creates a new InvalidCommandSyntaxException with the given synopsis and * usage. - * + * * @param synopsis the synopsis of the command. - * @param usage the usage of the command. + * @param usage the usage of the command. */ - public InvalidCommandSyntaxException(String synopsis, String usage) - { + public InvalidCommandSyntaxException(String synopsis, String usage) { super("Invalid command syntax: " + synopsis); this.synopsis = synopsis; this.usage = usage; @@ -49,21 +47,19 @@ public InvalidCommandSyntaxException(String synopsis, String usage) /** * Returns the synopsis of the command that was called with invalid syntax. - * + * * @return the synopsis of the command that was called with invalid syntax. */ - public String getSynopsis() - { + public String getSynopsis() { return synopsis; } /** * Returns a description of the command that was called with invalid syntax. - * + * * @return a description of the command that was called with invalid syntax. */ - public String getUsage() - { + public String getUsage() { return usage; } } diff --git a/src/main/java/org/asteriskjava/fastagi/InvalidOrUnknownCommandException.java b/src/main/java/org/asteriskjava/fastagi/InvalidOrUnknownCommandException.java index ca03069b0..b9897c585 100644 --- a/src/main/java/org/asteriskjava/fastagi/InvalidOrUnknownCommandException.java +++ b/src/main/java/org/asteriskjava/fastagi/InvalidOrUnknownCommandException.java @@ -19,12 +19,11 @@ /** * An InvalidOrUnknownCommandException is thrown when the reader receives a reply * with status code 510. - * + * * @author srt * @version $Id$ */ -public class InvalidOrUnknownCommandException extends AgiException -{ +public class InvalidOrUnknownCommandException extends AgiException { /** * Serial version identifier. */ @@ -32,11 +31,10 @@ public class InvalidOrUnknownCommandException extends AgiException /** * Creates a new InvalidOrUnknownCommandException. - * + * * @param command the invalid or unknown command. */ - public InvalidOrUnknownCommandException(String command) - { + public InvalidOrUnknownCommandException(String command) { super("Invalid or unknown command: " + command); } } diff --git a/src/main/java/org/asteriskjava/fastagi/MappingStrategy.java b/src/main/java/org/asteriskjava/fastagi/MappingStrategy.java index e1d7c3a09..e54acbaee 100644 --- a/src/main/java/org/asteriskjava/fastagi/MappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/MappingStrategy.java @@ -20,27 +20,26 @@ * A MappingStrategy determines which {@link org.asteriskjava.fastagi.AgiScript} * is called to service a given {@link org.asteriskjava.fastagi.AgiRequest}.

    * A MappingStrategy can use any of the properties - * of an AgiRequest to do this. However most MappingStrategies will just use + * of an AgiRequest to do this. However most MappingStrategies will just use * the script property, that is the name of the invoked AGI script as passed * from Asterisk's dialplan.

    * Asterisk-Java ships with several mapping strategies that are available out * of the box. If you have some special requirements that are not satisfied by * any of the available strategies feel free to implement this interface and * use your own strategy. - * + * * @author srt * @version $Id$ */ -public interface MappingStrategy -{ +public interface MappingStrategy { /** - * Returns the AgiScript instance that is responsible to handle + * Returns the AgiScript instance that is responsible to handle * the given request. - * + * * @param request the request to lookup. * @param channel the channel. - * @return the AgiScript instance to handle this request - * or null if none could be determined by this strategy. + * @return the AgiScript instance to handle this request + * or null if none could be determined by this strategy. */ AgiScript determineScript(AgiRequest request, AgiChannel channel); } diff --git a/src/main/java/org/asteriskjava/fastagi/NamedAgiScript.java b/src/main/java/org/asteriskjava/fastagi/NamedAgiScript.java index 6995d2550..35fdfe83f 100644 --- a/src/main/java/org/asteriskjava/fastagi/NamedAgiScript.java +++ b/src/main/java/org/asteriskjava/fastagi/NamedAgiScript.java @@ -21,8 +21,7 @@ * * @since 1.0.0 */ -public interface NamedAgiScript extends AgiScript -{ +public interface NamedAgiScript extends AgiScript { /** * Returns the name of the script. * diff --git a/src/main/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategy.java b/src/main/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategy.java index b93f6550b..df31e0c31 100644 --- a/src/main/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategy.java @@ -16,30 +16,34 @@ */ package org.asteriskjava.fastagi; +import org.asteriskjava.lock.Locker.LockCloser; + import java.util.*; /** - * A MappingStrategy that is configured via a resource bundle.

    + * A MappingStrategy that is configured via a resource bundle. + *

    * The resource bundle contains the script part of the url as key and the fully - * qualified class name of the corresponding AgiScript as value.

    + * qualified class name of the corresponding AgiScript as value. + *

    * Example: - * + * *

      * leastcostdial.agi = com.example.fastagi.LeastCostDialAgiScript
      * hello.agi = com.example.fastagi.HelloAgiScript
      * 
    - * + *

    * LeastCostDialAgiScript and HelloAgiScript must both implement the AgiScript - * interface and have a default constructor with no parameters.

    + * interface and have a default constructor with no parameters. + *

    * The resource bundle (properties) file is called - * fastagi-mapping.properties by default and must be available on + * fastagi-mapping.properties by default and must be available on * the classpath. - * + * * @author srt * @version $Id$ */ -public class ResourceBundleMappingStrategy extends AbstractMappingStrategy -{ +public class ResourceBundleMappingStrategy extends AbstractMappingStrategy { private static final String DEFAULT_RESOURCE_BUNDLE_NAME = "fastagi-mapping"; private String resourceBundleName; private Map mappings; @@ -49,65 +53,58 @@ public class ResourceBundleMappingStrategy extends AbstractMappingStrategy /** * Creates a new ResourceBundleMappingStrategy using shared instances.. */ - public ResourceBundleMappingStrategy() - { + public ResourceBundleMappingStrategy() { this(DEFAULT_RESOURCE_BUNDLE_NAME); } /** - * Creates a new ResourceBundleMappingStrategy with the given basename - * of the resource bundle to use. - * + * Creates a new ResourceBundleMappingStrategy with the given basename of + * the resource bundle to use. + * * @param resourceBundleName basename of the resource bundle to use */ - public ResourceBundleMappingStrategy(String resourceBundleName) - { + public ResourceBundleMappingStrategy(String resourceBundleName) { this(resourceBundleName, true); } /** - * Creates a new ResourceBundleMappingStrategy indicating whether to use shared - * instances or not. - * + * Creates a new ResourceBundleMappingStrategy indicating whether to use + * shared instances or not. + * * @param shareInstances true to use shared instances, - * false to create a new instance for - * each request. + * false to create a new instance for each request. * @since 0.3 */ - public ResourceBundleMappingStrategy(boolean shareInstances) - { + public ResourceBundleMappingStrategy(boolean shareInstances) { this(DEFAULT_RESOURCE_BUNDLE_NAME, shareInstances); } /** - * Creates a new ResourceBundleMappingStrategy with the given basename - * of the resource bundle to use and indicating whether to use shared - * instances or not. - * + * Creates a new ResourceBundleMappingStrategy with the given basename of + * the resource bundle to use and indicating whether to use shared instances + * or not. + * * @param resourceBundleName basename of the resource bundle to use - * @param shareInstances true to use shared instances, - * false to create a new instance for - * each request. + * @param shareInstances true to use shared instances, + * false to create a new instance for each request. * @since 0.3 */ - public ResourceBundleMappingStrategy(String resourceBundleName, boolean shareInstances) - { + public ResourceBundleMappingStrategy(String resourceBundleName, boolean shareInstances) { super(); this.resourceBundleName = resourceBundleName; this.shareInstances = shareInstances; } /** - * Sets the basename of the resource bundle to use.

    + * Sets the basename of the resource bundle to use. + *

    * Default is "fastagi-mapping". - * + * * @param resourceBundleName basename of the resource bundle to use */ - public void setResourceBundleName(String resourceBundleName) - { + public void setResourceBundleName(String resourceBundleName) { this.resourceBundleName = resourceBundleName; - synchronized (this) - { + try (LockCloser closer = this.withLock()) { this.mappings = null; this.instances = null; } @@ -115,46 +112,38 @@ public void setResourceBundleName(String resourceBundleName) /** * Sets whether to use shared instances or not. If set to true - * all AgiRequests are served by the same instance of an - * AgiScript, if set to false a new instance is created for - * each request.

    + * all AgiRequests are served by the same instance of an AgiScript, if set + * to false a new instance is created for each request. + *

    * Default is true. - * + * * @param shareInstances true to use shared instances, - * false to create a new instance for - * each request. + * false to create a new instance for each request. * @since 0.3 */ - public synchronized void setShareInstances(boolean shareInstances) - { + public synchronized void setShareInstances(boolean shareInstances) { this.shareInstances = shareInstances; } - private synchronized void loadResourceBundle() - { + private synchronized void loadResourceBundle() { ResourceBundle resourceBundle; Enumeration keys; - mappings = new HashMap(); - if (shareInstances) - { - instances = new HashMap(); + mappings = new HashMap<>(); + if (shareInstances) { + instances = new HashMap<>(); } - try - { + try { resourceBundle = ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), getClassLoader()); - } - catch (MissingResourceException e) - { + } catch (MissingResourceException e) { logger.info("Resource bundle '" + resourceBundleName + "' not found."); return; } keys = resourceBundle.getKeys(); - while (keys.hasMoreElements()) - { + while (keys.hasMoreElements()) { String scriptName; String className; AgiScript agiScript; @@ -164,11 +153,9 @@ private synchronized void loadResourceBundle() mappings.put(scriptName, className); - if (shareInstances) - { + if (shareInstances) { agiScript = createAgiScriptInstance(className); - if (agiScript == null) - { + if (agiScript == null) { continue; } instances.put(scriptName, agiScript); @@ -178,20 +165,14 @@ private synchronized void loadResourceBundle() } } - public synchronized AgiScript determineScript(AgiRequest request) - { - if (mappings == null || (shareInstances && instances == null)) - { + public synchronized AgiScript determineScript(AgiRequest request) { + if (mappings == null || (shareInstances && instances == null)) { loadResourceBundle(); } - if (shareInstances) - { + if (shareInstances) { return instances.get(request.getScript()); } - else - { - return createAgiScriptInstance(mappings.get(request.getScript())); - } + return createAgiScriptInstance(mappings.get(request.getScript())); } } diff --git a/src/main/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategy.java b/src/main/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategy.java index e2ffdcb82..780b6562e 100644 --- a/src/main/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategy.java @@ -16,30 +16,31 @@ */ package org.asteriskjava.fastagi; -import org.asteriskjava.util.LogFactory; import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; +import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; -import javax.script.Bindings; import javax.script.ScriptException; import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Arrays; -import java.util.regex.Matcher; import java.util.List; -import java.util.ArrayList; -import java.net.URLClassLoader; -import java.net.URL; -import java.net.MalformedURLException; +import java.util.regex.Matcher; /** - * A MappingStrategy that uses {@see javax.script.ScriptEngine} to run AgiScripts. This MappingStrategy - * can be used to run JavaScript, Groovy, JRuby, etc. scripts. + * A MappingStrategy that uses {@link javax.script.ScriptEngine} to run + * AgiScripts. This MappingStrategy can be used to run JavaScript, Groovy, + * JRuby, etc. scripts. * * @since 1.0.0 */ -public class ScriptEngineMappingStrategy implements MappingStrategy -{ +public class ScriptEngineMappingStrategy implements MappingStrategy { protected final Log logger = LogFactory.getLog(getClass()); /** @@ -60,61 +61,61 @@ public class ScriptEngineMappingStrategy implements MappingStrategy protected ScriptEngineManager scriptEngineManager = null; /** - * Creates a new ScriptEngineMappingStrategy that searches for scripts in the current directory. + * Creates a new ScriptEngineMappingStrategy that searches for scripts in + * the current directory. */ - public ScriptEngineMappingStrategy() - { + public ScriptEngineMappingStrategy() { this(DEFAULT_SCRIPT_PATH, DEFAULT_LIB_PATH); } /** - * Creates a new ScriptEngineMappingStrategy that searches for scripts on the given path. + * Creates a new ScriptEngineMappingStrategy that searches for scripts on + * the given path. * * @param scriptPath array of directory names to search for script files. - * @param libPath array of directory names to search for additional libraries (jar files). + * @param libPath array of directory names to search for additional + * libraries (jar files). */ - public ScriptEngineMappingStrategy(String[] scriptPath, String[] libPath) - { + public ScriptEngineMappingStrategy(String[] scriptPath, String[] libPath) { setScriptPath(scriptPath); setLibPath(libPath); } /** - * Sets the path to search for script files.

    + * Sets the path to search for script files. + *

    * Default is "agi". * * @param scriptPath array of directory names to search for script files. */ - public void setScriptPath(String[] scriptPath) - { - this.scriptPath = Arrays.copyOf(scriptPath, scriptPath.length);; + public void setScriptPath(String[] scriptPath) { + this.scriptPath = Arrays.copyOf(scriptPath, scriptPath.length); } /** - * Sets the path to search for additional libraries (jar files).

    + * Sets the path to search for additional libraries (jar files). + *

    * Default is "lib". * - * @param libPath array of directory names to search for additional libraries (jar files). + * @param libPath array of directory names to search for additional + * libraries (jar files). */ - public void setLibPath(String[] libPath) - { + public void setLibPath(String[] libPath) { this.libPath = Arrays.copyOf(libPath, libPath.length); } @Override - public AgiScript determineScript(AgiRequest request, AgiChannel channel) - { - // check is a file corresponding to the AGI request is found on the scriptPath + public AgiScript determineScript(AgiRequest request, AgiChannel channel) { + // check is a file corresponding to the AGI request is found on the + // scriptPath final File file = searchFile(request.getScript(), scriptPath); - if (file == null) - { + if (file == null) { return null; } // check if there is a ScriptEngine that can handle the file final ScriptEngine scriptEngine = getScriptEngine(file); - if (scriptEngine == null) - { + if (scriptEngine == null) { logger.debug("No ScriptEngine found that can handle '" + file.getPath() + "'"); return null; } @@ -128,11 +129,9 @@ public AgiScript determineScript(AgiRequest request, AgiChannel channel) * @param file the file to search a ScriptEngine for. * @return the ScriptEngine or null if none is found. */ - protected ScriptEngine getScriptEngine(File file) - { + protected ScriptEngine getScriptEngine(File file) { final String extension = getExtension(file.getName()); - if (extension == null) - { + if (extension == null) { return null; } @@ -140,69 +139,62 @@ protected ScriptEngine getScriptEngine(File file) } /** - * Returns the ScriptEngineManager to use for loading the ScriptEngine. The ScriptEngineManager is only - * created once and reused for subsequent requests. Override this method to provide your own implementation. + * Returns the ScriptEngineManager to use for loading the ScriptEngine. The + * ScriptEngineManager is only created once and reused for subsequent + * requests. Override this method to provide your own implementation. * * @return the ScriptEngineManager to use for loading the ScriptEngine. * @see javax.script.ScriptEngineManager#ScriptEngineManager() */ - protected synchronized ScriptEngineManager getScriptEngineManager() - { - if (scriptEngineManager == null) - { + protected synchronized ScriptEngineManager getScriptEngineManager() { + if (scriptEngineManager == null) { this.scriptEngineManager = new ScriptEngineManager(getClassLoader()); } return scriptEngineManager; } /** - * Returns the ClassLoader to use for the ScriptEngineManager. Adds all jar files in the "lib" subdirectory of - * the current directory to the class path. Override this method to provide your own ClassLoader. + * Returns the ClassLoader to use for the ScriptEngineManager. Adds all jar + * files in the "lib" subdirectory of the current directory to the class + * path. Override this method to provide your own ClassLoader. * * @return the ClassLoader to use for the ScriptEngineManager. * @see #getScriptEngineManager() */ - protected ClassLoader getClassLoader() - { + protected ClassLoader getClassLoader() { final ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader(); - final List jarFileUrls = new ArrayList(); + final List jarFileUrls = new ArrayList<>(); - if (libPath == null || libPath.length == 0) - { + if (libPath == null || libPath.length == 0) { return parentClassLoader; } - for (String libPathEntry : libPath) - { + for (String libPathEntry : libPath) { final File libDir = new File(libPathEntry); - if (!libDir.isDirectory()) - { + if (!libDir.isDirectory()) { continue; } - final File[] jarFiles = libDir.listFiles(new FilenameFilter() - { - public boolean accept(File dir, String name) - { + final File[] jarFiles = libDir.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }); - - for (File jarFile : jarFiles) - { - try - { - jarFileUrls.add(jarFile.toURI().toURL()); - } - catch (MalformedURLException e) - { - // should not happen + if (jarFiles != null) { + + for (File jarFile : jarFiles) { + try { + jarFileUrls.add(jarFile.toURI().toURL()); + } catch (MalformedURLException e) { + // should not happen + } } + } else { + logger.error("Didn't find any jar files at " + libDir.getAbsolutePath()); } } - if (jarFileUrls.size() == 0) - { + if (jarFileUrls.isEmpty()) { return parentClassLoader; } @@ -213,51 +205,41 @@ public boolean accept(File dir, String name) * Searches for the file with the given name on the path. * * @param scriptName the name of the file to search for. - * @param path an array of directories to search for the file in order of preference. - * @return the canonical file if found on the path or null if not found. + * @param path an array of directories to search for the file in order of + * preference. + * @return the canonical file if found on the path or null if + * not found. */ - protected File searchFile(String scriptName, String[] path) - { - if (scriptName == null || path == null) - { + protected File searchFile(String scriptName, String[] path) { + if (scriptName == null || path == null) { return null; } - for (String pathElement : path) - { + for (String pathElement : path) { final File pathElementDir = new File(pathElement); // skip if pathElement is not a directory - if (!pathElementDir.isDirectory()) - { + if (!pathElementDir.isDirectory()) { continue; } final File file = new File(pathElementDir, scriptName.replaceAll("/", Matcher.quoteReplacement(File.separator))); - if (!file.exists()) - { + if (!file.exists()) { continue; } - try - { + try { // prevent attacks with scripts using ".." in their name. - if (!isInside(file, pathElementDir)) - { + if (!isInside(file, pathElementDir)) { return null; } - } - catch (IOException e) - { + } catch (IOException e) { logger.warn("Unable to check whether '" + file.getPath() + "' is below '" + pathElementDir.getPath() + "'"); continue; } - try - { + try { return file.getCanonicalFile(); - } - catch (IOException e) - { + } catch (IOException e) { logger.error("Unable to get canonical file for '" + file.getPath() + "'", e); } } @@ -265,15 +247,17 @@ protected File searchFile(String scriptName, String[] path) } /** - * Checks whether a file is contained within a given directory (or a sub directory) or not. + * Checks whether a file is contained within a given directory (or a sub + * directory) or not. * * @param file the file to check. * @param dir the directory to check. - * @return true if file is below directory, false otherwise. - * @throws IOException if the canonical path of file or dir cannot be determined. + * @return true if file is below directory, false + * otherwise. + * @throws IOException if the canonical path of file or dir cannot be + * determined. */ - protected final boolean isInside(File file, File dir) throws IOException - { + protected final boolean isInside(File file, File dir) throws IOException { return file.getCanonicalPath().startsWith(dir.getCanonicalPath()); } @@ -281,49 +265,41 @@ protected final boolean isInside(File file, File dir) throws IOException * Returns the extension (the part after the last ".") of the given script. * * @param scriptName the name of the script to return the extension of. - * @return the extension of the script or null if there is no extension. + * @return the extension of the script or null if there is no + * extension. */ - protected static String getExtension(String scriptName) - { - if (scriptName == null) - { + protected static String getExtension(String scriptName) { + if (scriptName == null) { return null; } int filePosition = scriptName.lastIndexOf("/"); String fileName; - if (scriptName.lastIndexOf("\\") > filePosition) - { + if (scriptName.lastIndexOf("\\") > filePosition) { filePosition = scriptName.lastIndexOf("\\"); } - if (filePosition >= 0) - { + if (filePosition >= 0) { fileName = scriptName.substring(filePosition + 1); - } - else - { + } else { fileName = scriptName; } final int extensionPosition = fileName.lastIndexOf("."); - if (extensionPosition >= 0) - { + if (extensionPosition >= 0) { return fileName.substring(extensionPosition + 1); } return null; } - protected static Reader getReader(File file) throws FileNotFoundException - { + protected static Reader getReader(File file) throws FileNotFoundException { final InputStream is = new FileInputStream(file); - return new InputStreamReader(is); + return new InputStreamReader(is, StandardCharsets.UTF_8); } - protected class ScriptEngineAgiScript implements NamedAgiScript - { + protected class ScriptEngineAgiScript implements NamedAgiScript { final File file; final ScriptEngine scriptEngine; @@ -333,19 +309,16 @@ protected class ScriptEngineAgiScript implements NamedAgiScript * @param file the file that contains the script to execute. * @param scriptEngine the ScriptEngine to use for executing the script. */ - public ScriptEngineAgiScript(File file, ScriptEngine scriptEngine) - { + public ScriptEngineAgiScript(File file, ScriptEngine scriptEngine) { this.file = file; this.scriptEngine = scriptEngine; } - public String getName() - { + public String getName() { return file == null ? null : file.getName(); } - public void service(AgiRequest request, AgiChannel channel) throws AgiException - { + public void service(AgiRequest request, AgiChannel channel) throws AgiException { final Bindings bindings = scriptEngine.createBindings(); bindings.put(ScriptEngine.FILENAME, file.getPath()); @@ -355,33 +328,28 @@ public void service(AgiRequest request, AgiChannel channel) throws AgiException // support for custom bindings populateBindings(file, request, channel, bindings); - try - { + try { scriptEngine.eval(getReader(file), bindings); - } - catch (ScriptException e) - { + } catch (ScriptException e) { throw new AgiException("Execution of script '" + file.getPath() + "' with ScriptEngine failed", e); - } - catch (FileNotFoundException e) - { + } catch (FileNotFoundException e) { throw new AgiException("Script '" + file.getPath() + "' not found", e); } } } /** - * Override this method if you want to add additional bindings before the script is run. By default the - * AGI request, AGI channel and the filename are available to scripts under the bindings "request", "channel" - * and "javax.script.filename". + * Override this method if you want to add additional bindings before the + * script is run. By default the AGI request, AGI channel and the filename + * are available to scripts under the bindings "request", "channel" and + * "javax.script.filename". * * @param file the script file. * @param request the AGI request. * @param channel the AGI channel. * @param bindings the bindings to populate. */ - protected void populateBindings(File file, AgiRequest request, AgiChannel channel, Bindings bindings) - { + protected void populateBindings(File file, AgiRequest request, AgiChannel channel, Bindings bindings) { } } diff --git a/src/main/java/org/asteriskjava/fastagi/SimpleMappingStrategy.java b/src/main/java/org/asteriskjava/fastagi/SimpleMappingStrategy.java index 864439c60..44d49e414 100644 --- a/src/main/java/org/asteriskjava/fastagi/SimpleMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/SimpleMappingStrategy.java @@ -22,7 +22,7 @@ * A MappingStrategy that is configured via a fixed set of properties.

    * This mapping strategy is most useful when used with the Spring framework.

    * Example (using Spring): - * + * *

      * <beans>
      *    <bean id="mapping"
    @@ -50,35 +50,31 @@
      *    </bean>
      * <beans>
      * 
    - * + *

    * LeastCostDialAgiScript and HelloAgiScript must both implement the AgiScript.

    - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class SimpleMappingStrategy implements MappingStrategy -{ +public class SimpleMappingStrategy implements MappingStrategy { private Map mappings; /** * Set the "path to AgiScript" mapping.

    * Use the path (for example hello.agi) as key and your * AgiScript (for example new HelloAgiScript()) as value of - * this map. - * + * this map. + * * @param mappings the path to AgiScript mapping. */ - public void setMappings(Map mappings) - { + public void setMappings(Map mappings) { this.mappings = mappings; } @Override - public AgiScript determineScript(AgiRequest request, AgiChannel channel) - { - if (mappings == null) - { + public AgiScript determineScript(AgiRequest request, AgiChannel channel) { + if (mappings == null) { return null; } diff --git a/src/main/java/org/asteriskjava/fastagi/SpeechRecognitionResult.java b/src/main/java/org/asteriskjava/fastagi/SpeechRecognitionResult.java index f9a710f78..821a93caf 100644 --- a/src/main/java/org/asteriskjava/fastagi/SpeechRecognitionResult.java +++ b/src/main/java/org/asteriskjava/fastagi/SpeechRecognitionResult.java @@ -2,9 +2,9 @@ import org.asteriskjava.fastagi.reply.AgiReply; -import java.util.List; -import java.util.ArrayList; import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; /** * Contains the results of a speech recognition command. @@ -14,13 +14,11 @@ * @see org.asteriskjava.fastagi.command.SpeechRecognizeCommand * @since 1.0.0 */ -public class SpeechRecognitionResult implements Serializable -{ +public class SpeechRecognitionResult implements Serializable { private static final long serialVersionUID = 0L; private final AgiReply agiReply; - public SpeechRecognitionResult(AgiReply agiReply) - { + public SpeechRecognitionResult(AgiReply agiReply) { this.agiReply = agiReply; } @@ -30,8 +28,7 @@ public SpeechRecognitionResult(AgiReply agiReply) * @return true if a DTMF digit was received, false otherwise. * @see #getDigit() */ - public boolean isDtmf() - { + public boolean isDtmf() { return "digit".equals(agiReply.getExtra()); } @@ -43,8 +40,7 @@ public boolean isDtmf() * @see #getScore() * @see #getGrammar() */ - public boolean isSpeech() - { + public boolean isSpeech() { return "speech".equals(agiReply.getExtra()); } @@ -53,8 +49,7 @@ public boolean isSpeech() * * @return true a timeout was encountered, false otherwise. */ - public boolean isTimeout() - { + public boolean isTimeout() { return "timeout".equals(agiReply.getExtra()); } @@ -63,11 +58,9 @@ public boolean isTimeout() * * @return the DTMF digit that was received or 0x0 if none was received. */ - public char getDigit() - { + public char getDigit() { final String digit = agiReply.getAttribute("digit"); - if (digit == null || digit.length() == 0) - { + if (digit == null || digit.length() == 0) { return 0x0; } return digit.charAt(0); @@ -79,9 +72,8 @@ public char getDigit() * * @return the position where the prompt stopped playing, 0 if it was played completely. */ - public int getEndpos() - { - return Integer.valueOf(agiReply.getAttribute("endpos")); + public int getEndpos() { + return Integer.parseInt(agiReply.getAttribute("endpos")); } /** @@ -90,10 +82,9 @@ public int getEndpos() * * @return the confidence score for the first recognition result or 0 if no speech was recognized. */ - public int getScore() - { + public int getScore() { final String score0 = agiReply.getAttribute("score0"); - return score0 == null ? 0 : Integer.valueOf(score0); + return score0 == null ? 0 : Integer.parseInt(score0); } /** @@ -101,8 +92,7 @@ public int getScore() * * @return the text for the first recognition result or null if no speech was recognized. */ - public String getText() - { + public String getText() { return agiReply.getAttribute("text0"); } @@ -111,8 +101,7 @@ public String getText() * * @return the grammar for the first recognition result or null if no speech was recognized. */ - public String getGrammar() - { + public String getGrammar() { return agiReply.getAttribute("grammar0"); } @@ -122,21 +111,18 @@ public String getGrammar() * * @return the number of results recognized. */ - public int getNumberOfResults() - { + public int getNumberOfResults() { final String numberOfResults = agiReply.getAttribute("results"); - return numberOfResults == null ? 0 : Integer.valueOf(numberOfResults); + return numberOfResults == null ? 0 : Integer.parseInt(numberOfResults); } - public List getAllResults() - { + public List getAllResults() { final int numberOfResults = getNumberOfResults(); - final List results = new ArrayList(numberOfResults); + final List results = new ArrayList<>(numberOfResults); - for (int i = 0; i < numberOfResults; i++) - { + for (int i = 0; i < numberOfResults; i++) { SpeechResult result = new SpeechResult( - Integer.valueOf(agiReply.getAttribute("score" + i)), + Integer.parseInt(agiReply.getAttribute("score" + i)), agiReply.getAttribute("text" + i), agiReply.getAttribute("grammar" + i) ); @@ -146,28 +132,23 @@ public List getAllResults() return results; } - public String toString() - { + public String toString() { final StringBuilder sb = new StringBuilder("SpeechRecognitionResult["); - if (isDtmf()) - { + if (isDtmf()) { sb.append("dtmf=true,"); sb.append("digit=").append(getDigit()).append(","); } - if (isSpeech()) - { + if (isSpeech()) { sb.append("speech=true,"); sb.append("score=").append(getScore()).append(","); sb.append("text='").append(getText()).append("',"); sb.append("grammar='").append(getGrammar()).append("',"); } - if (isTimeout()) - { + if (isTimeout()) { sb.append("timeout=true,"); } - if (getNumberOfResults() > 1) - { + if (getNumberOfResults() > 1) { sb.append("numberOfResults=").append(getNumberOfResults()).append(","); sb.append("allResults=").append(getAllResults()).append(","); } @@ -181,15 +162,13 @@ public String toString() * * @see SpeechRecognitionResult#getAllResults() */ - public static class SpeechResult implements Serializable - { + public static class SpeechResult implements Serializable { private static final long serialVersionUID = 0L; private final int score; private final String text; private final String grammar; - private SpeechResult(int score, String text, String grammar) - { + private SpeechResult(int score, String text, String grammar) { this.score = score; this.text = text; this.grammar = grammar; @@ -201,8 +180,7 @@ private SpeechResult(int score, String text, String grammar) * * @return the confidence score. */ - public int getScore() - { + public int getScore() { return score; } @@ -211,8 +189,7 @@ public int getScore() * * @return the text */ - public String getText() - { + public String getText() { return text; } @@ -221,13 +198,11 @@ public String getText() * * @return the grammar */ - public String getGrammar() - { + public String getGrammar() { return grammar; } - public String toString() - { + public String toString() { final StringBuilder sb = new StringBuilder("["); sb.append("score=").append(score).append(","); sb.append("text='").append(text).append("',"); diff --git a/src/main/java/org/asteriskjava/fastagi/StaticMappingStrategy.java b/src/main/java/org/asteriskjava/fastagi/StaticMappingStrategy.java index dfa0274a4..a831c3eef 100644 --- a/src/main/java/org/asteriskjava/fastagi/StaticMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/StaticMappingStrategy.java @@ -5,12 +5,10 @@ * * @since 1.0.0 */ -public class StaticMappingStrategy implements MappingStrategy -{ +public class StaticMappingStrategy implements MappingStrategy { private AgiScript agiScript; - public StaticMappingStrategy() - { + public StaticMappingStrategy() { } /** @@ -18,8 +16,7 @@ public StaticMappingStrategy() * * @param agiScript the script to map to. */ - public StaticMappingStrategy(AgiScript agiScript) - { + public StaticMappingStrategy(AgiScript agiScript) { this.agiScript = agiScript; } @@ -28,14 +25,12 @@ public StaticMappingStrategy(AgiScript agiScript) * * @param agiScript the AgiScript to map to. */ - public void setAgiScript(AgiScript agiScript) - { + public void setAgiScript(AgiScript agiScript) { this.agiScript = agiScript; } @Override - public AgiScript determineScript(AgiRequest request, AgiChannel channel) - { + public AgiScript determineScript(AgiRequest request, AgiChannel channel) { return agiScript; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/AbstractAgiCommand.java b/src/main/java/org/asteriskjava/fastagi/command/AbstractAgiCommand.java index 35bb5ebdb..595984897 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/AbstractAgiCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/AbstractAgiCommand.java @@ -1,91 +1,97 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.util.Log; + import java.io.Serializable; +import static java.lang.String.format; +import static java.lang.System.identityHashCode; +import static org.asteriskjava.AsteriskVersion.ASTERISK_1_4; +import static org.asteriskjava.util.LogFactory.getLog; + /** - * Abstract base class that provides some convenience methods for - * implementing AgiCommand classes. - * + * Abstract base class that provides some convenience methods for implementing {@link AgiCommand} classes. + * * @author srt - * @version $Id$ */ -public abstract class AbstractAgiCommand implements Serializable, AgiCommand -{ - /** - * Serial version identifier. - */ +public abstract class AbstractAgiCommand implements Serializable, AgiCommand { private static final long serialVersionUID = 3257849874518456633L; + private static final Log logger = getLog(AbstractAgiCommand.class); + + private AsteriskVersion asteriskVersion; + + AsteriskVersion getAsteriskVersion() { + if (asteriskVersion == null) { + logger.warn("Asterisk Version isn't known, returning 1.4"); + return ASTERISK_1_4; + } + return asteriskVersion; + } + + public void setAsteriskVersion(AsteriskVersion asteriskVersion) { + this.asteriskVersion = asteriskVersion; + } + public abstract String buildCommand(); + @Override + public String toString() { + return format("%s[command='%s', systemHashcode=%d]", getClass().getName(), buildCommand(), identityHashCode(this)); + } + /** - * Escapes and quotes a given String according to the rules set by - * Asterisk's AGI. - * - * @param s the String to escape and quote - * @return the transformed String + * Escapes and quotes a given string according to the rules set by Asterisk's AGI. + * + * @param string the string to escape and quote + * @return the escaped and quoted string */ - protected String escapeAndQuote(String s) - { - String tmp; - - if (s == null) - { + protected String escapeAndQuote(String string) { + if (string == null) { return "\"\""; } - tmp = s; - tmp = tmp.replaceAll("\\\\", "\\\\\\\\"); - tmp = tmp.replaceAll("\\\"", "\\\\\""); - tmp = tmp.replaceAll("\\\n", ""); // filter newline - return "\"" + tmp + "\""; // add quotes + string = string.replaceAll("\\\\", "\\\\\\\\"); + string = string.replaceAll("\\\"", "\\\\\""); + string = string.replaceAll("\\\n", ""); + return format("\"%s\"", string); } - protected String escapeAndQuote(String[] options) - { - if (options == null) - { + /** + * Escapes and quotes a given strings according to the rules set by Asterisk's AGI. + * + * @param strings the strings to escape and quote + * @return the escaped and quoted joined string + */ + protected String escapeAndQuote(String[] strings) { + if (strings == null) { return escapeAndQuote((String) null); } final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < options.length; i++) - { - if (i > 0) - { + for (int i = 0; i < strings.length; i++) { + if (i > 0) { sb.append(","); } - sb.append(options[i]); + sb.append(strings[i]); } return escapeAndQuote(sb.toString()); } - - @Override - public String toString() - { - StringBuffer sb; - - sb = new StringBuffer(getClass().getName()).append("["); - sb.append("command='").append(buildCommand()).append("', "); - sb.append("systemHashcode=").append(System.identityHashCode(this)).append("]"); - - return sb.toString(); - } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/AgiCommand.java b/src/main/java/org/asteriskjava/fastagi/command/AgiCommand.java index 4d77554af..73dc10242 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/AgiCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/AgiCommand.java @@ -1,36 +1,35 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; +import org.asteriskjava.AsteriskVersion; + /** - * AgiCommand that can be sent to Asterisk via the Asterisk Gateway Interface.

    - * This interface contains only one method that transforms the command to a - * String representation understood by Asterisk. - * + * AgiCommand that can be sent to Asterisk via the Asterisk Gateway Interface (AGI).

    + * This interface contains only one method that transforms the command to a string representation understood by Asterisk. + * * @author srt - * @version $Id$ */ -public interface AgiCommand -{ - +public interface AgiCommand { /** - * Returns a string suitable to be sent to asterisk.

    - * + * Returns a string suitable to be sent to asterisk. + * * @return a string suitable to be sent to asterisk. */ String buildCommand(); + + void setAsteriskVersion(AsteriskVersion asteriskVersion); } diff --git a/src/main/java/org/asteriskjava/fastagi/command/AnswerCommand.java b/src/main/java/org/asteriskjava/fastagi/command/AnswerCommand.java index 666bfb6e9..c9c7337ed 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/AnswerCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/AnswerCommand.java @@ -1,46 +1,36 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Answers channel if not already in answer state.

    - * Returns -1 on channel failure, or 0 if successful. - * + * AGI Command: ANSWER (Asterisk 18) + *

    + * Answer channel. + * * @author srt - * @version $Id$ */ -public class AnswerCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class AnswerCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3762248656229053753L; - /** - * Creates a new AnswerCommand. - */ - public AnswerCommand() - { + public AnswerCommand() { super(); } @Override - public String buildCommand() - { + public String buildCommand() { return "ANSWER"; } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/AsyncAgiBreakCommand.java b/src/main/java/org/asteriskjava/fastagi/command/AsyncAgiBreakCommand.java index 0ec6810e3..e646b2044 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/AsyncAgiBreakCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/AsyncAgiBreakCommand.java @@ -1,45 +1,38 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Breaks the Async AGI loop. + * AGI Command ASYNCAGI BREAK + *

    + * Interrupts expected flow of Async AGI commands and returns control to previous source (typically, the PBX dialplan). + *

    + * See: AGI Command ASYNCAGI BREAK (Asterisk 18) * * @author srt - * @version $Id$ */ -public class AsyncAgiBreakCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class AsyncAgiBreakCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; - /** - * Creates a new AsyncAgiBreakCommand. - */ - public AsyncAgiBreakCommand() - { + public AsyncAgiBreakCommand() { super(); } @Override - public String buildCommand() - { + public String buildCommand() { return "ASYNCAGI BREAK"; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/BridgeCommand.java b/src/main/java/org/asteriskjava/fastagi/command/BridgeCommand.java new file mode 100644 index 000000000..758f6ffd2 --- /dev/null +++ b/src/main/java/org/asteriskjava/fastagi/command/BridgeCommand.java @@ -0,0 +1,53 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import static org.asteriskjava.AsteriskVersion.ASTERISK_13; + +/** + * This is not a real AGI command. + *

    + * It uses EXEC command and add bridge application features. + *

    + * See: AGI Command EXEC (Asterisk 18)
    + * See: Application Bridge (Asterisk 18) + */ +public class BridgeCommand extends AbstractAgiCommand { + private static final long serialVersionUID = 3762248656229053753L; + + private final String channel; + private final String options; + + public BridgeCommand(String channel, String options) { + super(); + this.channel = channel; + this.options = options; + } + + @Override + public String buildCommand() { + String command = "EXEC " + escapeAndQuote("bridge") + " " + escapeAndQuote(channel); + if (options != null && options.length() > 0) { + if (getAsteriskVersion().isAtLeast(ASTERISK_13)) { + command += "," + escapeAndQuote(options); + } else { + command += "|" + escapeAndQuote(options); + } + } + + return command; + } +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/ChannelStatusCommand.java b/src/main/java/org/asteriskjava/fastagi/command/ChannelStatusCommand.java index 4bd075b88..a36063127 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/ChannelStatusCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/ChannelStatusCommand.java @@ -1,24 +1,26 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Returns the status of the specified channel. If no channel name is given the - * returns the status of the current channel.

    + * AGI Command: CHANNEL STATUS + *

    + * Returns the status of the specified channel. + * If no channel name is given the returns the status of the current channel. + *

    * Return values: *

      *
    • 0 Channel is down and available @@ -30,68 +32,56 @@ *
    • 6 Line is up *
    • 7 Line is busy *
    - * + *

    + * See: AGI Command CHANNEL STATUS (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class ChannelStatusCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class ChannelStatusCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3904959746380281145L; /** - * The name of the channel to query or null for the current - * channel. + * The name of the channel to query or null for the current channel. */ private String channel; /** * Creates a new ChannelStatusCommand that queries the current channel. */ - public ChannelStatusCommand() - { + public ChannelStatusCommand() { super(); } /** * Creates a new ChannelStatusCommand that queries the given channel. - * + * * @param channel the name of the channel to query. */ - public ChannelStatusCommand(String channel) - { + public ChannelStatusCommand(String channel) { super(); this.channel = channel; } /** * Returns the name of the channel to query. - * - * @return the name of the channel to query or null for the - * current channel. + * + * @return the name of the channel to query or null for the current channel. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel to query. - * - * @param channel the name of the channel to query or null - * for the current channel. + * + * @param channel the name of the channel to query or null for the current channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @Override - public String buildCommand() - { - return "CHANNEL STATUS" - + (channel == null ? "" : " " + escapeAndQuote(channel)); + public String buildCommand() { + return "CHANNEL STATUS" + (channel == null ? "" : " " + escapeAndQuote(channel)); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/ConfbridgeCommand.java b/src/main/java/org/asteriskjava/fastagi/command/ConfbridgeCommand.java new file mode 100644 index 000000000..60f6a70c9 --- /dev/null +++ b/src/main/java/org/asteriskjava/fastagi/command/ConfbridgeCommand.java @@ -0,0 +1,55 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.asteriskjava.AsteriskVersion; + +/** + * This is not a real AGI command. + *

    + * It uses EXEC command and add confbridge application features. + *

    + * See: AGI Command EXEC (Asterisk 18)
    + * See: Application ConfBridge (Asterisk 18) + */ +public class ConfbridgeCommand extends AbstractAgiCommand { + private static final long serialVersionUID = 3762248656229053753L; + + private final String room; + private final String profile; + + public ConfbridgeCommand(String room, String profile) { + super(); + this.room = room; + this.profile = profile; + } + + @Override + public String buildCommand() { + String separator = "|"; + if (getAsteriskVersion().isAtLeast(AsteriskVersion.ASTERISK_10)) { + separator = ","; + } + + String command = "EXEC " + escapeAndQuote("confbridge") + " " + escapeAndQuote(room); + if (profile != null && profile.length() > 0) { + command += separator + escapeAndQuote(profile); + } + + return command; + + } +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/ControlStreamFileCommand.java b/src/main/java/org/asteriskjava/fastagi/command/ControlStreamFileCommand.java index 0cecc324b..696c71ff4 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/ControlStreamFileCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/ControlStreamFileCommand.java @@ -1,41 +1,34 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Plays the given file, allowing playback to be interrupted by the given - * digits, if any, and allows the listner to control the stream.

    - * If offset is provided then the audio will seek to sample offset before play - * starts.

    - * Returns 0 if playback completes without a digit being pressed, or the ASCII - * numerical value of the digit if one was pressed, or -1 on error or if the - * channel was disconnected.

    - * Remember, the file extension must not be included in the filename.

    - * Available since Asterisk 1.2 - * + * AGI Command: CONTROL STREAM FILE + *

    + * Send the given file, allowing playback to be controlled by the given digits, if any. + * Use double quotes for the digits if you wish none to be permitted. + * If offsetms is provided then the audio will seek to offsetms before play starts. + * Returns 0 if playback completes without a digit being pressed, or the ASCII numerical value of the digit if one was pressed, + * or -1 on error or if the channel was disconnected. Returns the position where playback was terminated as endpos. + *

    + * See: AGI Command CONTROL STREAM FILE (Asterisk 18) + * * @author srt - * @version $Id$ - * @since 0.2 */ -public class ControlStreamFileCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class ControlStreamFileCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3978141041352128820L; /** @@ -60,30 +53,25 @@ public class ControlStreamFileCommand extends AbstractAgiCommand private String pauseDigit; /** - * Creates a new ControlStreamFileCommand, streaming from the beginning. It - * uses the default digit "#" for forward and "*" for rewind and does not - * support pausing. - * + * Creates a new ControlStreamFileCommand, streaming from the beginning. + * It uses the default digit "#" for forward and "*" for rewind and does not support pausing. + * * @param file the name of the file to stream, must not include extension. */ - public ControlStreamFileCommand(String file) - { + public ControlStreamFileCommand(String file) { super(); this.file = file; this.offset = -1; } /** - * Creates a new ControlStreamFileCommand, streaming from the beginning. It - * uses the default digit "#" for forward and "*" for rewind and does not - * support pausing. - * - * @param file the name of the file to stream, must not include extension. - * @param escapeDigits contains the digits that allow the user to interrupt - * this command. + * Creates a new ControlStreamFileCommand, streaming from the beginning. + * It uses the default digit "#" for forward and "*" for rewind and does not support pausing. + * + * @param file the name of the file to stream, must not include extension. + * @param escapeDigits contains the digits that allow the user to interrupt this command. */ - public ControlStreamFileCommand(String file, String escapeDigits) - { + public ControlStreamFileCommand(String file, String escapeDigits) { super(); this.file = file; this.escapeDigits = escapeDigits; @@ -92,17 +80,14 @@ public ControlStreamFileCommand(String file, String escapeDigits) /** * Creates a new ControlStreamFileCommand, streaming from the given offset. - * It uses the default digit "#" for forward and "*" for rewind and does not - * support pausing. - * - * @param file the name of the file to stream, must not include extension. - * @param escapeDigits contains the digits that allow the user to interrupt - * this command. May be null if you don't want the - * user to interrupt. - * @param offset the offset samples to skip before streaming. - */ - public ControlStreamFileCommand(String file, String escapeDigits, int offset) - { + * It uses the default digit "#" for forward and "*" for rewind and does not support pausing. + * + * @param file the name of the file to stream, must not include extension. + * @param escapeDigits contains the digits that allow the user to interrupt this command. + * May be null if you don't want the user to interrupt. + * @param offset the offset samples to skip before streaming. + */ + public ControlStreamFileCommand(String file, String escapeDigits, int offset) { super(); this.file = file; this.escapeDigits = escapeDigits; @@ -112,20 +97,18 @@ public ControlStreamFileCommand(String file, String escapeDigits, int offset) /** * Creates a new ControlStreamFileCommand, streaming from the given offset. * It allows the user to pause streaming by pressing the pauseDigit. - * - * @param file the name of the file to stream, must not include extension. - * @param escapeDigits contains the digits that allow the user to interrupt - * this command. May be null if you don't want the - * user to interrupt. - * @param offset the offset samples to skip before streaming. - * @param forwardDigit the digit for fast forward. - * @param rewindDigit the digit for rewind. - * @param pauseDigit the digit for pause and unpause. - */ - public ControlStreamFileCommand(String file, String escapeDigits, - int offset, String forwardDigit, String rewindDigit, - String pauseDigit) - { + * + * @param file the name of the file to stream, must not include extension. + * @param escapeDigits contains the digits that allow the user to interrupt this command. + * May be null if you don't want the user to interrupt. + * @param offset the offset samples to skip before streaming. + * @param forwardDigit the digit for fast-forward. + * @param rewindDigit the digit for rewind. + * @param pauseDigit the digit for pause and unpause. + */ + public ControlStreamFileCommand( + String file, String escapeDigits, int offset, String forwardDigit, String rewindDigit, String pauseDigit + ) { super(); this.file = file; this.escapeDigits = escapeDigits; @@ -137,154 +120,131 @@ public ControlStreamFileCommand(String file, String escapeDigits, /** * Returns the name of the file to stream. - * + * * @return the name of the file to stream. */ - public String getFile() - { + public String getFile() { return file; } /** * Sets the name of the file to stream. - * + * * @param file the name of the file to stream, must not include extension. */ - public void setFile(String file) - { + public void setFile(String file) { this.file = file; } /** * Returns the digits that allow the user to interrupt this command. - * + * * @return the digits that allow the user to interrupt this command. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } /** * Sets the digits that allow the user to interrupt this command. - * - * @param escapeDigits the digits that allow the user to interrupt this - * command or null for none. + * + * @param escapeDigits the digits that allow the user to interrupt this command or null for none. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } /** * Returns the offset samples to skip before streaming. - * + * * @return the offset samples to skip before streaming. */ - public int getOffset() - { + public int getOffset() { return offset; } /** * Sets the offset samples to skip before streaming. - * + * * @param offset the offset samples to skip before streaming. */ - public void setOffset(int offset) - { + public void setOffset(int offset) { this.offset = offset; } /** - * Returns the digit for fast forward. - * - * @return the digit for fast forward. + * Returns the digit for fast-forward. + * + * @return the digit for fast-forward. */ - public String getForwardDigit() - { + public String getForwardDigit() { return forwardDigit; } /** * Returns the digit for rewind. - * + * * @return the digit for rewind. */ - public String getRewindDigit() - { + public String getRewindDigit() { return rewindDigit; } /** * Retruns the digit for pause and unpause. - * + * * @return the digit for pause and unpause. */ - public String getPauseDigit() - { + public String getPauseDigit() { return pauseDigit; } /** - * Sets the control digits for fast forward and rewind. - * - * @param forwardDigit the digit for fast forward. - * @param rewindDigit the digit for rewind. + * Sets the control digits for fast-forward and rewind. + * + * @param forwardDigit the digit for fast-forward. + * @param rewindDigit the digit for rewind. */ - public void setControlDigits(String forwardDigit, String rewindDigit) - { + public void setControlDigits(String forwardDigit, String rewindDigit) { this.forwardDigit = forwardDigit; this.rewindDigit = rewindDigit; } /** - * Sets the control digits for fast forward, rewind and pause. - * - * @param forwardDigit the digit for fast forward. - * @param rewindDigit the digit for rewind. - * @param pauseDigit the digit for pause and unpause. + * Sets the control digits for fast-forward, rewind and pause. + * + * @param forwardDigit the digit for fast-forward. + * @param rewindDigit the digit for rewind. + * @param pauseDigit the digit for pause and unpause. */ - public void setControlDigits(String forwardDigit, String rewindDigit, - String pauseDigit) - { + public void setControlDigits(String forwardDigit, String rewindDigit, String pauseDigit) { this.forwardDigit = forwardDigit; this.rewindDigit = rewindDigit; this.pauseDigit = pauseDigit; } @Override - public String buildCommand() - { - StringBuffer sb; - - sb = new StringBuffer("CONTROL STREAM FILE "); + public String buildCommand() { + StringBuilder sb = new StringBuilder("CONTROL STREAM FILE "); sb.append(escapeAndQuote(file)); sb.append(" "); sb.append(escapeAndQuote(escapeDigits)); - if (offset >= 0) - { + if (offset >= 0) { sb.append(" "); sb.append(offset); - } - else if (forwardDigit != null || rewindDigit != null - || pauseDigit != null) - { + } else if (forwardDigit != null || rewindDigit != null || pauseDigit != null) { sb.append(" 0"); } - if (forwardDigit != null || rewindDigit != null || pauseDigit != null) - { + if (forwardDigit != null || rewindDigit != null || pauseDigit != null) { sb.append(" "); sb.append(forwardDigit); } - if (rewindDigit != null || pauseDigit != null) - { + if (rewindDigit != null || pauseDigit != null) { sb.append(" "); sb.append(rewindDigit); } - if (pauseDigit != null) - { + if (pauseDigit != null) { sb.append(" "); sb.append(pauseDigit); } diff --git a/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelCommand.java b/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelCommand.java index 2c27d2fe4..1c94366ac 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelCommand.java @@ -1,34 +1,31 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Deletes a family or specific keytree within a family in the Asterisk - * database.

    + * AGI Command: DATABASE DEL + *

    + * Deletes an entry in the Asterisk database for a given family and key.
    * Returns 1 if successful, 0 otherwise. - * + *

    + * See: AGI Command DATABASE DEL (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class DatabaseDelCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class DatabaseDelCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -43,23 +40,21 @@ public class DatabaseDelCommand extends AbstractAgiCommand /** * Creates a new DatabaseDelCommand to delete a family. - * + * * @param family the family to delete. */ - public DatabaseDelCommand(String family) - { + public DatabaseDelCommand(String family) { super(); this.family = family; } /** * Creates a new DatabaseDelCommand to delete a keytree. - * - * @param family the family of the keytree to delete. + * + * @param family the family of the keytree to delete. * @param keyTree the keytree to delete. */ - public DatabaseDelCommand(String family, String keyTree) - { + public DatabaseDelCommand(String family, String keyTree) { super(); this.family = family; this.keyTree = keyTree; @@ -67,48 +62,42 @@ public DatabaseDelCommand(String family, String keyTree) /** * Returns the family (or family of the keytree) to delete. - * + * * @return the family (or family of the keytree) to delete. */ - public String getFamily() - { + public String getFamily() { return family; } /** * Sets the family (or family of the keytree) to delete. - * + * * @param family the family (or family of the keytree) to delete. */ - public void setFamily(String family) - { + public void setFamily(String family) { this.family = family; } /** * Returns the the keytree to delete. - * + * * @return the keytree to delete. */ - public String getKeyTree() - { + public String getKeyTree() { return keyTree; } /** * Sets the keytree to delete. - * + * * @param keyTree the keytree to delete. */ - public void setKeyTree(String keyTree) - { + public void setKeyTree(String keyTree) { this.keyTree = keyTree; } @Override - public String buildCommand() - { - return "DATABASE DELTREE " + escapeAndQuote(family) - + (keyTree == null ? "" : " " + escapeAndQuote(keyTree)); + public String buildCommand() { + return "DATABASE DEL " + escapeAndQuote(family) + (keyTree == null ? "" : " " + escapeAndQuote(keyTree)); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelTreeCommand.java b/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelTreeCommand.java index 43948a261..17e438797 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelTreeCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelTreeCommand.java @@ -1,33 +1,31 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Deletes a family or specific keytree within a family in the Asterisk database.

    + * AGI Command: DATABASE DELTREE + *

    + * Deletes a family or specific keytree within a family in the Asterisk database.
    * Returns 1 if successful, 0 otherwise. - * + *

    + * See: AGI Command DATABASE DELTREE (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class DatabaseDelTreeCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class DatabaseDelTreeCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -42,23 +40,22 @@ public class DatabaseDelTreeCommand extends AbstractAgiCommand /** * Creates a new DatabaseDelCommand to delete a whole family. - * + * * @param family the family to delete. */ - public DatabaseDelTreeCommand(String family) - { + public DatabaseDelTreeCommand(String family) { super(); this.family = family; } /** - * Creates a new DatabaseDelCommand to delete a keytree within a given family. - * - * @param family the family of the keytree to delete. + * Creates a new DatabaseDelCommand to delete a keytree within a given + * family. + * + * @param family the family of the keytree to delete. * @param keyTree the keytree to delete. */ - public DatabaseDelTreeCommand(String family, String keyTree) - { + public DatabaseDelTreeCommand(String family, String keyTree) { super(); this.family = family; this.keyTree = keyTree; @@ -66,54 +63,45 @@ public DatabaseDelTreeCommand(String family, String keyTree) /** * Returns the family of the key to delete. - * + * * @return the family of the key to delete. */ - public String getFamily() - { + public String getFamily() { return family; } /** * Sets the family of the key to delete. - * + * * @param family the family of the key to delete. */ - public void setFamily(String family) - { + public void setFamily(String family) { this.family = family; } /** - * Returns the the keytree to delete. - * + * Returns the keytree to delete. + * * @return the keytree to delete. */ - public String getKeyTree() - { + public String getKeyTree() { return keyTree; } /** * Sets the keytree to delete. - * + * * @param keyTree the keytree to delete, null to delete the whole family. */ - public void setKeyTree(String keyTree) - { + public void setKeyTree(String keyTree) { this.keyTree = keyTree; } @Override - public String buildCommand() - { - if (keyTree == null) - { + public String buildCommand() { + if (keyTree != null) { return "DATABASE DELTREE " + escapeAndQuote(family) + " " + escapeAndQuote(keyTree); } - else - { - return "DATABASE DELTREE " + escapeAndQuote(family); - } + return "DATABASE DELTREE " + escapeAndQuote(family); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/DatabaseGetCommand.java b/src/main/java/org/asteriskjava/fastagi/command/DatabaseGetCommand.java index c3732893a..740d0a4d6 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/DatabaseGetCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/DatabaseGetCommand.java @@ -1,35 +1,31 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Retrieves an entry in the Asterisk database for a given family and key.

    - * Returns 0 if is not set. Returns 1 if the variable is set and returns the - * value in parenthesis.

    - * Example return code: 200 result=1 (testvariable) - * + * AGI Command: DATABASE GET + *

    + * Retrieves an entry in the Asterisk database for a given family and key.
    + * Returns 0 if is not set. Returns 1 if the variable is set and returns the value in parentheses. + *

    + * See: AGI Command DATABASE GET (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class DatabaseGetCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class DatabaseGetCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -44,12 +40,11 @@ public class DatabaseGetCommand extends AbstractAgiCommand /** * Creates a new DatabaseGetCommand. - * + * * @param family the family of the key to retrieve. - * @param key the key to retrieve. + * @param key the key to retrieve. */ - public DatabaseGetCommand(String family, String key) - { + public DatabaseGetCommand(String family, String key) { super(); this.family = family; this.key = key; @@ -57,48 +52,42 @@ public DatabaseGetCommand(String family, String key) /** * Returns the family of the key to retrieve. - * + * * @return the family of the key to retrieve. */ - public String getFamily() - { + public String getFamily() { return family; } /** * Sets the family of the key to retrieve. - * + * * @param family the family of the key to retrieve. */ - public void setFamily(String family) - { + public void setFamily(String family) { this.family = family; } /** - * Returns the the key to retrieve. - * + * Returns the key to retrieve. + * * @return the key to retrieve. */ - public String getKey() - { + public String getKey() { return key; } /** * Sets the key to retrieve. - * + * * @param key the key to retrieve. */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } @Override - public String buildCommand() - { - return "DATABASE GET " + escapeAndQuote(family) + " " - + escapeAndQuote(key); + public String buildCommand() { + return "DATABASE GET " + escapeAndQuote(family) + " " + escapeAndQuote(key); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/DatabasePutCommand.java b/src/main/java/org/asteriskjava/fastagi/command/DatabasePutCommand.java index 93a3ba9de..808edddf8 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/DatabasePutCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/DatabasePutCommand.java @@ -1,34 +1,31 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Adds or updates an entry in the Asterisk database for a given family, key, - * and value.

    + * AGI Command: DATABASE PUT + *

    + * Adds or updates an entry in the Asterisk database for a given family, key, and value.
    * Returns 1 if successful, 0 otherwise. - * + *

    + * See: AGI Command DATABASE PUT (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class DatabasePutCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class DatabasePutCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -48,13 +45,12 @@ public class DatabasePutCommand extends AbstractAgiCommand /** * Creates a new DatabasePutCommand. - * + * * @param family the family of the key to set. - * @param key the key to set. - * @param value the value to set. + * @param key the key to set. + * @param value the value to set. */ - public DatabasePutCommand(String family, String key, String value) - { + public DatabasePutCommand(String family, String key, String value) { super(); this.family = family; this.key = key; @@ -63,68 +59,60 @@ public DatabasePutCommand(String family, String key, String value) /** * Returns the family of the key to set. - * + * * @return the family of the key to set. */ - public String getFamily() - { + public String getFamily() { return family; } /** * Sets the family of the key to set. - * + * * @param family the family of the key to set. */ - public void setFamily(String family) - { + public void setFamily(String family) { this.family = family; } /** - * Returns the the key to set. - * + * Returns the key to set. + * * @return the key to set. */ - public String getKey() - { + public String getKey() { return key; } /** * Sets the key to set. - * + * * @param key the key to set. */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } /** * Returns the value to set. - * + * * @return the value to set. */ - public String getValue() - { + public String getValue() { return value; } /** * Sets the value to set. - * + * * @param value the value to set. */ - public void setValue(String value) - { + public void setValue(String value) { this.value = value; } @Override - public String buildCommand() - { - return "DATABASE PUT " + escapeAndQuote(family) + " " - + escapeAndQuote(key) + " " + escapeAndQuote(value); + public String buildCommand() { + return "DATABASE PUT " + escapeAndQuote(family) + " " + escapeAndQuote(key) + " " + escapeAndQuote(value); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/DialCommand.java b/src/main/java/org/asteriskjava/fastagi/command/DialCommand.java new file mode 100644 index 000000000..e306f8e46 --- /dev/null +++ b/src/main/java/org/asteriskjava/fastagi/command/DialCommand.java @@ -0,0 +1,64 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.asteriskjava.util.Log; + +import static org.asteriskjava.AsteriskVersion.ASTERISK_10; +import static org.asteriskjava.util.LogFactory.getLog; + +/** + * This is not a real AGI command. + *

    + * It uses EXEC command and add dial application features. + *

    + * See: AGI Command EXEC (Asterisk 18)
    + * See: Application Dial (Asterisk 18) + */ +public class DialCommand extends AbstractAgiCommand { + private static final long serialVersionUID = 3762248656229053753L; + + private final Log logger = getLog(getClass()); + + private final String target; + private final int timeout; + private final String options; + + public DialCommand(String target, int timeout, String options) { + super(); + this.target = target; + this.timeout = timeout; + this.options = options; + } + + @Override + public String buildCommand() { + + String separator = "|"; + if (getAsteriskVersion().isAtLeast(ASTERISK_10)) { + separator = ","; + } + + String command = "EXEC " + escapeAndQuote("dial") + " " + escapeAndQuote(target) + separator + escapeAndQuote("" + timeout); + if (options != null && options.length() > 0) { + command += separator + escapeAndQuote(options); + } + + logger.info(command); + + return command; + } +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/ExecCommand.java b/src/main/java/org/asteriskjava/fastagi/command/ExecCommand.java index b65be09b3..636bc0f36 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/ExecCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/ExecCommand.java @@ -1,34 +1,33 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; +import static java.lang.String.format; + /** - * Executes an application with the given options.

    - * Returns whatever the application returns, or -2 if the application was not - * found. - * + * AGI Command: EXEC + *

    + * Executes an application with the given options.
    + * Returns whatever the application returns, or -2 if the application was not found. + *

    + * See: EXEC (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class ExecCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class ExecCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3904959746380281145L; /** @@ -41,25 +40,12 @@ public class ExecCommand extends AbstractAgiCommand */ private String[] options; - /** - * Creates a new ExecCommand. - * - * @param application the name of the application to execute. - */ - public ExecCommand(String application) - { + public ExecCommand(String application) { super(); this.application = application; } - /** - * Creates a new ExecCommand. - * - * @param application the name of the application to execute. - * @param options the options to pass to the application. - */ - public ExecCommand(String application, String... options) - { + public ExecCommand(String application, String... options) { super(); this.application = application; this.options = options; @@ -67,48 +53,42 @@ public ExecCommand(String application, String... options) /** * Returns the name of the application to execute. - * + * * @return the name of the application to execute. */ - public String getApplication() - { + public String getApplication() { return application; } /** * Sets the name of the application to execute. - * + * * @param application the name of the application to execute. */ - public void setApplication(String application) - { + public void setApplication(String application) { this.application = application; } /** * Returns the options to pass to the application. - * + * * @return the options to pass to the application. */ - public String[] getOptions() - { + public String[] getOptions() { return options; } /** * Sets the options to pass to the application. - * + * * @param options the options to pass to the application. */ - public void setOptions(String... options) - { + public void setOptions(String... options) { this.options = options; } @Override - public String buildCommand() - { - return "EXEC " + escapeAndQuote(application) + " " - + escapeAndQuote(options); + public String buildCommand() { + return format("EXEC %s %s", escapeAndQuote(application), escapeAndQuote(options)); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/GetDataCommand.java b/src/main/java/org/asteriskjava/fastagi/command/GetDataCommand.java index 14c6c62f8..64bd2c31d 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/GetDataCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/GetDataCommand.java @@ -17,52 +17,48 @@ package org.asteriskjava.fastagi.command; /** - * Stream the given file, and recieve DTMF data. The user may interrupt the streaming - * by starting to enter digits.

    - * Returns the digits recieved from the channel at the other end.

    - * Input ends when the timeout is reached, the maximum number of digits is read - * or the user presses #. - * + * AGI Command: GET DATA + *

    + * Stream the given file, and receive DTMF data. The user may interrupt the streaming by starting to enter digits.
    + * Returns the digits received from the channel at the other end. + *

    + * Input ends when the timeout is reached, the maximum number of digits is read or the user presses #. + *

    + * See: AGI Command GET DATA (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class GetDataCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class GetDataCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3978141041352128820L; - private static final int DEFAULT_MAX_DIGITS = 1024; private static final int DEFAULT_TIMEOUT = 0; + private static final int DEFAULT_MAX_DIGITS = 1024; - /** * The name of the file to stream. */ private String file; /** - * The timeout in milliseconds to wait for data.

    - * 0 means standard timeout value, -1 means "ludicrous time" (essentially - * never times out). + * The timeout in milliseconds to wait for data. + *

    + * 0 means standard timeout value, -1 means "ludicrous time" (essentially never times out). */ private long timeout; /** - * The maximum number of digits to read.

    + * The maximum number of digits to read. + *

    * Must be in [1..1024]. */ private int maxDigits; /** - * Creates a new GetDataCommand with default timeout and maxDigits set to - * 1024. - * + * Creates a new GetDataCommand with default timeout and maxDigits set to 1024. + * * @param file the name of the file to stream, must not include extension. */ - public GetDataCommand(String file) - { + public GetDataCommand(String file) { super(); this.file = file; this.timeout = DEFAULT_TIMEOUT; @@ -72,14 +68,13 @@ public GetDataCommand(String file) /** * Creates a new GetDataCommand with the given timeout and maxDigits set to * 1024. - * - * @param file the name of the file to stream, must not include extension. - * @param timeout the timeout in milliseconds to wait for data.

    - * 0 means standard timeout value, -1 means "ludicrous time" - * (essentially never times out). + * + * @param file the name of the file to stream, must not include extension. + * @param timeout the timeout in milliseconds to wait for data. + *

    + * 0 means standard timeout value, -1 means "ludicrous time" (essentially never times out). */ - public GetDataCommand(String file, long timeout) - { + public GetDataCommand(String file, long timeout) { super(); this.file = file; this.timeout = timeout; @@ -88,24 +83,19 @@ public GetDataCommand(String file, long timeout) /** * Creates a new GetDataCommand with the given timeout and maxDigits. - * - * @param file the name of the file to stream, must not include extension. - * @param timeout the timeout in milliseconds to wait for data.

    - * 0 means standard timeout value, -1 means "ludicrous time" - * (essentially never times out). - * @param maxDigits the maximum number of digits to read.

    - * Must be in [1..1024]. - * + * + * @param file the name of the file to stream, must not include extension. + * @param timeout the timeout in milliseconds to wait for data. + *

    + * 0 means standard timeout value, -1 means "ludicrous time" (essentially never times out). + * @param maxDigits the maximum number of digits to read. + *

    + * Must be in [1..1024]. * @throws IllegalArgumentException if maxDigits is not in [1..1024] */ - public GetDataCommand(String file, long timeout, int maxDigits) - throws IllegalArgumentException - { + public GetDataCommand(String file, long timeout, int maxDigits) throws IllegalArgumentException { super(); - if (maxDigits < 1 || maxDigits > 1024) - { - throw new IllegalArgumentException("maxDigits must be in [1..1024]"); - } + validateMaxDigits(maxDigits); this.file = file; this.timeout = timeout; @@ -114,90 +104,81 @@ public GetDataCommand(String file, long timeout, int maxDigits) /** * Returns the name of the file to stream. - * + * * @return the name of the file to stream. */ - public String getFile() - { + public String getFile() { return file; } /** - * Sets the name of the file to stream.

    + * Sets the name of the file to stream. + *

    * This attribute is mandatory. - * + * * @param file the name of the file to stream, must not include extension. */ - public void setFile(String file) - { + public void setFile(String file) { this.file = file; } /** * Returns the timeout to wait for data. - * + * * @return the timeout in milliseconds to wait for data. */ - public long getTimeout() - { + public long getTimeout() { return timeout; } /** * Sets the timeout to wait for data. - * - * @param timeout the timeout in milliseconds to wait for data.

    - * 0 means standard timeout value, -1 means "ludicrous time" - * (essentially never times out). + * + * @param timeout the timeout in milliseconds to wait for data. + *

    + * 0 means standard timeout value, -1 means "ludicrous time" (essentially never times out). */ - public void setTimeout(long timeout) - { + public void setTimeout(long timeout) { this.timeout = timeout; } /** * Returns the maximum number of digits to read. - * + * * @return the maximum number of digits to read. */ - public int getMaxDigits() - { + public int getMaxDigits() { return maxDigits; } /** * Sets the maximum number of digits to read. - * - * @param maxDigits the maximum number of digits to read.

    - * Must be in [1..1024]. - * + * + * @param maxDigits the maximum number of digits to read. + *

    + * Must be in [1..1024]. * @throws IllegalArgumentException if maxDigits is not in [1..1024] */ - public void setMaxDigits(int maxDigits) throws IllegalArgumentException - { - if (maxDigits < 1 || maxDigits > 1024) - { - throw new IllegalArgumentException("maxDigits must be in [1..1024]"); - } + public void setMaxDigits(int maxDigits) throws IllegalArgumentException { + validateMaxDigits(maxDigits); this.maxDigits = maxDigits; } @Override - public String buildCommand() - { - if (maxDigits == DEFAULT_MAX_DIGITS) - { - if (timeout == DEFAULT_TIMEOUT) - { + public String buildCommand() { + if (maxDigits == DEFAULT_MAX_DIGITS) { + if (timeout == DEFAULT_TIMEOUT) { return "GET DATA " + escapeAndQuote(file); } - else - { - return "GET DATA " + escapeAndQuote(file) + " " + timeout; - } + return "GET DATA " + escapeAndQuote(file) + " " + timeout; + } + return "GET DATA " + escapeAndQuote(file) + " " + timeout + " " + maxDigits; + } + + private static void validateMaxDigits(int maxDigits) { + if (maxDigits < 1 || maxDigits > 1024) { + throw new IllegalArgumentException("maxDigits must be in [1..1024]"); } - return "GET DATA " + escapeAndQuote(file) + " " + timeout + " " - + maxDigits; } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/GetFullVariableCommand.java b/src/main/java/org/asteriskjava/fastagi/command/GetFullVariableCommand.java index b3d76d04d..a5277cbaa 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/GetFullVariableCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/GetFullVariableCommand.java @@ -1,41 +1,34 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Returns the value of the given channel varible and understands complex - * variable names and builtin variables, unlike the GetVariableCommand.

    - * You can also use this command to use custom Asterisk functions. Syntax is - * "func(args)".

    - * Returns 0 if the variable is not set or channel does not exist. Returns 1 if - * the variable is set and returns the variable in parenthesis.

    - * Available since Asterisk 1.2

    + * AGI Command: GET FULL VARIABLE + *

    + * Evaluates the given expression against the channel specified by channelname, or the current channel if channelname is not provided.
    + * Unlike GET VARIABLE, the expression is processed in a manner similar to dialplan evaluation, + * allowing complex and built-in variables to be accessed, e.g. The time is ${EPOCH}
    + * Returns 0 if no channel matching channelname exists, 1 otherwise.
    * Example return code: 200 result=1 (testvariable) - * - * @since 0.2 + *

    + * See: AGI Command GET FULL VARIABLE (Asterisk 18) + * * @author srt - * @version $Id$ - * @see org.asteriskjava.fastagi.command.GetVariableCommand */ -public class GetFullVariableCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class GetFullVariableCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -47,23 +40,21 @@ public class GetFullVariableCommand extends AbstractAgiCommand /** * Creates a new GetFullVariableCommand. - * + * * @param variable the name of the variable to retrieve. */ - public GetFullVariableCommand(String variable) - { + public GetFullVariableCommand(String variable) { super(); this.variable = variable; } /** * Creates a new GetFullVariableCommand. - * + * * @param variable the name of the variable to retrieve. - * @param channel the name of the channel. + * @param channel the name of the channel. */ - public GetFullVariableCommand(String variable, String channel) - { + public GetFullVariableCommand(String variable, String channel) { super(); this.variable = variable; this.channel = channel; @@ -71,56 +62,49 @@ public GetFullVariableCommand(String variable, String channel) /** * Returns the name of the variable to retrieve. - * - * @return the the name of the variable to retrieve. + * + * @return the name of the variable to retrieve. */ - public String getVariable() - { + public String getVariable() { return variable; } /** * Sets the name of the variable to retrieve.

    - * You can also use custom dialplan functions (like "func(args)") as - * variable. - * + * You can also use custom dialplan functions (like "func(args)") as variable. + * * @param variable the name of the variable to retrieve. */ - public void setVariable(String variable) - { + public void setVariable(String variable) { this.variable = variable; } /** - * Returns the the name of the channel. - * + * Returns the name of the channel. + * * @return the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel. - * + * * @param channel the name of the channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @Override - public String buildCommand() - { - StringBuffer sb; + public String buildCommand() { + StringBuilder sb; - sb = new StringBuffer("GET FULL VARIABLE "); + sb = new StringBuilder("GET FULL VARIABLE "); sb.append(escapeAndQuote(variable)); - if (channel != null) - { + if (channel != null) { sb.append(" "); sb.append(escapeAndQuote(channel)); } diff --git a/src/main/java/org/asteriskjava/fastagi/command/GetOptionCommand.java b/src/main/java/org/asteriskjava/fastagi/command/GetOptionCommand.java index 8f26f4ee6..edce75aa6 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/GetOptionCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/GetOptionCommand.java @@ -1,40 +1,32 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Plays the given file, and waits for the user to press one of the given - * digits. If none of the esacpe digits is pressed while streaming the file this - * command waits for the specified timeout still waiting for the user to press a - * digit. Streaming always begins at the beginning.

    - * Returns 0 if no digit being pressed, or the ASCII numerical value of the - * digit if one was pressed, or -1 on error or if the channel was disconnected. - *

    + * AGI Command: GET OPTION + *

    + * Behaves similar to STREAM FILE but used with a timeout option.
    * Remember, the file extension must not be included in the filename. + *

    + * See: AGI Command GET OPTION (Asterisk 18) * * @author srt - * @version $Id$ - * @see org.asteriskjava.fastagi.command.StreamFileCommand + * @see StreamFileCommand */ -public class GetOptionCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class GetOptionCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3978141041352128820L; /** @@ -56,11 +48,9 @@ public class GetOptionCommand extends AbstractAgiCommand * Creates a new GetOptionCommand with a default timeout of 5 seconds. * * @param file the name of the file to stream, must not include extension. - * @param escapeDigits contains the digits that the user is expected to - * press. + * @param escapeDigits contains the digits that the user is expected to press. */ - public GetOptionCommand(String file, String escapeDigits) - { + public GetOptionCommand(String file, String escapeDigits) { super(); this.file = file; this.escapeDigits = escapeDigits; @@ -71,13 +61,10 @@ public GetOptionCommand(String file, String escapeDigits) * Creates a new GetOptionCommand with the given timeout. * * @param file the name of the file to stream, must not include extension. - * @param escapeDigits contains the digits that the user is expected to - * press. - * @param timeout the timeout in milliseconds to wait if none of the defined - * esacpe digits was presses while streaming. + * @param escapeDigits contains the digits that the user is expected to press. + * @param timeout the timeout in milliseconds to wait if none of the defined escape digits was presses while streaming. */ - public GetOptionCommand(String file, String escapeDigits, long timeout) - { + public GetOptionCommand(String file, String escapeDigits, long timeout) { super(); this.file = file; this.escapeDigits = escapeDigits; @@ -89,8 +76,7 @@ public GetOptionCommand(String file, String escapeDigits, long timeout) * * @return the name of the file to stream. */ - public String getFile() - { + public String getFile() { return file; } @@ -99,8 +85,7 @@ public String getFile() * * @param file the name of the file to stream, must not include extension. */ - public void setFile(String file) - { + public void setFile(String file) { this.file = file; } @@ -109,8 +94,7 @@ public void setFile(String file) * * @return the digits that the user is expected to press. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } @@ -119,38 +103,30 @@ public String getEscapeDigits() * * @param escapeDigits the digits that the user is expected to press. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } /** - * Returns the timeout to wait if none of the defined esacpe digits was - * presses while streaming. + * Returns the timeout to wait if none of the defined escape digits was presses while streaming. * * @return the timeout in milliseconds. */ - public long getTimeout() - { + public long getTimeout() { return timeout; } /** - * Sets the timeout to wait if none of the defined esacpe digits was presses - * while streaming. + * Sets the timeout to wait if none of the defined escape digits was presses while streaming. * - * @param timeout the timeout in milliks,seconds. + * @param timeout the timeout in millis,seconds. */ - public void setTimeout(long timeout) - { + public void setTimeout(long timeout) { this.timeout = timeout; } @Override - public String buildCommand() - { - return "GET OPTION " + escapeAndQuote(file) + " " - + escapeAndQuote(escapeDigits) - + (timeout < 0 ? "" : " " + timeout); + public String buildCommand() { + return "GET OPTION " + escapeAndQuote(file) + " " + escapeAndQuote(escapeDigits) + (timeout < 0 ? "" : " " + timeout); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/GetVariableCommand.java b/src/main/java/org/asteriskjava/fastagi/command/GetVariableCommand.java index 471f28f8e..1dcf263d3 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/GetVariableCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/GetVariableCommand.java @@ -1,37 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Returns the value of the given channel varible.

    - * Since Asterisk 1.2 you can also use this command to use custom Asterisk - * functions. Syntax is "func(args)".

    - * Returns 0 if the variable is not set. Returns 1 if the variable is set and - * returns the variable in parenthesis.

    - * Example return code: 200 result=1 (testvariable) - * + * AGI Command: GET VARIABLE + *

    + * Gets a channel variable. + *

    + * See: AGI Command GET VARIABLE (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class GetVariableCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class GetVariableCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -41,40 +34,35 @@ public class GetVariableCommand extends AbstractAgiCommand /** * Creates a new GetVariableCommand. - * + * * @param variable the name of the variable to retrieve. */ - public GetVariableCommand(String variable) - { + public GetVariableCommand(String variable) { super(); this.variable = variable; } /** * Returns the name of the variable to retrieve. - * - * @return the the name of the variable to retrieve. + * + * @return the name of the variable to retrieve. */ - public String getVariable() - { + public String getVariable() { return variable; } /** * Sets the name of the variable to retrieve.

    - * Since Asterisk 1.2 you can also use custom dialplan functions (like - * "func(args)") as variable. - * + * Since Asterisk 1.2 you can also use custom dialplan functions (like "func(args)") as variable. + * * @param variable the name of the variable to retrieve. */ - public void setVariable(String variable) - { + public void setVariable(String variable) { this.variable = variable; } @Override - public String buildCommand() - { + public String buildCommand() { return "GET VARIABLE " + escapeAndQuote(variable); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/GosubCommand.java b/src/main/java/org/asteriskjava/fastagi/command/GosubCommand.java index c4a80f79e..73015b708 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/GosubCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/GosubCommand.java @@ -1,17 +1,31 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.asteriskjava.fastagi.command; /** - * Calls a subroutine from dialplan. - *

    - * Example return code: 200 result=0 Gosub complete - *

    - * This command is available since Asterisk 1.6. + * AGI Command: GOSUB + *

    + * Cause the channel to execute the specified dialplan subroutine. + *

    + * See: AGI Command GOSUB (Asterisk 18) * * @author fadishei * @since 1.0.0 */ -public class GosubCommand extends AbstractAgiCommand -{ +public class GosubCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; /** @@ -31,9 +45,9 @@ public class GosubCommand extends AbstractAgiCommand /** * an optional list of arguments to be passed to the subroutine. - * They will accessible in the form of ${ARG1}, ${ARG2}, etc in the subroutine body. + * They will be accessible in the form of ${ARG1}, ${ARG2}, etc in the subroutine body. */ - private String arguments[]; + private String[] arguments; /** * Creates a new GosubCommand. @@ -42,8 +56,7 @@ public class GosubCommand extends AbstractAgiCommand * @param extension the extension in the called context. * @param priority of the called extension. */ - public GosubCommand(String context, String extension, String priority) - { + public GosubCommand(String context, String extension, String priority) { super(); this.context = context; this.extension = extension; @@ -58,8 +71,7 @@ public GosubCommand(String context, String extension, String priority) * @param priority the priority of the called extension. * @param arguments the arguments to be passed to the called subroutine. */ - public GosubCommand(String context, String extension, String priority, String... arguments) - { + public GosubCommand(String context, String extension, String priority, String... arguments) { super(); this.context = context; this.extension = extension; @@ -72,8 +84,7 @@ public GosubCommand(String context, String extension, String priority, String... * * @return the context of the subroutine to call. */ - public String getContext() - { + public String getContext() { return context; } @@ -82,8 +93,7 @@ public String getContext() * * @param context the context of the subroutine to call. */ - public void setContext(String context) - { + public void setContext(String context) { this.context = context; } @@ -92,8 +102,7 @@ public void setContext(String context) * * @return the extension within the called context. */ - public String getExtension() - { + public String getExtension() { return extension; } @@ -102,8 +111,7 @@ public String getExtension() * * @param extension the extension within the called context. */ - public void setExtension(String extension) - { + public void setExtension(String extension) { this.extension = extension; } @@ -112,8 +120,7 @@ public void setExtension(String extension) * * @return the priority of the called extension. */ - public String getPriority() - { + public String getPriority() { return priority; } @@ -122,8 +129,7 @@ public String getPriority() * * @param priority the priority of the called extension. */ - public void setPriority(String priority) - { + public void setPriority(String priority) { this.priority = priority; } @@ -132,8 +138,7 @@ public void setPriority(String priority) * * @return the arguments to be passed to the subroutine. */ - public String[] getArguments() - { + public String[] getArguments() { return arguments; } @@ -142,21 +147,18 @@ public String[] getArguments() * * @param arguments the arguments to be passed to the subroutine. */ - public void setArguments(String[] arguments) - { + public void setArguments(String[] arguments) { this.arguments = arguments; } @Override - public String buildCommand() - { + public String buildCommand() { final StringBuilder sb = new StringBuilder("GOSUB "); sb.append(escapeAndQuote(context)).append(" "); sb.append(escapeAndQuote(extension)).append(" "); sb.append(escapeAndQuote(priority)); - if (arguments != null) - { + if (arguments != null) { sb.append(" ").append(escapeAndQuote(arguments)); } diff --git a/src/main/java/org/asteriskjava/fastagi/command/HangupCommand.java b/src/main/java/org/asteriskjava/fastagi/command/HangupCommand.java index 22859e0df..274eaa0f4 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/HangupCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/HangupCommand.java @@ -1,86 +1,74 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Hangs up the specified channel. If no channel name is given, hangs up the - * current channel. - * + * AGI Command: HANGUP + *

    + * Hangs up the specified channel. If no channel name is given, hangs up the current channel. + *

    + * See: AGI Command HANGUP (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class HangupCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class HangupCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3904959746380281145L; /** - * The name of the channel to hangup or null for the current - * channel. + * The name of the channel to hangup or null for the current channel. */ private String channel; /** * Creates a new HangupCommand that hangs up the current channel. */ - public HangupCommand() - { + public HangupCommand() { super(); } /** * Creates a new HangupCommand that hangs up the given channel. - * + * * @param channel the name of the channel to hangup. */ - public HangupCommand(String channel) - { + public HangupCommand(String channel) { super(); this.channel = channel; } /** * Returns the name of the channel to hangup. - * - * @return the name of the channel to hangup or null for the - * current channel. + * + * @return the name of the channel to hangup or null for the current channel. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel to hangup. - * - * @param channel the name of the channel to hangup or null - * for the current channel. + * + * @param channel the name of the channel to hangup or null for the current channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @Override - public String buildCommand() - { - return "HANGUP" - + (channel == null ? "" : " " + escapeAndQuote(channel)); + public String buildCommand() { + return "HANGUP" + (channel == null ? "" : " " + escapeAndQuote(channel)); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/MeetmeCommand.java b/src/main/java/org/asteriskjava/fastagi/command/MeetmeCommand.java new file mode 100644 index 000000000..328bde93c --- /dev/null +++ b/src/main/java/org/asteriskjava/fastagi/command/MeetmeCommand.java @@ -0,0 +1,47 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +/** + * This is not a real AGI command. + *

    + * It uses EXEC command and add meetme application features. + *

    + * See: AGI Command EXEC (Asterisk 18)
    + * See: Application MeetMe (Asterisk 18) + */ +public class MeetmeCommand extends AbstractAgiCommand { + private static final long serialVersionUID = 3762248656229053753L; + + private final String room; + private final String options; + + public MeetmeCommand(String room, String options) { + super(); + this.room = room; + this.options = options; + } + + @Override + public String buildCommand() { + String command = "EXEC " + escapeAndQuote("meetme") + " " + escapeAndQuote(room); + if (options != null && options.length() > 0) { + command += "|" + escapeAndQuote(options); + } + + return command; + } +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/NoopCommand.java b/src/main/java/org/asteriskjava/fastagi/command/NoopCommand.java index c6f0f9fb4..f3b3de077 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/NoopCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/NoopCommand.java @@ -1,45 +1,38 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** + * AGI Command: NOOP + *

    * Does nothing. - * + *

    + * See: AGI Command NOOP (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class NoopCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class NoopCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3762248656229053753L; - /** - * Creates a new NoopCommand. - */ - public NoopCommand() - { + public NoopCommand() { super(); } @Override - public String buildCommand() - { + public String buildCommand() { return "NOOP"; } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/QueueCommand.java b/src/main/java/org/asteriskjava/fastagi/command/QueueCommand.java new file mode 100644 index 000000000..8452a8466 --- /dev/null +++ b/src/main/java/org/asteriskjava/fastagi/command/QueueCommand.java @@ -0,0 +1,41 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +/** + * This is not a real AGI command. + *

    + * It uses EXEC command and add queue application features. + *

    + * See: AGI Command EXEC (Asterisk 18)
    + * See: Application Queue (Asterisk 18) + */ +public class QueueCommand extends AbstractAgiCommand { + private static final long serialVersionUID = 3762248656229053753L; + + private final String queue; + + public QueueCommand(String queue) { + super(); + this.queue = queue; + + } + + @Override + public String buildCommand() { + return "EXEC " + escapeAndQuote("queue") + " " + escapeAndQuote(queue); + } +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/ReceiveCharCommand.java b/src/main/java/org/asteriskjava/fastagi/command/ReceiveCharCommand.java index d1c062c44..e26c34c84 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/ReceiveCharCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/ReceiveCharCommand.java @@ -1,37 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Receives a character of text on a channel.

    - * Specify timeout to be the maximum time to wait for input in milliseconds, or - * 0 for infinite.

    - * Most channels do not support the reception of text.

    - * Returns the decimal value of the character if one is received, or 0 if the - * channel does not support text reception. Returns -1 only on error/hangup. - * + * AGI Command: RECEIVE CHAR + *

    + * Receives one character from channels supporting it. + *

    + * See: AGI CommandRECEIVE CHAR (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class ReceiveCharCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class ReceiveCharCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -40,51 +33,43 @@ public class ReceiveCharCommand extends AbstractAgiCommand private int timeout; /** - * Creates a new ReceiveCharCommand with a default timeout of 0 meaning to - * wait for ever. + * Creates a new ReceiveCharCommand with a default timeout of 0 meaning to wait forever. */ - public ReceiveCharCommand() - { + public ReceiveCharCommand() { super(); this.timeout = 0; } /** * Creates a new ReceiveCharCommand. - * - * @param timeout the milliseconds to wait for the channel to receive a - * character. + * + * @param timeout the milliseconds to wait for the channel to receive a character. */ - public ReceiveCharCommand(int timeout) - { + public ReceiveCharCommand(int timeout) { super(); this.timeout = timeout; } /** * Returns the milliseconds to wait for the channel to receive a character. - * + * * @return the milliseconds to wait for the channel to receive a character. */ - public int getTimeout() - { + public int getTimeout() { return timeout; } /** * Sets the milliseconds to wait for the channel to receive a character. - * - * @param timeout the milliseconds to wait for the channel to receive a - * character. + * + * @param timeout the milliseconds to wait for the channel to receive a character. */ - public void setTimeout(int timeout) - { + public void setTimeout(int timeout) { this.timeout = timeout; } @Override - public String buildCommand() - { + public String buildCommand() { return "RECEIVE CHAR " + timeout; } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/ReceiveTextCommand.java b/src/main/java/org/asteriskjava/fastagi/command/ReceiveTextCommand.java index 564d5f11c..3f1454ab4 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/ReceiveTextCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/ReceiveTextCommand.java @@ -1,38 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Receives a string of text on a channel.

    - * Specify timeout to be the maximum time to wait for input in milliseconds, or - * 0 for infinite.

    - * Most channels do not support the reception of text.

    - * Returns -1 for failure or 1 for success, and the string in parentheses.

    - * Available since Asterisk 1.2. - * - * @since 0.2 + * AGI Command: RECEIVE TEXT + *

    + * Receives text from channels supporting it. + *

    + * See: AGI Command RECEIVE TEXT (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class ReceiveTextCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class ReceiveTextCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -41,51 +33,43 @@ public class ReceiveTextCommand extends AbstractAgiCommand private int timeout; /** - * Creates a new ReceiveTextCommand with a default timeout of 0 meaning to - * wait for ever. + * Creates a new ReceiveTextCommand with a default timeout of 0 meaning to wait forever. */ - public ReceiveTextCommand() - { + public ReceiveTextCommand() { super(); this.timeout = 0; } /** * Creates a new ReceiveTextCommand. - * - * @param timeout the milliseconds to wait for the channel to receive the - * text. + * + * @param timeout the milliseconds to wait for the channel to receive the text. */ - public ReceiveTextCommand(int timeout) - { + public ReceiveTextCommand(int timeout) { super(); this.timeout = timeout; } /** * Returns the milliseconds to wait for the channel to receive the text. - * + * * @return the milliseconds to wait for the channel to receive the text. */ - public int getTimeout() - { + public int getTimeout() { return timeout; } /** * Sets the milliseconds to wait for the channel to receive the text. - * - * @param timeout the milliseconds to wait for the channel to receive the - * text. + * + * @param timeout the milliseconds to wait for the channel to receive the text. */ - public void setTimeout(int timeout) - { + public void setTimeout(int timeout) { this.timeout = timeout; } @Override - public String buildCommand() - { + public String buildCommand() { return "RECEIVE TEXT " + timeout; } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/RecordFileCommand.java b/src/main/java/org/asteriskjava/fastagi/command/RecordFileCommand.java index abea85e7d..d4bc84fb4 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/RecordFileCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/RecordFileCommand.java @@ -1,41 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Record to a file until a given dtmf digit in the sequence is received. + * AGI Command: RECORD FILE *

    - * Returns -1 on hangup or error. + * Records to a given file. *

    - * The format will specify what kind of file will be recorded. The timeout is - * the maximum record time in milliseconds, or -1 for no timeout. Offset samples - * is optional, and if provided will seek to the offset without exceeding the - * end of the file. "maxSilence" is the number of seconds of maxSilence allowed - * before the function returns despite the lack of dtmf digits or reaching - * timeout. - * + * See: AGI Command RECORD FILE (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class RecordFileCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class RecordFileCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3978141041352128820L; /** @@ -64,28 +53,24 @@ public class RecordFileCommand extends AbstractAgiCommand private int offset; /** - * Wheather a beep should be played before recording. + * Whether a beep should be played before recording. */ private boolean beep; /** - * The amount of silence (in seconds) to allow before returning despite the - * lack of dtmf digits or reaching timeout. + * The amount of silence (in seconds) to allow before returning despite the lack of dtmf digits or reaching timeout. */ private int maxSilence; /** * Creates a new RecordFileCommand. - * - * @param file the name of the file to stream, must not include extension. - * @param format the format of the file to be recorded, for example "wav". - * @param escapeDigits contains the digits that allow the user to end - * recording. - * @param timeout the maximum record time in milliseconds, or -1 for no - * timeout. + * + * @param file the name of the file to stream, must not include extension. + * @param format the format of the file to be recorded, for example "wav". + * @param escapeDigits contains the digits that allow the user to end recording. + * @param timeout the maximum record time in milliseconds, or -1 for no timeout. */ - public RecordFileCommand(String file, String format, String escapeDigits, int timeout) - { + public RecordFileCommand(String file, String format, String escapeDigits, int timeout) { super(); this.file = file; this.format = format; @@ -98,22 +83,19 @@ public RecordFileCommand(String file, String format, String escapeDigits, int ti /** * Creates a new RecordFileCommand. - * - * @param file the name of the file to stream, must not include extension. - * @param format the format of the file to be recorded, for example "wav". - * @param escapeDigits contains the digits that allow the user to end - * recording. - * @param timeout the maximum record time in milliseconds, or -1 for no - * timeout. - * @param offset the offset samples to skip. - * @param beep true if a beep should be played before - * recording. - * @param maxSilence The amount of silence (in seconds) to allow before - * returning despite the lack of dtmf digits or reaching timeout. - */ - public RecordFileCommand(String file, String format, String escapeDigits, int timeout, int offset, boolean beep, - int maxSilence) - { + * + * @param file the name of the file to stream, must not include extension. + * @param format the format of the file to be recorded, for example "wav". + * @param escapeDigits contains the digits that allow the user to end recording. + * @param timeout the maximum record time in milliseconds, or -1 for no timeout. + * @param offset the offset samples to skip. + * @param beep true if a beep should be played before recording. + * @param maxSilence The amount of silence (in seconds) to allow before + * returning despite the lack of dtmf digits or reaching timeout. + */ + public RecordFileCommand( + String file, String format, String escapeDigits, int timeout, int offset, boolean beep, int maxSilence + ) { super(); this.file = file; this.format = format; @@ -126,155 +108,132 @@ public RecordFileCommand(String file, String format, String escapeDigits, int ti /** * Returns the name of the file to stream. - * + * * @return the name of the file to stream. */ - public String getFile() - { + public String getFile() { return file; } /** * Sets the name of the file to stream. - * + * * @param file the name of the file to stream, must not include extension. */ - public void setFile(String file) - { + public void setFile(String file) { this.file = file; } /** * Returns the format of the file to be recorded, for example "wav". - * + * * @return the format of the file to be recorded, for example "wav". */ - public String getFormat() - { + public String getFormat() { return format; } /** * Sets the format of the file to be recorded, for example "wav". - * + * * @param format the format of the file to be recorded, for example "wav". */ - public void setFormat(String format) - { + public void setFormat(String format) { this.format = format; } /** * Returns the digits that allow the user to end recording. - * + * * @return the digits that allow the user to end recording. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } /** * Sets the digits that allow the user to end recording. - * - * @param escapeDigits the digits that allow the user to end recording or - * null for none. + * + * @param escapeDigits the digits that allow the user to end recording or null for none. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } /** * Returns the maximum record time in milliseconds. - * + * * @return the maximum record time in milliseconds. */ - public int getTimeout() - { + public int getTimeout() { return timeout; } /** * Sets the maximum record time in milliseconds. - * - * @param timeout the maximum record time in milliseconds, or -1 for no - * timeout. + * + * @param timeout the maximum record time in milliseconds, or -1 for no timeout. */ - public void setTimeout(int timeout) - { + public void setTimeout(int timeout) { this.timeout = timeout; } /** * Returns the offset samples to skip. - * + * * @return the offset samples to skip. */ - public int getOffset() - { + public int getOffset() { return offset; } /** * Sets the offset samples to skip. - * + * * @param offset the offset samples to skip. */ - public void setOffset(int offset) - { + public void setOffset(int offset) { this.offset = offset; } /** * Returns true if a beep should be played before recording. - * - * @return true if a beep should be played before recording, - * false if not. + * + * @return true if a beep should be played before recording, false if not. */ - public boolean getBeep() - { + public boolean getBeep() { return beep; } /** * Set to true to play a beep before recording. - * - * @param beep true if a beep should be played before - * recording, false if not. + * + * @param beep true if a beep should be played before recording, false if not. */ - public void setBeep(boolean beep) - { + public void setBeep(boolean beep) { this.beep = beep; } /** - * Returns the amount of silence (in seconds) to allow before returning - * despite the lack of dtmf digits or reaching timeout. - * - * @return the amount of silence (in seconds) to allow before returning - * despite the lack of dtmf digits or reaching timeout. + * Returns the amount of silence (in seconds) to allow before returning despite the lack of dtmf digits or reaching timeout. + * + * @return the amount of silence (in seconds) to allow before returning despite the lack of dtmf digits or reaching timeout. */ - int getMaxSilence() - { + int getMaxSilence() { return maxSilence; } /** - * Sets the amount of silence (in seconds) to allow before returning despite - * the lack of dtmf digits or reaching timeout. - * - * @param maxSilence the amount of silence (in seconds) to allow before - * returning despite the lack of dtmf digits or reaching timeout. + * Sets the amount of silence (in seconds) to allow before returning despite the lack of dtmf digits or reaching timeout. + * + * @param maxSilence the amount of silence (in seconds) to allow before returning despite the lack of dtmf digits or reaching timeout. */ - void setMaxSilence(int maxSilence) - { + void setMaxSilence(int maxSilence) { this.maxSilence = maxSilence; } @Override - public String buildCommand() - { + public String buildCommand() { return "RECORD FILE " + escapeAndQuote(file) + " " + escapeAndQuote(format) + " " + escapeAndQuote(escapeDigits) + " " + timeout + " " + offset + (beep ? " BEEP" : "") + " s=" + maxSilence; } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SayAlphaCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SayAlphaCommand.java index 75e771ffa..efbcb1250 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SayAlphaCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SayAlphaCommand.java @@ -1,35 +1,33 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this text except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** + * AGI Command: SAY ALPHA + *

    * Say a given character string, returning early if any of the - * given DTMF digits are received on the channel.

    + * given DTMF digits are received on the channel.
    * Returns 0 if playback completes without a digit being pressed, or the ASCII * numerical value of the digit if one was pressed or -1 on error/hangup. - * + *

    + * See: AGI Command SAY ALPHA + * * @author srt - * @version $Id$ */ -public class SayAlphaCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SayAlphaCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256721797012404276L; /** @@ -44,24 +42,21 @@ public class SayAlphaCommand extends AbstractAgiCommand /** * Creates a new SayAlphaCommand. - * + * * @param text the text to say. */ - public SayAlphaCommand(String text) - { + public SayAlphaCommand(String text) { super(); this.text = text; } /** * Creates a new SayAlphaCommand. - * - * @param text the text to say. - * @param escapeDigits contains the digits that allow the user to interrupt - * this command. + * + * @param text the text to say. + * @param escapeDigits contains the digits that allow the user to interrupt this command. */ - public SayAlphaCommand(String text, String escapeDigits) - { + public SayAlphaCommand(String text, String escapeDigits) { super(); this.text = text; this.escapeDigits = escapeDigits; @@ -69,49 +64,42 @@ public SayAlphaCommand(String text, String escapeDigits) /** * Returns the text to say. - * + * * @return the text to say. */ - public String getText() - { + public String getText() { return text; } /** * Sets the text to say. - * + * * @param text the text to say. */ - public void setText(String text) - { + public void setText(String text) { this.text = text; } /** * Returns the digits that allow the user to interrupt this command. - * + * * @return the digits that allow the user to interrupt this command. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } /** * Sets the digits that allow the user to interrupt this command. - * - * @param escapeDigits the text that allow the user to interrupt this - * command or null for none. + * + * @param escapeDigits the text that allow the user to interrupt this command or null for none. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } @Override - public String buildCommand() - { - return "SAY ALPHA " + escapeAndQuote(text) + " " - + escapeAndQuote(escapeDigits); + public String buildCommand() { + return "SAY ALPHA " + escapeAndQuote(text) + " " + escapeAndQuote(escapeDigits); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SayDateTimeCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SayDateTimeCommand.java index 3666ea5b5..eaebfb45e 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SayDateTimeCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SayDateTimeCommand.java @@ -1,37 +1,34 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** + * AGI Command: SAY DATETIME + *

    * Say a given time, returning early if any of the given DTMF digits are * pressed.

    * Returns 0 if playback completes without a digit being pressed, or the ASCII * numerical value of the digit if one was pressed or -1 on error/hangup.

    * Available since Asterisk 1.2. - * - * @since 0.2 + *

    + * See: AGI Command SAY DATETIME (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SayDateTimeCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier - */ +public class SayDateTimeCommand extends AbstractAgiCommand { private static final long serialVersionUID = -976344744239948036L; private static final String DEFAULT_FORMAT = "ABdY 'digits/at' IMp"; @@ -43,44 +40,34 @@ public class SayDateTimeCommand extends AbstractAgiCommand /** * Creates a new SayDateTimeCommand that says the given time. - * - * @param time the time to say in seconds elapsed since 00:00:00 on January - * 1, 1970, Coordinated Universal Time (UTC) + * + * @param time the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC) */ - public SayDateTimeCommand(long time) - { + public SayDateTimeCommand(long time) { super(); this.time = time; } /** - * Creates a new SayDateTimeCommand that says the given time and allows - * interruption by one of the given escape digits. - * - * @param time the time to say in seconds elapsed since 00:00:00 on January - * 1, 1970, Coordinated Universal Time (UTC) - * @param escapeDigits the digits that allow the user to interrupt this - * command or null for none. + * Creates a new SayDateTimeCommand that says the given time and allows interruption by one of the given escape digits. + * + * @param time the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC) + * @param escapeDigits the digits that allow the user to interrupt this command or null for none. */ - public SayDateTimeCommand(long time, String escapeDigits) - { + public SayDateTimeCommand(long time, String escapeDigits) { super(); this.time = time; this.escapeDigits = escapeDigits; } /** - * Creates a new SayDateTimeCommand that says the given time in the given - * format and allows interruption by one of the given escape digits. - * - * @param time the time to say in seconds elapsed since 00:00:00 on January - * 1, 1970, Coordinated Universal Time (UTC) - * @param escapeDigits the digits that allow the user to interrupt this - * command or null for none. - * @param format the format the time should be said in + * Creates a new SayDateTimeCommand that says the given time in the given format and allows interruption by one of the given escape digits. + * + * @param time the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC) + * @param escapeDigits the digits that allow the user to interrupt this command or null for none. + * @param format the format the time should be said in */ - public SayDateTimeCommand(long time, String escapeDigits, String format) - { + public SayDateTimeCommand(long time, String escapeDigits, String format) { super(); this.time = time; this.escapeDigits = escapeDigits; @@ -88,21 +75,15 @@ public SayDateTimeCommand(long time, String escapeDigits, String format) } /** - * Creates a new SayDateTimeCommand that says the given time in the given - * format and timezone and allows interruption by one of the given escape - * digits. - * - * @param time the time to say in seconds elapsed since 00:00:00 on January - * 1, 1970, Coordinated Universal Time (UTC) - * @param escapeDigits the digits that allow the user to interrupt this - * command or null for none. - * @param format the format the time should be said in - * @param timezone the timezone to use when saying the time, for example - * "UTC" or "Europe/Berlin". + * Creates a new SayDateTimeCommand that says the given time in the given format and timezone and allows interruption by one of the given escape digits. + * + * @param time the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC) + * @param escapeDigits the digits that allow the user to interrupt this command or null for none. + * @param format the format the time should be said in + * @param timezone the timezone to use when saying the time, for example "UTC" or "Europe/Berlin". */ public SayDateTimeCommand(long time, String escapeDigits, String format, - String timezone) - { + String timezone) { super(); this.time = time; this.escapeDigits = escapeDigits; @@ -111,58 +92,48 @@ public SayDateTimeCommand(long time, String escapeDigits, String format, } /** - * Returns the time to say in seconds elapsed since 00:00:00 on January 1, - * 1970, Coordinated Universal Time (UTC). - * - * @return the time to say in seconds elapsed since 00:00:00 on January 1, - * 1970, Coordinated Universal Time (UTC) + * Returns the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC). + * + * @return the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC) */ - public long getTime() - { + public long getTime() { return time; } /** - * Returns the time to say in seconds elapsed since 00:00:00 on January 1, - * 1970, Coordinated Universal Time (UTC).

    + * Returns the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC).

    * This property is mandatory. - * - * @param time the time to say in seconds elapsed since 00:00:00 on January - * 1, 1970, Coordinated Universal Time (UTC) + * + * @param time the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC) */ - public void setTime(long time) - { + public void setTime(long time) { this.time = time; } /** * Returns the digits that allow the user to interrupt this command. - * + * * @return the digits that allow the user to interrupt this command. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } /** * Sets the digits that allow the user to interrupt this command. - * - * @param escapeDigits the digits that allow the user to interrupt this - * command or null for none. + * + * @param escapeDigits the digits that allow the user to interrupt this command or null for none. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } /** * Returns the format the time should be said in. - * + * * @return the format the time should be said in */ - public String getFormat() - { + public String getFormat() { return format; } @@ -170,21 +141,19 @@ public String getFormat() * Sets the format the time should be said in.

    * See voicemail.conf.

    * Defaults to "ABdY 'digits/at' IMp". - * + * * @param format the format the time should be said in */ - public void setFormat(String format) - { + public void setFormat(String format) { this.format = format; } /** * Returns the timezone to use when saying the time. - * + * * @return the timezone to use when saying the time. */ - public String getTimezone() - { + public String getTimezone() { return timezone; } @@ -193,38 +162,32 @@ public String getTimezone() * A list of available timezones is available in * /usr/share/zoneinfo on your Asterisk server.

    * Defaults to machine default. - * - * @param timezone the timezone to use when saying the time, for example - * "UTC" or "Europe/Berlin". + * + * @param timezone the timezone to use when saying the time, for example "UTC" or "Europe/Berlin". */ - public void setTimezone(String timezone) - { + public void setTimezone(String timezone) { this.timezone = timezone; } @Override - public String buildCommand() - { - StringBuffer sb; + public String buildCommand() { + StringBuilder sb; - sb = new StringBuffer("SAY DATETIME "); + sb = new StringBuilder("SAY DATETIME "); sb.append(time); sb.append(" "); sb.append(escapeAndQuote(escapeDigits)); - if (format == null && timezone != null) - { + if (format == null && timezone != null) { sb.append(" "); sb.append(escapeAndQuote(DEFAULT_FORMAT)); } - if (format != null) - { + if (format != null) { sb.append(" "); sb.append(escapeAndQuote(format)); } - if (timezone != null) - { + if (timezone != null) { sb.append(" "); sb.append(escapeAndQuote(timezone)); } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SayDigitsCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SayDigitsCommand.java index e5b13c687..e08277da2 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SayDigitsCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SayDigitsCommand.java @@ -1,35 +1,32 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this digits except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Say a given digit string, returning early if any of the given DTMF digits are - * received on the channel.

    - * Returns 0 if playback completes without a digit being pressed, or the ASCII - * numerical value of the digit if one was pressed or -1 on error/hangup. - * + * AGI Command: SAY DIGIT + *

    + * Say a given digit string, returning early if any of the given DTMF digits are received on the channel.
    + * Returns 0 if playback completes without a digit being pressed, or the ASCII numerical value of the digit if one was + * pressed or -1 on error/hangup. + *

    + * See: AGI Command SAY DIGIT (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SayDigitsCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SayDigitsCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3907207173934101552L; /** @@ -38,31 +35,27 @@ public class SayDigitsCommand extends AbstractAgiCommand private String digits; /** - * When one of these digits is pressed while saying the digits the command - * returns. + * When one of these digits is pressed while saying the digits the command returns. */ private String escapeDigits; /** * Creates a new SayDigitsCommand. - * + * * @param digits the digits to say. */ - public SayDigitsCommand(String digits) - { + public SayDigitsCommand(String digits) { super(); this.digits = digits; } /** * Creates a new SayDigitsCommand. - * - * @param digits the digits to say. - * @param escapeDigits the digits that allow the user to interrupt this - * command. + * + * @param digits the digits to say. + * @param escapeDigits the digits that allow the user to interrupt this command. */ - public SayDigitsCommand(String digits, String escapeDigits) - { + public SayDigitsCommand(String digits, String escapeDigits) { super(); this.digits = digits; this.escapeDigits = escapeDigits; @@ -70,49 +63,42 @@ public SayDigitsCommand(String digits, String escapeDigits) /** * Returns the digits string to say. - * + * * @return the digits string to say. */ - public String getDigits() - { + public String getDigits() { return digits; } /** * Sets the digits to say. - * + * * @param digits the digits string to say. */ - public void setDigits(String digits) - { + public void setDigits(String digits) { this.digits = digits; } /** * Returns the digits that allow the user to interrupt this command. - * + * * @return the digits that allow the user to interrupt this command. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } /** * Sets the digits that allow the user to interrupt this command. - * - * @param escapeDigits the digits that allow the user to interrupt this - * command or null for none. + * + * @param escapeDigits the digits that allow the user to interrupt this command or null for none. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } @Override - public String buildCommand() - { - return "SAY DIGITS " + escapeAndQuote(digits) + " " - + escapeAndQuote(escapeDigits); + public String buildCommand() { + return "SAY DIGITS " + escapeAndQuote(digits) + " " + escapeAndQuote(escapeDigits); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SayNumberCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SayNumberCommand.java index 37933303e..488ee21b9 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SayNumberCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SayNumberCommand.java @@ -1,35 +1,32 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this number except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Say a given number, returning early if any of the given DTMF number are - * received on the channel.

    - * Returns 0 if playback completes without a digit being pressed, or the ASCII - * numerical value of the digit if one was pressed or -1 on error/hangup. - * + * AGI Command: SAY NUMBER + *

    + * Say a given number, returning early if any of the given DTMF number are received on the channel.
    + * Returns 0 if playback completes without a digit being pressed, or the ASCII numerical value of the digit if one was + * pressed or -1 on error/hangup. + *

    + * See: AGI Command SAY NUMBER (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SayNumberCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SayNumberCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3833744404153644087L; /** @@ -44,24 +41,21 @@ public class SayNumberCommand extends AbstractAgiCommand /** * Creates a new SayNumberCommand. - * + * * @param number the number to say. */ - public SayNumberCommand(String number) - { + public SayNumberCommand(String number) { super(); this.number = number; } /** * Creates a new SayNumberCommand. - * - * @param number the number to say. - * @param escapeDigits contains the number that allow the user to - * interrupt this command. + * + * @param number the number to say. + * @param escapeDigits contains the number that allow the user to interrupt this command. */ - public SayNumberCommand(String number, String escapeDigits) - { + public SayNumberCommand(String number, String escapeDigits) { super(); this.number = number; this.escapeDigits = escapeDigits; @@ -69,49 +63,42 @@ public SayNumberCommand(String number, String escapeDigits) /** * Returns the number to say. - * + * * @return the number to say. */ - public String getNumber() - { + public String getNumber() { return number; } /** * Sets the number to say. - * + * * @param number the number to say. */ - public void setNumber(String number) - { + public void setNumber(String number) { this.number = number; } /** * Returns the number that allow the user to interrupt this command. - * + * * @return the number that allow the user to interrupt this command. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } /** * Sets the number that allow the user to interrupt this command. - * - * @param escapeDigits the number that allow the user to interrupt this - * command or null for none. + * + * @param escapeDigits the number that allow the user to interrupt this command or null for none. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } @Override - public String buildCommand() - { - return "SAY NUMBER " + escapeAndQuote(number) + " " - + escapeAndQuote(escapeDigits); + public String buildCommand() { + return "SAY NUMBER " + escapeAndQuote(number) + " " + escapeAndQuote(escapeDigits); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SayPhoneticCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SayPhoneticCommand.java index 933b834d1..46d26b3b5 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SayPhoneticCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SayPhoneticCommand.java @@ -1,35 +1,31 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this text except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Say a given character string with phonetics, returning early if any of the - * given DTMF digits are received on the channel.

    - * Returns 0 if playback completes without a digit being pressed, or the ASCII - * numerical value of the digit if one was pressed or -1 on error/hangup. - * + * AGI Command: SAY PHONETIC + *

    + * Say a given character string with phonetics, returning early if any of the given DTMF digits are received on the channel.
    + * Returns 0 if playback completes without a digit being pressed, or the ASCII numerical value of the digit if one was pressed or -1 on error/hangup. + *

    + * See: AGI Command SAY PHONETIC (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SayPhoneticCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SayPhoneticCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256721797012404276L; /** @@ -43,25 +39,22 @@ public class SayPhoneticCommand extends AbstractAgiCommand private String escapeDigits; /** - * Creates a new SayPhonticCommand. - * + * Creates a new SayPhoneticCommand. + * * @param text the text to say. */ - public SayPhoneticCommand(String text) - { + public SayPhoneticCommand(String text) { super(); this.text = text; } /** * Creates a new SayPhoneticCommand. - * - * @param text the text to say. - * @param escapeDigits contains the digits that allow the user to interrupt - * this command. + * + * @param text the text to say. + * @param escapeDigits contains the digits that allow the user to interrupt this command. */ - public SayPhoneticCommand(String text, String escapeDigits) - { + public SayPhoneticCommand(String text, String escapeDigits) { super(); this.text = text; this.escapeDigits = escapeDigits; @@ -69,49 +62,42 @@ public SayPhoneticCommand(String text, String escapeDigits) /** * Returns the text to say. - * + * * @return the text to say. */ - public String getText() - { + public String getText() { return text; } /** * Sets the text to say. - * + * * @param text the text to say. */ - public void setText(String text) - { + public void setText(String text) { this.text = text; } /** * Returns the digits that allow the user to interrupt this command. - * + * * @return the digits that allow the user to interrupt this command. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } /** * Sets the digits that allow the user to interrupt this command. - * - * @param escapeDigits the text that allow the user to interrupt this - * command or null for none. + * + * @param escapeDigits the text that allow the user to interrupt this command or null for none. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } @Override - public String buildCommand() - { - return "SAY PHONETIC " + escapeAndQuote(text) + " " - + escapeAndQuote(escapeDigits); + public String buildCommand() { + return "SAY PHONETIC " + escapeAndQuote(text) + " " + escapeAndQuote(escapeDigits); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SayTimeCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SayTimeCommand.java index 9285e2f0b..d25bec8c5 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SayTimeCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SayTimeCommand.java @@ -1,37 +1,32 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this time except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Say a given time, returning early if any of the given DTMF digits are - * received on the channel.

    - * Time is the number of seconds elapsed since 00:00:00 on January 1, 1970, - * Coordinated Universal Time (UTC).

    - * Returns 0 if playback completes without a digit being pressed, or the ASCII - * numerical value of the digit if one was pressed or -1 on error/hangup. - * + * AGI Command: SAY TIME + *

    + * Say a given time, returning early if any of the given DTMF digits are received on the channel.
    + * Time is the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC).
    + * Returns 0 if playback completes without a digit being pressed, or the ASCII numerical value of the digit if one was pressed or -1 on error/hangup. + *

    + * See: AGI Command SAY TIME (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SayTimeCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SayTimeCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256721797012404276L; /** @@ -46,24 +41,21 @@ public class SayTimeCommand extends AbstractAgiCommand /** * Creates a new SayTimeCommand. - * + * * @param time the time to say in seconds since 00:00:00 on January 1, 1970. */ - public SayTimeCommand(long time) - { + public SayTimeCommand(long time) { super(); this.time = time; } /** * Creates a new SayTimeCommand. - * - * @param time the time to say in seconds since 00:00:00 on January 1, 1970. - * @param escapeDigits contains the digits that allow the user to interrupt - * this command. + * + * @param time the time to say in seconds since 00:00:00 on January 1, 1970. + * @param escapeDigits contains the digits that allow the user to interrupt this command. */ - public SayTimeCommand(long time, String escapeDigits) - { + public SayTimeCommand(long time, String escapeDigits) { super(); this.time = time; this.escapeDigits = escapeDigits; @@ -71,48 +63,42 @@ public SayTimeCommand(long time, String escapeDigits) /** * Returns the time to say in seconds since 00:00:00 on January 1, 1970. - * + * * @return the time to say in seconds since 00:00:00 on January 1, 1970. */ - public long getTime() - { + public long getTime() { return time; } /** * Sets the time to say in seconds since 00:00:00 on January 1, 1970. - * + * * @param time the time to say in seconds since 00:00:00 on January 1, 1970. */ - public void setTime(long time) - { + public void setTime(long time) { this.time = time; } /** * Returns the digits that allow the user to interrupt this command. - * + * * @return the digits that allow the user to interrupt this command. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } /** * Sets the digits that allow the user to interrupt this command. - * - * @param escapeDigits the time that allow the user to interrupt this - * command or null for none. + * + * @param escapeDigits the time that allow the user to interrupt this command or null for none. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } @Override - public String buildCommand() - { + public String buildCommand() { return "SAY TIME " + time + " " + escapeAndQuote(escapeDigits); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SendImageCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SendImageCommand.java index 0cc5c2949..a747298dc 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SendImageCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SendImageCommand.java @@ -1,36 +1,33 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Sends the given image on a channel.

    - * Most channels do not support the transmission of images.

    - * Returns 0 if image is sent, or if the channel does not support image - * transmission. Returns -1 only on error/hangup.

    + * AGI Command: SEND IMAGE + *

    + * Sends the given image on a channel.
    + * Most channels do not support the transmission of images.
    + * Returns 0 if image is sent, or if the channel does not support image transmission. Returns -1 only on error/hangup.
    * Image names should not include extensions. - * + *

    + * See: AGI Command SEND IMAGE (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SendImageCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SendImageCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3904959746380281145L; /** @@ -40,38 +37,34 @@ public class SendImageCommand extends AbstractAgiCommand /** * Creates a new SendImageCommand. - * + * * @param image the image to send, should not include extension. */ - public SendImageCommand(String image) - { + public SendImageCommand(String image) { super(); this.image = image; } /** * Returns the image to send. - * + * * @return the image to send. */ - public String getImage() - { + public String getImage() { return image; } /** * Sets the image to send. - * + * * @param image the image to send, should not include extension. */ - public void setImage(String image) - { + public void setImage(String image) { this.image = image; } @Override - public String buildCommand() - { + public String buildCommand() { return "SEND IMAGE " + escapeAndQuote(image); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SendTextCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SendTextCommand.java index 237cd445e..fe0d468d8 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SendTextCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SendTextCommand.java @@ -1,35 +1,32 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** + * AGI Command: SEND TEXT + *

    * Sends the given text on a channel.

    * Most channels do not support the transmission of text.

    - * Returns 0 if text is sent, or if the channel does not support text - * transmission. Returns -1 only on error/hangup. - * + * Returns 0 if text is sent, or if the channel does not support text transmission. Returns -1 only on error/hangup. + *

    + * See: AGI Command SEND TEXT (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SendTextCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SendTextCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3904959746380281145L; /** @@ -39,38 +36,34 @@ public class SendTextCommand extends AbstractAgiCommand /** * Creates a new SendTextCommand. - * + * * @param text the text to send. */ - public SendTextCommand(String text) - { + public SendTextCommand(String text) { super(); this.text = text; } /** * Returns the text to send. - * + * * @return the text to send. */ - public String getText() - { + public String getText() { return text; } /** * Sets the text to send. - * + * * @param text the text to send. */ - public void setText(String text) - { + public void setText(String text) { this.text = text; } @Override - public String buildCommand() - { + public String buildCommand() { return "SEND TEXT " + escapeAndQuote(text); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SetAutoHangupCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SetAutoHangupCommand.java index e1e806340..05e3586ba 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SetAutoHangupCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SetAutoHangupCommand.java @@ -1,35 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Cause the channel to automatically hangup at the given number of seconds in - * the future.

    - * Of course it can be hungup before then as well. Setting to 0 will cause the - * autohangup feature to be disabled on this channel. - * + * AGI Command: SET AUTOHANGUP + *

    + * Autohangup channel in some time. + *

    + * See: AGI Command SET AUTOHANGUP (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SetAutoHangupCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SetAutoHangupCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3257562923458443314L; /** @@ -39,44 +34,36 @@ public class SetAutoHangupCommand extends AbstractAgiCommand /** * Creates a new SetAutoHangupCommand. - * - * @param time the number of seconds before this channel is automatically - * hung up.

    - * 0 disables the autohangup feature. + * + * @param time the number of seconds before this channel is automatically hung up.

    + * 0 disables the autohangup feature. */ - public SetAutoHangupCommand(int time) - { + public SetAutoHangupCommand(int time) { super(); this.time = time; } /** - * Returns the number of seconds before this channel is automatically hung - * up. - * - * @return the number of seconds before this channel is automatically hung - * up. + * Returns the number of seconds before this channel is automatically hung up. + * + * @return the number of seconds before this channel is automatically hung up. */ - public int getTime() - { + public int getTime() { return time; } /** * Sets the number of seconds before this channel is automatically hung up. - * - * @param time the number of seconds before this channel is automatically - * hung up.

    - * 0 disables the autohangup feature. + * + * @param time the number of seconds before this channel is automatically hung up.

    + * 0 disables the autohangup feature. */ - public void setTime(int time) - { + public void setTime(int time) { this.time = time; } @Override - public String buildCommand() - { + public String buildCommand() { return "SET AUTOHANGUP " + time; } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SetCallerIdCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SetCallerIdCommand.java index a78f087d1..b980232f0 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SetCallerIdCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SetCallerIdCommand.java @@ -1,32 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this time except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Changes the callerid of the current channel. - * + * AGI Command: SET CALLERID + *

    + * Sets callerid for the current channel. + *

    + * See: AGI Command SET CALLERID (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SetCallerIdCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SetCallerIdCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256721797012404276L; /** @@ -36,38 +34,34 @@ public class SetCallerIdCommand extends AbstractAgiCommand /** * Creates a new SetCallerIdCommand. - * + * * @param callerId the new callerId. */ - public SetCallerIdCommand(String callerId) - { + public SetCallerIdCommand(String callerId) { super(); this.callerId = callerId; } /** * Returns the new callerId. - * + * * @return the new callerId. */ - public String getCallerId() - { + public String getCallerId() { return callerId; } /** * Sets the new callerId. - * + * * @param callerId the new callerId. */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } @Override - public String buildCommand() - { + public String buildCommand() { return "SET CALLERID " + escapeAndQuote(callerId); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SetContextCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SetContextCommand.java index e2fc923b7..045919a3a 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SetContextCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SetContextCommand.java @@ -1,32 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Sets the context for continuation upon exiting the application. - * + * AGI Command: SET CONTEXT + *

    + * Sets channel context. + *

    + * See: AGI Command SET CONTEXT (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SetContextCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SetContextCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -36,38 +34,34 @@ public class SetContextCommand extends AbstractAgiCommand /** * Creates a new SetPriorityCommand. - * + * * @param context the context for continuation upon exiting the application. */ - public SetContextCommand(String context) - { + public SetContextCommand(String context) { super(); this.context = context; } /** * Returns the context for continuation upon exiting the application. - * + * * @return the context for continuation upon exiting the application. */ - public String getContext() - { + public String getContext() { return context; } /** * Sets the context for continuation upon exiting the application. - * + * * @param context the context for continuation upon exiting the application. */ - public void setContext(String context) - { + public void setContext(String context) { this.context = context; } @Override - public String buildCommand() - { + public String buildCommand() { return "SET CONTEXT " + escapeAndQuote(context); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SetExtensionCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SetExtensionCommand.java index ef6ec34ae..8e13a1a99 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SetExtensionCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SetExtensionCommand.java @@ -1,32 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Sets the extension for continuation upon exiting the application. - * + * AGI Command: SET EXTENSION + *

    + * Changes channel extension. + *

    + * See: AGI Command SET EXTENSION (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SetExtensionCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SetExtensionCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -36,40 +34,34 @@ public class SetExtensionCommand extends AbstractAgiCommand /** * Creates a new SetPriorityCommand. - * - * @param extension the extension for continuation upon exiting the - * application. + * + * @param extension the extension for continuation upon exiting the application. */ - public SetExtensionCommand(String extension) - { + public SetExtensionCommand(String extension) { super(); this.extension = extension; } /** * Returns the extension for continuation upon exiting the application. - * + * * @return the extension for continuation upon exiting the application. */ - public String getExtension() - { + public String getExtension() { return extension; } /** * Sets the extension for continuation upon exiting the application. - * - * @param extension the extension for continuation upon exiting the - * application. + * + * @param extension the extension for continuation upon exiting the application. */ - public void setExtension(String extension) - { + public void setExtension(String extension) { this.extension = extension; } @Override - public String buildCommand() - { + public String buildCommand() { return "SET EXTENSION " + escapeAndQuote(extension); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SetMusicOffCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SetMusicOffCommand.java index e4770aee1..cb5ee37c7 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SetMusicOffCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SetMusicOffCommand.java @@ -1,46 +1,41 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Turns off music on hold on the current channel.

    - * Always returns 0. - * + * AGI Command: SET MUSIC + *

    + * Disable Music on hold generator. + *

    + * See: AGI Command SET MUSIC (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SetMusicOffCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SetMusicOffCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3762248656229053753L; /** * Creates a new SetMusicOffCommand. */ - public SetMusicOffCommand() - { + public SetMusicOffCommand() { super(); } @Override - public String buildCommand() - { + public String buildCommand() { return "SET MUSIC OFF"; } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SetMusicOnCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SetMusicOnCommand.java index 0c38dac41..e2064320c 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SetMusicOnCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SetMusicOnCommand.java @@ -1,33 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Turns on music on hold on the current channel.

    - * Always returns 0. - * + * AGI Command: SET MUSIC + *

    + * Enable Music on hold generator. + *

    + * See: AGI Command SET MUSIC (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SetMusicOnCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SetMusicOnCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3762248656229053753L; /** @@ -36,52 +33,42 @@ public class SetMusicOnCommand extends AbstractAgiCommand private String musicOnHoldClass; /** - * Creates a new SetMusicOnCommand playing music from the default music on - * hold class. + * Creates a new SetMusicOnCommand playing music from the default music on hold class. */ - public SetMusicOnCommand() - { + public SetMusicOnCommand() { super(); } /** - * Creates a new SetMusicOnCommand playing music from the default music on - * hold class. - * + * Creates a new SetMusicOnCommand playing music from the default music on hold class. + * * @param musicOnHoldClass the music on hold class to play music from. */ - public SetMusicOnCommand(String musicOnHoldClass) - { + public SetMusicOnCommand(String musicOnHoldClass) { this.musicOnHoldClass = musicOnHoldClass; } /** * Returns the music on hold class to play music from. - * + * * @return the music on hold class to play music from or null - * for the default class. + * for the default class. */ - public String getMusicOnHoldClass() - { + public String getMusicOnHoldClass() { return musicOnHoldClass; } /** * Sets the music on hold class to play music from. - * - * @param musicOnHoldClass the music on hold class to play music from or - * null for the default class. + * + * @param musicOnHoldClass the music on hold class to play music from or null for the default class. */ - public void setMusicOnHoldClass(String musicOnHoldClass) - { + public void setMusicOnHoldClass(String musicOnHoldClass) { this.musicOnHoldClass = musicOnHoldClass; } @Override - public String buildCommand() - { - return "SET MUSIC ON" - + (musicOnHoldClass == null ? "" : " " - + escapeAndQuote(musicOnHoldClass)); + public String buildCommand() { + return "SET MUSIC ON" + (musicOnHoldClass == null ? "" : " " + escapeAndQuote(musicOnHoldClass)); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SetPriorityCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SetPriorityCommand.java index 402124425..24ebeeb2a 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SetPriorityCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SetPriorityCommand.java @@ -1,33 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Sets the priority for continuation upon exiting the application.

    - * Since Asterisk 1.2 SetPriorityCommand also supports labels. - * + * AGI Command: SET PRIORITY + *

    + * Set channel dialplan priority. + *

    + * See: AGI Command SET PRIORITY (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SetPriorityCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SetPriorityCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -37,40 +34,34 @@ public class SetPriorityCommand extends AbstractAgiCommand /** * Creates a new SetPriorityCommand. - * - * @param priority the priority or label for continuation upon exiting the - * application. + * + * @param priority the priority or label for continuation upon exiting the application. */ - public SetPriorityCommand(String priority) - { + public SetPriorityCommand(String priority) { super(); this.priority = priority; } /** * Returns the priority or label for continuation upon exiting the application. - * + * * @return the priority or label for continuation upon exiting the application. */ - public String getPriority() - { + public String getPriority() { return priority; } /** * Sets the priority or label for continuation upon exiting the application. - * - * @param priority the priority or label for continuation upon exiting the - * application. + * + * @param priority the priority or label for continuation upon exiting the application. */ - public void setPriority(String priority) - { + public void setPriority(String priority) { this.priority = priority; } @Override - public String buildCommand() - { + public String buildCommand() { return "SET PRIORITY " + escapeAndQuote(priority); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SetVariableCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SetVariableCommand.java index 5c93d97e8..db9ee980b 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SetVariableCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SetVariableCommand.java @@ -1,32 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Sets the given channel varible to the given value. - * + * AGI Command: SET VARIABLE + *

    + * Sets a channel variable. + *

    + * See: AGI Command SET VARIABLE (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class SetVariableCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SetVariableCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -41,12 +39,11 @@ public class SetVariableCommand extends AbstractAgiCommand /** * Creates a new GetVariableCommand. - * + * * @param variable the name of the variable to set. - * @param value the value to set. + * @param value the value to set. */ - public SetVariableCommand(String variable, String value) - { + public SetVariableCommand(String variable, String value) { super(); this.variable = variable; this.value = value; @@ -54,48 +51,42 @@ public SetVariableCommand(String variable, String value) /** * Returns the name of the variable to set. - * - * @return the the name of the variable to set. + * + * @return the name of the variable to set. */ - public String getVariable() - { + public String getVariable() { return variable; } /** * Sets the name of the variable to set. - * + * * @param variable the name of the variable to set. */ - public void setVariable(String variable) - { + public void setVariable(String variable) { this.variable = variable; } /** * Returns the value to set. - * + * * @return the value to set. */ - public String getValue() - { + public String getValue() { return value; } /** * Sets the value to set. - * + * * @param value the value to set. */ - public void setValue(String value) - { + public void setValue(String value) { this.value = value; } @Override - public String buildCommand() - { - return "SET VARIABLE " + escapeAndQuote(variable) + " " - + escapeAndQuote(value); + public String buildCommand() { + return "SET VARIABLE " + escapeAndQuote(variable) + " " + escapeAndQuote(value); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/SpeechActivateGrammarCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SpeechActivateGrammarCommand.java index be3cffccf..e8c56d9c4 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SpeechActivateGrammarCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SpeechActivateGrammarCommand.java @@ -1,46 +1,43 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Activates the specified grammar.

    - * Available since Asterisk 1.6. + * AGI Command: SPEECH ACTIVATE GRAMMAR + *

    + * Activates a grammar. + *

    + * See: AGI Command SPEECH ACTIVATE GRAMMAR (Asterisk 18) * * @author srt - * @version $Id$ * @see org.asteriskjava.fastagi.command.SpeechLoadGrammarCommand * @see org.asteriskjava.fastagi.command.SpeechDeactivateGrammarCommand * @since 1.0.0 */ -public class SpeechActivateGrammarCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SpeechActivateGrammarCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; + private String name; /** - * Creates a new SpeechActivateGrammarCommand that acitvates the given grammer. + * Creates a new SpeechActivateGrammarCommand that activates the given grammar. * * @param name the name of the grammar. */ - public SpeechActivateGrammarCommand(String name) - { + public SpeechActivateGrammarCommand(String name) { this.name = name; } @@ -49,8 +46,7 @@ public SpeechActivateGrammarCommand(String name) * * @return the name of the grammar. */ - public String getName() - { + public String getName() { return name; } @@ -59,14 +55,12 @@ public String getName() * * @param name the name of the grammar. */ - public void setName(String name) - { + public void setName(String name) { this.name = name; } @Override - public String buildCommand() - { + public String buildCommand() { return "SPEECH ACTIVATE GRAMMAR " + escapeAndQuote(name); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/SpeechCreateCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SpeechCreateCommand.java index 5ce0f0064..5f504be2f 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SpeechCreateCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SpeechCreateCommand.java @@ -1,37 +1,35 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Creates a speech object to be used by the other Speech AGI commands.

    - * Available since Asterisk 1.6. + * AGI Command: SPEECH CREATE + *

    + * Creates a speech object. + *

    + * See: AGI Command SPEECH CREATE (Asterisk 18) * * @author srt - * @version $Id$ - * @since 1.0.0 * @see org.asteriskjava.fastagi.command.SpeechDestroyCommand * @see org.asteriskjava.fastagi.command.SpeechLoadGrammarCommand + * @since 1.0.0 */ -public class SpeechCreateCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SpeechCreateCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; + private String engine; /** @@ -39,8 +37,7 @@ public class SpeechCreateCommand extends AbstractAgiCommand * * @param engine the name of the speech engine to use for subsequent Speech AGI commands. */ - public SpeechCreateCommand(String engine) - { + public SpeechCreateCommand(String engine) { this.engine = engine; } @@ -49,8 +46,7 @@ public SpeechCreateCommand(String engine) * * @return the name of the speech engine to use for subsequent Speech AGI commands. */ - public String getEngine() - { + public String getEngine() { return engine; } @@ -59,14 +55,12 @@ public String getEngine() * * @param engine the name of the speech engine to use for subsequent Speech AGI commands. */ - public void setEngine(String engine) - { + public void setEngine(String engine) { this.engine = engine; } @Override - public String buildCommand() - { + public String buildCommand() { return "SPEECH CREATE " + escapeAndQuote(engine); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/SpeechDeactivateGrammarCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SpeechDeactivateGrammarCommand.java index 48106db35..9d9f3f716 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SpeechDeactivateGrammarCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SpeechDeactivateGrammarCommand.java @@ -1,45 +1,42 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Deactivates the specified grammar.

    - * Available since Asterisk 1.6. + * AGI Command: SPEECH DEACTIVATE GRAMMAR + *

    + * Deactivates a grammar. + *

    + * See: AGI Command SPEECH DEACTIVATE GRAMMAR (Asterisk 18) * * @author srt - * @version $Id$ * @see org.asteriskjava.fastagi.command.SpeechActivateGrammarCommand * @since 1.0.0 */ -public class SpeechDeactivateGrammarCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SpeechDeactivateGrammarCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; + private String name; /** - * Creates a new SpeechDeactivateGrammarCommand that deacitvates the given grammer. + * Creates a new SpeechDeactivateGrammarCommand that deactivates the given grammar. * * @param name the name of the grammar. */ - public SpeechDeactivateGrammarCommand(String name) - { + public SpeechDeactivateGrammarCommand(String name) { this.name = name; } @@ -48,8 +45,7 @@ public SpeechDeactivateGrammarCommand(String name) * * @return the name of the grammar. */ - public String getName() - { + public String getName() { return name; } @@ -58,14 +54,12 @@ public String getName() * * @param name the name of the grammar. */ - public void setName(String name) - { + public void setName(String name) { this.name = name; } @Override - public String buildCommand() - { + public String buildCommand() { return "SPEECH DEACTIVATE GRAMMAR " + escapeAndQuote(name); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/SpeechDestroyCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SpeechDestroyCommand.java index 67ef745c7..f4232b5ff 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SpeechDestroyCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SpeechDestroyCommand.java @@ -1,48 +1,43 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Destroys a speech object previously created by a {@link SpeechCreateCommand}.

    - * Available since Asterisk 1.6. + * AGI Command: SPEECH DESTROY + *

    + * Destroys a speech object. + *

    + * See: AGI Command SPEECH DESTROY (Asterisk 18) * * @author srt - * @version $Id$ - * @since 1.0.0 * @see org.asteriskjava.fastagi.command.SpeechCreateCommand + * @since 1.0.0 */ -public class SpeechDestroyCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SpeechDestroyCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; /** * Creates a new empty SpeechDestroyCommand. */ - public SpeechDestroyCommand() - { + public SpeechDestroyCommand() { super(); } @Override - public String buildCommand() - { + public String buildCommand() { return "SPEECH DESTROY"; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/SpeechLoadGrammarCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SpeechLoadGrammarCommand.java index 177020e8f..d044464a0 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SpeechLoadGrammarCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SpeechLoadGrammarCommand.java @@ -1,49 +1,46 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Loads the specified grammar as the specified name.

    - * Available since Asterisk 1.6. + * AGI Command: SPEECH LOAD GRAMMAR + *

    + * Loads a grammar. + *

    + * See: AGI Command SPEECH LOAD GRAMMAR (Asterisk 18) * * @author srt - * @version $Id$ * @see org.asteriskjava.fastagi.command.SpeechUnloadGrammarCommand * @see org.asteriskjava.fastagi.command.SpeechActivateGrammarCommand * @since 1.0.0 */ -public class SpeechLoadGrammarCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SpeechLoadGrammarCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; + private String name; private String path; /** - * Creates a new SpeechLoadGrammarCommand that loads the grammer from the given path and + * Creates a new SpeechLoadGrammarCommand that loads the grammar from the given path and * makes it available under the given name. * - * @param name the name of the grammar, used to activate the gammer later. + * @param name the name of the grammar, used to activate the grammar later. * @param path the path to the grammar. */ - public SpeechLoadGrammarCommand(String name, String path) - { + public SpeechLoadGrammarCommand(String name, String path) { this.name = name; this.path = path; } @@ -53,18 +50,16 @@ public SpeechLoadGrammarCommand(String name, String path) * * @return the name of the grammar. */ - public String getName() - { + public String getName() { return name; } /** - * Sets the name of the grammar, used to activate the gammer later. + * Sets the name of the grammar, used to activate the grammar later. * * @param name the name of the grammar. */ - public void setName(String name) - { + public void setName(String name) { this.name = name; } @@ -73,8 +68,7 @@ public void setName(String name) * * @return the path to the grammar. */ - public String getPath() - { + public String getPath() { return path; } @@ -83,14 +77,12 @@ public String getPath() * * @param path the path to the grammar. */ - public void setPath(String path) - { + public void setPath(String path) { this.path = path; } @Override - public String buildCommand() - { + public String buildCommand() { return "SPEECH LOAD GRAMMAR " + escapeAndQuote(name) + " " + escapeAndQuote(path); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/SpeechRecognizeCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SpeechRecognizeCommand.java index ffb1b2dd5..8eab217b5 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SpeechRecognizeCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SpeechRecognizeCommand.java @@ -1,34 +1,31 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Plays back given prompt while listening for speech and dtmf.

    - * Available since Asterisk 1.6. + * AGI Command: SPEECH RECOGNIZE + *

    + * Recognizes speech. + *

    + * See: AGI Command SPEECH RECOGNIZE (Asterisk 18) * * @author srt - * @version $Id$ * @since 1.0.0 */ -public class SpeechRecognizeCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SpeechRecognizeCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; private String prompt; @@ -36,13 +33,12 @@ public class SpeechRecognizeCommand extends AbstractAgiCommand private int offset; /** - * Creates a new SpeechRecognizeCommand that plays the given prompt and listens for for speech and dtmf. + * Creates a new SpeechRecognizeCommand that plays the given prompt and listens for speech and dtmf. * * @param prompt the prompt to play. * @param timeout the maximum recognition time in milliseconds. */ - public SpeechRecognizeCommand(String prompt, int timeout) - { + public SpeechRecognizeCommand(String prompt, int timeout) { this.prompt = prompt; this.timeout = timeout; this.offset = 0; @@ -55,8 +51,7 @@ public SpeechRecognizeCommand(String prompt, int timeout) * @param timeout the maximum recognition time in milliseconds. * @param offset the offset samples to skip when playing the prompt. */ - public SpeechRecognizeCommand(String prompt, int timeout, int offset) - { + public SpeechRecognizeCommand(String prompt, int timeout, int offset) { this.prompt = prompt; this.timeout = timeout; this.offset = offset; @@ -67,8 +62,7 @@ public SpeechRecognizeCommand(String prompt, int timeout, int offset) * * @return the prompt to play. */ - public String getPrompt() - { + public String getPrompt() { return prompt; } @@ -77,8 +71,7 @@ public String getPrompt() * * @param prompt the prompt to play. */ - public void setPrompt(String prompt) - { + public void setPrompt(String prompt) { this.prompt = prompt; } @@ -87,8 +80,7 @@ public void setPrompt(String prompt) * * @return the maximum recognition time in milliseconds. */ - public int getTimeout() - { + public int getTimeout() { return timeout; } @@ -97,8 +89,7 @@ public int getTimeout() * * @param timeout the maximum recognition time in milliseconds, or -1 for no timeout. */ - public void setTimeout(int timeout) - { + public void setTimeout(int timeout) { this.timeout = timeout; } @@ -107,8 +98,7 @@ public void setTimeout(int timeout) * * @return the offset samples to skip when playing the prompt. */ - public int getOffset() - { + public int getOffset() { return offset; } @@ -117,14 +107,12 @@ public int getOffset() * * @param offset the offset samples to skip when playing the prompt. */ - public void setOffset(int offset) - { + public void setOffset(int offset) { this.offset = offset; } @Override - public String buildCommand() - { + public String buildCommand() { return "SPEECH RECOGNIZE " + escapeAndQuote(prompt) + " " + timeout + " " + offset; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/SpeechSetCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SpeechSetCommand.java index 0f300747a..538d9c5a1 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SpeechSetCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SpeechSetCommand.java @@ -1,35 +1,33 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Sets a speech engine specific setting.

    - * Available since Asterisk 1.6. + * AGI Command: SPEECH SET + *

    + * Sets a speech engine setting. + *

    + * See: AGI Command SPEECH SET (Asterisk 18) * * @author srt - * @version $Id$ * @since 1.0.0 */ -public class SpeechSetCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SpeechSetCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; + private String name; private String value; @@ -39,8 +37,7 @@ public class SpeechSetCommand extends AbstractAgiCommand * @param name the name of the setting to set. * @param value the value to set. */ - public SpeechSetCommand(String name, String value) - { + public SpeechSetCommand(String name, String value) { this.name = name; this.value = value; } @@ -50,8 +47,7 @@ public SpeechSetCommand(String name, String value) * * @return the name of the setting to set. */ - public String getName() - { + public String getName() { return name; } @@ -60,8 +56,7 @@ public String getName() * * @param name the name of the setting to set. */ - public void setName(String name) - { + public void setName(String name) { this.name = name; } @@ -70,8 +65,7 @@ public void setName(String name) * * @return the value to set. */ - public String getValue() - { + public String getValue() { return value; } @@ -80,14 +74,12 @@ public String getValue() * * @param value the value to set. */ - public void setValue(String value) - { + public void setValue(String value) { this.value = value; } @Override - public String buildCommand() - { + public String buildCommand() { return "SPEECH SET " + escapeAndQuote(name) + " " + escapeAndQuote(value); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/SpeechUnloadGrammarCommand.java b/src/main/java/org/asteriskjava/fastagi/command/SpeechUnloadGrammarCommand.java index 1d1ca0bc6..8e76bbbd5 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/SpeechUnloadGrammarCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/SpeechUnloadGrammarCommand.java @@ -1,45 +1,42 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Unloads the specified grammar.

    - * Available since Asterisk 1.6. + * AGI Command: SPEECH UNLOAD GRAMMAR + *

    + * Unloads a grammar. + *

    + * See: AGI Command SPEECH UNLOAD GRAMMAR (Asterisk 18) * * @author srt - * @version $Id$ * @see SpeechLoadGrammarCommand * @since 1.0.0 */ -public class SpeechUnloadGrammarCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class SpeechUnloadGrammarCommand extends AbstractAgiCommand { private static final long serialVersionUID = 1L; + private String name; /** - * Creates a new SpeechUnloadGrammarCommand that unloads the given grammer. + * Creates a new SpeechUnloadGrammarCommand that unloads the given grammar. * * @param name the name of the grammar. */ - public SpeechUnloadGrammarCommand(String name) - { + public SpeechUnloadGrammarCommand(String name) { this.name = name; } @@ -48,8 +45,7 @@ public SpeechUnloadGrammarCommand(String name) * * @return the name of the grammar. */ - public String getName() - { + public String getName() { return name; } @@ -58,14 +54,12 @@ public String getName() * * @param name the name of the grammar. */ - public void setName(String name) - { + public void setName(String name) { this.name = name; } @Override - public String buildCommand() - { + public String buildCommand() { return "SPEECH UNLOAD GRAMMAR " + escapeAndQuote(name); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/command/StreamFileCommand.java b/src/main/java/org/asteriskjava/fastagi/command/StreamFileCommand.java index 6bef5f529..91f3fdd12 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/StreamFileCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/StreamFileCommand.java @@ -17,28 +17,15 @@ package org.asteriskjava.fastagi.command; /** - * Plays the given file, allowing playback to be interrupted by the given - * digits, if any. + * AGI Command: STREAM FILE *

    - * If offset is provided then the audio will seek to sample offset before play - * starts. + * Sends audio file on channel. *

    - * Returns 0 if playback completes without a digit being pressed, or the ASCII - * numerical value of the digit if one was pressed, or -1 on error or if the - * channel was disconnected. - *

    - * Remember, filename follows the same conventions and uses the same file path - * as dialplan applications like Playback or Background. The file extension must - * not be included in the filename. - * + * See: AGI Command STREAM FILE (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class StreamFileCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class StreamFileCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3978141041352128820L; /** @@ -58,11 +45,10 @@ public class StreamFileCommand extends AbstractAgiCommand /** * Creates a new StreamFileCommand, streaming from the beginning. - * + * * @param file the name of the file to stream, must not include extension. */ - public StreamFileCommand(String file) - { + public StreamFileCommand(String file) { super(); this.file = file; this.offset = -1; @@ -70,13 +56,12 @@ public StreamFileCommand(String file) /** * Creates a new StreamFileCommand, streaming from the beginning. - * - * @param file the name of the file to stream, must not include extension. + * + * @param file the name of the file to stream, must not include extension. * @param escapeDigits contains the digits that allow the user to interrupt - * this command. + * this command. */ - public StreamFileCommand(String file, String escapeDigits) - { + public StreamFileCommand(String file, String escapeDigits) { super(); this.file = file; this.escapeDigits = escapeDigits; @@ -85,15 +70,14 @@ public StreamFileCommand(String file, String escapeDigits) /** * Creates a new StreamFileCommand, streaming from the given offset. - * - * @param file the name of the file to stream, must not include extension. + * + * @param file the name of the file to stream, must not include extension. * @param escapeDigits contains the digits that allow the user to interrupt - * this command. Maybe null if you don't want the - * user to interrupt. - * @param offset the offset samples to skip before streaming. + * this command. Maybe null if you don't want the + * user to interrupt. + * @param offset the offset samples to skip before streaming. */ - public StreamFileCommand(String file, String escapeDigits, int offset) - { + public StreamFileCommand(String file, String escapeDigits, int offset) { super(); this.file = file; this.escapeDigits = escapeDigits; @@ -102,70 +86,61 @@ public StreamFileCommand(String file, String escapeDigits, int offset) /** * Returns the name of the file to stream. - * + * * @return the name of the file to stream. */ - public String getFile() - { + public String getFile() { return file; } /** * Sets the name of the file to stream. - * + * * @param file the name of the file to stream, must not include extension. */ - public void setFile(String file) - { + public void setFile(String file) { this.file = file; } /** * Returns the digits that allow the user to interrupt this command. - * + * * @return the digits that allow the user to interrupt this command. */ - public String getEscapeDigits() - { + public String getEscapeDigits() { return escapeDigits; } /** * Sets the digits that allow the user to interrupt this command. - * + * * @param escapeDigits the digits that allow the user to interrupt this - * command or null for none. + * command or null for none. */ - public void setEscapeDigits(String escapeDigits) - { + public void setEscapeDigits(String escapeDigits) { this.escapeDigits = escapeDigits; } /** * Returns the offset samples to skip before streaming. - * + * * @return the offset samples to skip before streaming. */ - public int getOffset() - { + public int getOffset() { return offset; } /** * Sets the offset samples to skip before streaming. - * + * * @param offset the offset samples to skip before streaming. */ - public void setOffset(int offset) - { + public void setOffset(int offset) { this.offset = offset; } @Override - public String buildCommand() - { - return "STREAM FILE " + escapeAndQuote(file) + " " - + escapeAndQuote(escapeDigits) - + (offset < 0 ? "" : " " + offset); + public String buildCommand() { + return "STREAM FILE " + escapeAndQuote(file) + " " + escapeAndQuote(escapeDigits) + (offset < 0 ? "" : " " + offset); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/TddModeCommand.java b/src/main/java/org/asteriskjava/fastagi/command/TddModeCommand.java index 6bdfe6435..fbcd15dbe 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/TddModeCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/TddModeCommand.java @@ -1,33 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Enable/Disable TDD transmission/reception on a channel.

    - * Returns 1 if successful, or 0 if channel is not TDD-capable. - * + * AGI Command: TDD MODE + *

    + * Toggles TDD mode (for the deaf). + *

    + * See: AGI Command TDD MODE (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class TddModeCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class TddModeCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3258411746401268532L; /** @@ -37,40 +34,34 @@ public class TddModeCommand extends AbstractAgiCommand /** * Creates a new TDDModeCommand. - * - * @param mode the mode to set, this can be one of "on", "off", "mate" or - * "tdd". + * + * @param mode the mode to set, this can be one of "on", "off", "mate" or "tdd". */ - public TddModeCommand(String mode) - { + public TddModeCommand(String mode) { super(); this.mode = mode; } /** * Returns the mode to set. - * + * * @return the mode to set. */ - public String getMode() - { + public String getMode() { return mode; } /** * Sets the mode to set. - * - * @param mode the mode to set, this can be one of "on", "off", "mate" or - * "tdd". + * + * @param mode the mode to set, this can be one of "on", "off", "mate" or "tdd". */ - public void setMode(String mode) - { + public void setMode(String mode) { this.mode = mode; } @Override - public String buildCommand() - { + public String buildCommand() { return "TDD MODE " + escapeAndQuote(mode); } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/VerboseCommand.java b/src/main/java/org/asteriskjava/fastagi/command/VerboseCommand.java index 2fdd1fd08..c9df38b99 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/VerboseCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/VerboseCommand.java @@ -1,33 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Sends a message to the Asterisk console via the verbose message system.

    - * Always returns 1. - * + * AGI Command: VERBOSE + *

    + * Logs a message to the asterisk verbose log. + *

    + * See: AGI Command VERBOSE (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class VerboseCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class VerboseCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3256719598056387384L; /** @@ -43,13 +40,12 @@ public class VerboseCommand extends AbstractAgiCommand /** * Creates a new VerboseCommand. - * + * * @param message the message to send. - * @param level the verbosity level to use.

    - * Must be in [1..4] + * @param level the verbosity level to use.

    + * Must be in [1..4] */ - public VerboseCommand(String message, int level) - { + public VerboseCommand(String message, int level) { super(); this.message = message; this.level = level; @@ -57,48 +53,43 @@ public VerboseCommand(String message, int level) /** * Returns the message to send. - * + * * @return the message to send. */ - public String getMessage() - { + public String getMessage() { return message; } /** * Sets the message to send. - * + * * @param message the message to send. */ - public void setMessage(String message) - { + public void setMessage(String message) { this.message = message; } /** * Returns the level to use. - * + * * @return the level to use. */ - public int getLevel() - { + public int getLevel() { return level; } /** * Sets the level to use.

    * Must be in in [1..4]. - * + * * @param level the level to use. */ - public void setLevel(int level) - { + public void setLevel(int level) { this.level = level; } @Override - public String buildCommand() - { + public String buildCommand() { return "VERBOSE " + escapeAndQuote(message) + " " + level; } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/WaitForDigitCommand.java b/src/main/java/org/asteriskjava/fastagi/command/WaitForDigitCommand.java index ce9971986..7a861d15e 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/WaitForDigitCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/WaitForDigitCommand.java @@ -1,35 +1,30 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; /** - * Waits up to 'timeout' milliseconds for channel to receive a DTMF digit.

    - * Returns -1 on channel failure, 0 if no digit is received in the timeout, or - * the numerical value of the ascii of the digit if one is received. Use -1 for - * the timeout value if you desire the call to block indefinitely. - * + * AGI Command: WAIT FOR DIGIT + *

    + * Waits for a digit to be pressed. + *

    + * See: AGI Command WAIT FOR DIGIT (Asterisk 18) + * * @author srt - * @version $Id$ */ -public class WaitForDigitCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +public class WaitForDigitCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3257562923458443314L; /** @@ -38,51 +33,43 @@ public class WaitForDigitCommand extends AbstractAgiCommand private long timeout; /** - * Creates a new WaitForDigitCommand with a default timeout of -1 which - * blocks the channel indefinitely. + * Creates a new WaitForDigitCommand with a default timeout of -1 which blocks the channel indefinitely. */ - public WaitForDigitCommand() - { + public WaitForDigitCommand() { super(); this.timeout = -1; } /** * Creates a new WaitForDigitCommand. - * - * @param timeout the milliseconds to wait for the channel to receive a DTMF - * digit. + * + * @param timeout the milliseconds to wait for the channel to receive a DTMF digit. */ - public WaitForDigitCommand(long timeout) - { + public WaitForDigitCommand(long timeout) { super(); this.timeout = timeout; } /** * Returns the milliseconds to wait for the channel to receive a DTMF digit. - * + * * @return the milliseconds to wait for the channel to receive a DTMF digit. */ - public long getTimeout() - { + public long getTimeout() { return timeout; } /** * Sets the milliseconds to wait for the channel to receive a DTMF digit. - * - * @param timeout the milliseconds to wait for the channel to receive a DTMF - * digit. + * + * @param timeout the milliseconds to wait for the channel to receive a DTMF digit. */ - public void setTimeout(long timeout) - { + public void setTimeout(long timeout) { this.timeout = timeout; } @Override - public String buildCommand() - { + public String buildCommand() { return "WAIT FOR DIGIT " + timeout; } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/package.html b/src/main/java/org/asteriskjava/fastagi/command/package.html index 391c66946..96eb51bd4 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/package.html +++ b/src/main/java/org/asteriskjava/fastagi/command/package.html @@ -1,28 +1,27 @@ - + -

    Provides classes that represent the standard commands that can be sent - to an Asterisk server via the FastAGI.

    +

    Provides classes that represent the standard commands that can be sent to an Asterisk server via the FastAGI.

    - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelImpl.java b/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelImpl.java index 184a91866..cb51f56d0 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelImpl.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelImpl.java @@ -16,9 +16,12 @@ */ package org.asteriskjava.fastagi.internal; +import org.asteriskjava.AsteriskVersion; import org.asteriskjava.fastagi.*; import org.asteriskjava.fastagi.command.*; import org.asteriskjava.fastagi.reply.AgiReply; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; /** * Default implementation of the AgiChannel interface. @@ -26,477 +29,448 @@ * @author srt * @version $Id$ */ -public class AgiChannelImpl implements AgiChannel -{ +public class AgiChannelImpl implements AgiChannel { private final AgiRequest request; private final AgiWriter agiWriter; private final AgiReader agiReader; + private AsteriskVersion asteriskVersion; + + private static Log logger = LogFactory.getLog(AgiChannelImpl.class); private AgiReply lastReply; - protected AgiChannelImpl(AgiRequest request, AgiWriter agiWriter, AgiReader agiReader) - { + protected AgiChannelImpl(AgiRequest request, AgiWriter agiWriter, AgiReader agiReader) { this.request = request; this.agiWriter = agiWriter; this.agiReader = agiReader; this.lastReply = null; } - public String getName() - { + public String getName() { return request.getChannel(); } - public String getUniqueId() - { + public String getUniqueId() { return request.getUniqueId(); } - public AgiReply getLastReply() - { + public AgiReply getLastReply() { return lastReply; } - public synchronized AgiReply sendCommand(AgiCommand command) throws AgiException - { + public synchronized AgiReply sendCommand(AgiCommand command) throws AgiException { + // make the Asterisk Version available to the AgiCommand, with out + // causing a major refactor + command.setAsteriskVersion(getAsteriskVersion()); agiWriter.sendCommand(command); lastReply = agiReader.readReply(); - if (lastReply.getStatus() == AgiReply.SC_INVALID_OR_UNKNOWN_COMMAND) - { + if (lastReply.getStatus() == AgiReply.SC_INVALID_OR_UNKNOWN_COMMAND) { throw new InvalidOrUnknownCommandException(command.buildCommand()); } - if (lastReply.getStatus() == AgiReply.SC_DEAD_CHANNEL) - { + if (lastReply.getStatus() == AgiReply.SC_DEAD_CHANNEL) { throw new AgiHangupException(); } - if (lastReply.getStatus() == AgiReply.SC_INVALID_COMMAND_SYNTAX) - { + if (lastReply.getStatus() == AgiReply.SC_INVALID_COMMAND_SYNTAX) { throw new InvalidCommandSyntaxException(lastReply.getSynopsis(), lastReply.getUsage()); } return lastReply; } - public void answer() throws AgiException - { + public AsteriskVersion getAsteriskVersion() { + if (request == null) { + logger.warn("Request is null, I assume you're testing..."); + return AsteriskVersion.DEFAULT_VERSION; + } + if (asteriskVersion == null) { + asteriskVersion = request.getAsteriskVersion(); + } + return asteriskVersion; + } + + public void answer() throws AgiException { sendCommand(new AnswerCommand()); } - public void hangup() throws AgiException - { + public void hangup() throws AgiException { sendCommand(new HangupCommand()); } - public void setAutoHangup(int time) throws AgiException - { + public void setAutoHangup(int time) throws AgiException { sendCommand(new SetAutoHangupCommand(time)); } - public void setCallerId(String callerId) throws AgiException - { + public void setCallerId(String callerId) throws AgiException { sendCommand(new SetCallerIdCommand(callerId)); } - public void playMusicOnHold() throws AgiException - { + public void playMusicOnHold() throws AgiException { sendCommand(new SetMusicOnCommand()); } - public void playMusicOnHold(String musicOnHoldClass) throws AgiException - { + public void playMusicOnHold(String musicOnHoldClass) throws AgiException { sendCommand(new SetMusicOnCommand(musicOnHoldClass)); } - public void stopMusicOnHold() throws AgiException - { + public void stopMusicOnHold() throws AgiException { sendCommand(new SetMusicOffCommand()); } - public int getChannelStatus() throws AgiException - { + public int getChannelStatus() throws AgiException { sendCommand(new ChannelStatusCommand()); return lastReply.getResultCode(); } - public String getData(String file) throws AgiException - { + public String getData(String file) throws AgiException { sendCommand(new GetDataCommand(file)); return lastReply.getResult(); } - public String getData(String file, long timeout) throws AgiException - { + public String getData(String file, long timeout) throws AgiException { sendCommand(new GetDataCommand(file, timeout)); return lastReply.getResult(); } - public String getData(String file, long timeout, int maxDigits) throws AgiException - { + public String getData(String file, long timeout, int maxDigits) throws AgiException { sendCommand(new GetDataCommand(file, timeout, maxDigits)); return lastReply.getResult(); } - public char getOption(String file, String escapeDigits) throws AgiException - { + public char getOption(String file, String escapeDigits) throws AgiException { sendCommand(new GetOptionCommand(file, escapeDigits)); return lastReply.getResultCodeAsChar(); } - public char getOption(String file, String escapeDigits, long timeout) throws AgiException - { + public char getOption(String file, String escapeDigits, long timeout) throws AgiException { sendCommand(new GetOptionCommand(file, escapeDigits, timeout)); return lastReply.getResultCodeAsChar(); } - public int exec(String application) throws AgiException - { + public int exec(String application) throws AgiException { sendCommand(new ExecCommand(application)); return lastReply.getResultCode(); } - public int exec(String application, String... options) throws AgiException - { + public int exec(String application, String... options) throws AgiException { sendCommand(new ExecCommand(application, options)); return lastReply.getResultCode(); } - public void setContext(String context) throws AgiException - { + public void setContext(String context) throws AgiException { sendCommand(new SetContextCommand(context)); } - public void setExtension(String extension) throws AgiException - { + public void setExtension(String extension) throws AgiException { sendCommand(new SetExtensionCommand(extension)); } - public void setPriority(String priority) throws AgiException - { + public void setPriority(String priority) throws AgiException { sendCommand(new SetPriorityCommand(priority)); } - public void streamFile(String file) throws AgiException - { + public void streamFile(String file) throws AgiException { + checkFile(file); sendCommand(new StreamFileCommand(file)); } - public char streamFile(String file, String escapeDigits) throws AgiException - { + private void checkFile(String file) { + if (file == null || file.length() == 0) { + logger.error( + "Call to streamFile with empty file, this will result in AGI setting AGISTATUS = FAILURE and returning -1"); + } + } + + public char streamFile(String file, String escapeDigits) throws AgiException { + checkFile(file); sendCommand(new StreamFileCommand(file, escapeDigits)); return lastReply.getResultCodeAsChar(); } - public char streamFile(String file, String escapeDigits, int offset) throws AgiException - { + public char streamFile(String file, String escapeDigits, int offset) throws AgiException { + checkFile(file); sendCommand(new StreamFileCommand(file, escapeDigits, offset)); return lastReply.getResultCodeAsChar(); } - public void sayDigits(String digits) throws AgiException - { + public void sayDigits(String digits) throws AgiException { sendCommand(new SayDigitsCommand(digits)); } - public char sayDigits(String digits, String escapeDigits) throws AgiException - { + public char sayDigits(String digits, String escapeDigits) throws AgiException { sendCommand(new SayDigitsCommand(digits, escapeDigits)); return lastReply.getResultCodeAsChar(); } - public void sayNumber(String number) throws AgiException - { + public void sayNumber(String number) throws AgiException { sendCommand(new SayNumberCommand(number)); } - public char sayNumber(String number, String escapeDigits) throws AgiException - { + public char sayNumber(String number, String escapeDigits) throws AgiException { sendCommand(new SayNumberCommand(number, escapeDigits)); return lastReply.getResultCodeAsChar(); } - public void sayPhonetic(String text) throws AgiException - { + public void sayPhonetic(String text) throws AgiException { sendCommand(new SayPhoneticCommand(text)); } - public char sayPhonetic(String text, String escapeDigits) throws AgiException - { + public char sayPhonetic(String text, String escapeDigits) throws AgiException { sendCommand(new SayPhoneticCommand(text, escapeDigits)); return lastReply.getResultCodeAsChar(); } - public void sayAlpha(String text) throws AgiException - { + public void sayAlpha(String text) throws AgiException { sendCommand(new SayAlphaCommand(text)); } - public char sayAlpha(String text, String escapeDigits) throws AgiException - { + public char sayAlpha(String text, String escapeDigits) throws AgiException { sendCommand(new SayAlphaCommand(text, escapeDigits)); return lastReply.getResultCodeAsChar(); } - public void sayTime(long time) throws AgiException - { + public void sayTime(long time) throws AgiException { sendCommand(new SayTimeCommand(time)); } - public char sayTime(long time, String escapeDigits) throws AgiException - { + public char sayTime(long time, String escapeDigits) throws AgiException { sendCommand(new SayTimeCommand(time, escapeDigits)); return lastReply.getResultCodeAsChar(); } - public String getVariable(String name) throws AgiException - { + public String getVariable(String name) throws AgiException { sendCommand(new GetVariableCommand(name)); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { return null; } return lastReply.getExtra(); } - public void setVariable(String name, String value) throws AgiException - { + public void setVariable(String name, String value) throws AgiException { sendCommand(new SetVariableCommand(name, value)); } - public char waitForDigit(int timeout) throws AgiException - { + public char waitForDigit(int timeout) throws AgiException { sendCommand(new WaitForDigitCommand(timeout)); return lastReply.getResultCodeAsChar(); } - public String getFullVariable(String name) throws AgiException - { + public String getFullVariable(String name) throws AgiException { sendCommand(new GetFullVariableCommand(name)); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { return null; } return lastReply.getExtra(); } - public String getFullVariable(String name, String channel) throws AgiException - { + public String getFullVariable(String name, String channel) throws AgiException { sendCommand(new GetFullVariableCommand(name, channel)); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { return null; } return lastReply.getExtra(); } - public char sayDateTime(long time, String escapeDigits, String format, String timezone) throws AgiException - { + public char sayDateTime(long time, String escapeDigits, String format, String timezone) throws AgiException { sendCommand(new SayDateTimeCommand(time, escapeDigits, format, timezone)); return lastReply.getResultCodeAsChar(); } - public char sayDateTime(long time, String escapeDigits, String format) throws AgiException - { + public char sayDateTime(long time, String escapeDigits, String format) throws AgiException { sendCommand(new SayDateTimeCommand(time, escapeDigits, format)); return lastReply.getResultCodeAsChar(); } - public char sayDateTime(long time, String escapeDigits) throws AgiException - { + public char sayDateTime(long time, String escapeDigits) throws AgiException { sendCommand(new SayDateTimeCommand(time, escapeDigits)); return lastReply.getResultCodeAsChar(); } - public void sayDateTime(long time) throws AgiException - { + public void sayDateTime(long time) throws AgiException { sendCommand(new SayDateTimeCommand(time)); } - public String databaseGet(String family, String key) throws AgiException - { + public String databaseGet(String family, String key) throws AgiException { sendCommand(new DatabaseGetCommand(family, key)); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { return null; } return lastReply.getExtra(); } - public void databasePut(String family, String key, String value) throws AgiException - { + public void databasePut(String family, String key, String value) throws AgiException { sendCommand(new DatabasePutCommand(family, key, value)); } - public void databaseDel(String family, String key) throws AgiException - { + public void databaseDel(String family, String key) throws AgiException { sendCommand(new DatabaseDelCommand(family, key)); } - public void databaseDelTree(String family) throws AgiException - { + public void databaseDelTree(String family) throws AgiException { sendCommand(new DatabaseDelTreeCommand(family)); } - public void databaseDelTree(String family, String keytree) throws AgiException - { + public void databaseDelTree(String family, String keytree) throws AgiException { sendCommand(new DatabaseDelTreeCommand(family, keytree)); } - public void verbose(String message, int level) throws AgiException - { + public void verbose(String message, int level) throws AgiException { sendCommand(new VerboseCommand(message, level)); } - public char recordFile(String file, String format, String escapeDigits, int timeout) throws AgiException - { + public char recordFile(String file, String format, String escapeDigits, int timeout) throws AgiException { sendCommand(new RecordFileCommand(file, format, escapeDigits, timeout)); return lastReply.getResultCodeAsChar(); } - public char recordFile(String file, String format, String escapeDigits, int timeout, int offset, boolean beep, int maxSilence) throws AgiException - { + public char recordFile(String file, String format, String escapeDigits, int timeout, int offset, boolean beep, + int maxSilence) throws AgiException { sendCommand(new RecordFileCommand(file, format, escapeDigits, timeout, offset, beep, maxSilence)); return lastReply.getResultCodeAsChar(); } - public void controlStreamFile(String file) throws AgiException - { + public void controlStreamFile(String file) throws AgiException { sendCommand(new ControlStreamFileCommand(file)); } - public char controlStreamFile(String file, String escapeDigits) throws AgiException - { + public char controlStreamFile(String file, String escapeDigits) throws AgiException { sendCommand(new ControlStreamFileCommand(file, escapeDigits)); return lastReply.getResultCodeAsChar(); } - public char controlStreamFile(String file, String escapeDigits, int offset) throws AgiException - { + public char controlStreamFile(String file, String escapeDigits, int offset) throws AgiException { sendCommand(new ControlStreamFileCommand(file, escapeDigits, offset)); return lastReply.getResultCodeAsChar(); } - public char controlStreamFile(String file, String escapeDigits, int offset, String forwardDigit, String rewindDigit, String pauseDigit) throws AgiException - { + public char controlStreamFile(String file, String escapeDigits, int offset, String forwardDigit, String rewindDigit, + String pauseDigit) throws AgiException { sendCommand(new ControlStreamFileCommand(file, escapeDigits, offset, forwardDigit, rewindDigit, pauseDigit)); return lastReply.getResultCodeAsChar(); } - public void speechCreate() throws AgiException - { + public void speechCreate() throws AgiException { speechCreate(""); } - public void speechCreate(String engine) throws AgiException - { + public void speechCreate(String engine) throws AgiException { sendCommand(new SpeechCreateCommand(engine)); - if (lastReply.getResultCode() != 1) - { - if (engine == null || "".equals(engine)) - { + if (lastReply.getResultCode() != 1) { + if (engine == null || "".equals(engine)) { throw new AgiSpeechException("Speech object for default engine cannot be created"); } - else - { - throw new AgiSpeechException("Speech object for engine '" + engine + "' cannot be created"); - } + throw new AgiSpeechException("Speech object for engine '" + engine + "' cannot be created"); } } - public void speechSet(String name, String value) throws AgiException - { + public void speechSet(String name, String value) throws AgiException { sendCommand(new SpeechSetCommand(name, value)); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { throw new AgiSpeechException("Setting '" + name + "' cannot be set to '" + value + "'"); } } - public void speechDestroy() throws AgiException - { + public void speechDestroy() throws AgiException { sendCommand(new SpeechDestroyCommand()); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { throw new AgiSpeechException("Speech object cannot be destroyed"); } } - public void speechLoadGrammar(String name, String path) throws AgiException - { + public void speechLoadGrammar(String name, String path) throws AgiException { sendCommand(new SpeechLoadGrammarCommand(name, path)); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { throw new AgiSpeechException("Grammar '" + name + "' cannot be loaded from '" + path + "'"); } } - public void speechUnloadGrammar(String name) throws AgiException - { + public void speechUnloadGrammar(String name) throws AgiException { sendCommand(new SpeechUnloadGrammarCommand(name)); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { throw new AgiSpeechException("Grammar '" + name + "' cannot be unloaded"); } } - public void speechActivateGrammar(String name) throws AgiException - { + public void speechActivateGrammar(String name) throws AgiException { sendCommand(new SpeechActivateGrammarCommand(name)); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { throw new AgiSpeechException("Grammar '" + name + "' cannot be activated"); } } - public void speechDeactivateGrammar(String name) throws AgiException - { + public void speechDeactivateGrammar(String name) throws AgiException { sendCommand(new SpeechDeactivateGrammarCommand(name)); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { throw new AgiSpeechException("Grammar '" + name + "' cannot be deactivated"); } } - public SpeechRecognitionResult speechRecognize(String prompt, int timeout) throws AgiException - { + public SpeechRecognitionResult speechRecognize(String prompt, int timeout) throws AgiException { return speechRecognize(new SpeechRecognizeCommand(prompt, timeout)); } - public SpeechRecognitionResult speechRecognize(String prompt, int timeout, int offset) throws AgiException - { + public SpeechRecognitionResult speechRecognize(String prompt, int timeout, int offset) throws AgiException { return speechRecognize(new SpeechRecognizeCommand(prompt, timeout, offset)); } - private SpeechRecognitionResult speechRecognize(SpeechRecognizeCommand command) throws AgiException - { + private SpeechRecognitionResult speechRecognize(SpeechRecognizeCommand command) throws AgiException { sendCommand(command); - if (lastReply.getResultCode() != 1) - { + if (lastReply.getResultCode() != 1) { throw new AgiSpeechException("Cannot recognize speech"); } - if ("hangup".equals(lastReply.getExtra())) - { + if ("hangup".equals(lastReply.getExtra())) { throw new AgiHangupException(); } final AgiReply speechRecognizeReply = lastReply; return new SpeechRecognitionResult(speechRecognizeReply); } - public void continueAt(String context, String extension, String priority) throws AgiException - { + public void continueAt(String context, String extension, String priority) throws AgiException { setContext(context); setExtension(extension); setPriority(priority); } - public void gosub(String context, String extension, String priority) throws AgiException - { + public void gosub(String context, String extension, String priority) throws AgiException { sendCommand(new GosubCommand(context, extension, priority)); } - public void gosub(String context, String extension, String priority, String... arguments) throws AgiException - { + public void gosub(String context, String extension, String priority, String... arguments) throws AgiException { sendCommand(new GosubCommand(context, extension, priority, arguments)); } + + public AgiRequest getInternalAgiRequest() { + return request; + } + + @Override + public void confbridge(String room, String profile) throws AgiException { + sendCommand(new ConfbridgeCommand(room, profile)); + + } + + @Override + public void meetme(String room, String options) throws AgiException { + sendCommand(new MeetmeCommand(room, options)); + + } + + @Override + public void dial(String target, int timeout, String options) throws AgiException { + sendCommand(new DialCommand(target, timeout, options)); + + } + + @Override + public void bridge(String channelName, String options) throws AgiException { + sendCommand(new BridgeCommand(channelName, options)); + + } + + @Override + public void queue(String queue) throws AgiException { + sendCommand(new QueueCommand(queue)); + + } } diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AgiConnectionHandler.java b/src/main/java/org/asteriskjava/fastagi/internal/AgiConnectionHandler.java index c3d6e85f8..cf66f8c9c 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiConnectionHandler.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AgiConnectionHandler.java @@ -21,28 +21,32 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + /** * An AgiConnectionHandler is created and run by the AgiServer whenever a new - * AGI connection from an Asterisk Server is received. - *

    + * AGI connection from an Asterisk Server is received.
    * It reads the request using an AgiReader and runs the AgiScript configured to * handle this type of request. Finally it closes the AGI connection. * * @author srt * @version $Id$ */ -public abstract class AgiConnectionHandler implements Runnable -{ +public abstract class AgiConnectionHandler implements Runnable { private static final String AJ_AGISTATUS_VARIABLE = "AJ_AGISTATUS"; private static final String AJ_AGISTATUS_NOT_FOUND = "NOT_FOUND"; private static final String AJ_AGISTATUS_SUCCESS = "SUCCESS"; private static final String AJ_AGISTATUS_FAILED = "FAILED"; - private static final ThreadLocal channel = new ThreadLocal(); + private static final ThreadLocal channel = new ThreadLocal<>(); private final Log logger = LogFactory.getLog(getClass()); private boolean ignoreMissingScripts = false; private AgiScript script = null; private AgiChannelFactory agiChannelFactory; + public static final ConcurrentMap AGI_CONNECTION_HANDLERS = new ConcurrentHashMap<>( + 32); + /** * The strategy to use to determine which script to run. */ @@ -51,17 +55,16 @@ public abstract class AgiConnectionHandler implements Runnable /** * Creates a new AGIConnectionHandler to handle the given socket connection. * - * @param mappingStrategy the strategy to use to determine which script to run. - * @param agiChannelFactory the AgiFactory, that is used to create new AgiChannel objects. + * @param mappingStrategy the strategy to use to determine which script to + * run. + * @param agiChannelFactory the AgiFactory, that is used to create new + * AgiChannel objects. */ - protected AgiConnectionHandler(MappingStrategy mappingStrategy, AgiChannelFactory agiChannelFactory) - { - if (mappingStrategy == null) - { + protected AgiConnectionHandler(MappingStrategy mappingStrategy, AgiChannelFactory agiChannelFactory) { + if (mappingStrategy == null) { throw new IllegalArgumentException("MappingStrategy must not be null"); } - if (agiChannelFactory == null) - { + if (agiChannelFactory == null) { throw new IllegalArgumentException("AgiChannelFactory must not be null"); } @@ -69,18 +72,15 @@ protected AgiConnectionHandler(MappingStrategy mappingStrategy, AgiChannelFactor this.mappingStrategy = mappingStrategy; } - protected boolean isIgnoreMissingScripts() - { + protected boolean isIgnoreMissingScripts() { return ignoreMissingScripts; } - protected void setIgnoreMissingScripts(boolean ignoreMissingScripts) - { + protected void setIgnoreMissingScripts(boolean ignoreMissingScripts) { this.ignoreMissingScripts = ignoreMissingScripts; } - protected AgiScript getScript() - { + protected AgiScript getScript() { return script; } @@ -93,12 +93,11 @@ protected AgiScript getScript() */ public abstract void release(); - public void run() - { + @Override + public void run() { AgiChannel channel = null; - try - { + try { AgiReader reader; AgiWriter writer; AgiRequest request; @@ -111,110 +110,92 @@ public void run() AgiConnectionHandler.channel.set(channel); - if (mappingStrategy != null) - { + if (mappingStrategy != null) { script = mappingStrategy.determineScript(request, channel); } - if (script == null && !ignoreMissingScripts) - { + if (script == null && !ignoreMissingScripts) { final String errorMessage; - errorMessage = "No script configured for URL '" + request.getRequestURL() + "' (script '" + request.getScript() + "')"; + errorMessage = "No script configured for URL '" + request.getRequestURL() + "' (script '" + + request.getScript() + "')"; logger.error(errorMessage); setStatusVariable(channel, AJ_AGISTATUS_NOT_FOUND); logToAsterisk(channel, errorMessage); - } - else if (script != null) - { + } else if (script != null) { + AGI_CONNECTION_HANDLERS.put(this, channel); runScript(script, request, channel); } - } - catch (AgiException e) - { + } catch (AgiException e) { setStatusVariable(channel, AJ_AGISTATUS_FAILED); logger.error("AgiException while handling request", e); - } - catch (Exception e) - { + } catch (Exception e) { setStatusVariable(channel, AJ_AGISTATUS_FAILED); logger.error("Unexpected Exception while handling request", e); - } - finally - { + } finally { + AGI_CONNECTION_HANDLERS.remove(this); AgiConnectionHandler.channel.set(null); release(); } - } + }// run - private void runScript(AgiScript script, AgiRequest request, AgiChannel channel) - { + private void runScript(AgiScript script, AgiRequest request, AgiChannel channel) { + String channelName = channel.getName(); String threadName; threadName = Thread.currentThread().getName(); - logger.info("Begin AgiScript " + getScriptName(script) + " on " + threadName); - try - { + logger.debug("Begin AgiScript " + describeAgiCall(threadName, channelName)); + try { script.service(request, channel); setStatusVariable(channel, AJ_AGISTATUS_SUCCESS); - } - catch (AgiException e) - { - logger.error("AgiException running AgiScript " + getScriptName(script) + " on " + threadName, e); + } catch (AgiException e) { + logger.error("AgiException running AgiScript " + describeAgiCall(threadName, channelName), e); setStatusVariable(channel, AJ_AGISTATUS_FAILED); - } - catch (Exception e) - { - logger.error("Exception running AgiScript " + getScriptName(script) + " on " + threadName, e); + } catch (Exception e) { + logger.error("Exception running AgiScript " + describeAgiCall(threadName, channelName), e); setStatusVariable(channel, AJ_AGISTATUS_FAILED); + } finally { + logger.debug("End AgiScript " + describeAgiCall(threadName, channelName)); } - logger.info("End AgiScript " + getScriptName(script) + " on " + threadName); } - protected String getScriptName(AgiScript script) - { - if (script == null) - { + private String describeAgiCall(String threadName, String channelName) { + return getScriptName(script) + " on " + threadName + " on " + channelName; + } + + protected String getScriptName(AgiScript script) { + if (script == null) { return null; } - if (script instanceof NamedAgiScript) - { + if (script instanceof NamedAgiScript) { return ((NamedAgiScript) script).getName(); } return script.getClass().getName(); } - private void setStatusVariable(AgiChannel channel, String value) - { - if (channel == null) - { + private void setStatusVariable(AgiChannel channel, String value) { + if (channel == null) { return; } - try - { + try { channel.setVariable(AJ_AGISTATUS_VARIABLE, value); - } - catch (Exception e) // NOPMD + } catch (Exception e) // NOPMD { // swallow } } - private void logToAsterisk(AgiChannel channel, String message) - { - if (channel == null) - { + private void logToAsterisk(AgiChannel channel, String message) { + if (channel == null) { return; } - try - { + try { channel.sendCommand(new VerboseCommand(message, 1)); - } - catch (Exception e) // NOPMD + } catch (Exception e) // NOPMD { // swallow } @@ -224,10 +205,9 @@ private void logToAsterisk(AgiChannel channel, String message) * Returns the AgiChannel associated with the current thread. * * @return the AgiChannel associated with the current thread or - * null if none is associated. + * null if none is associated. */ - public static AgiChannel getChannel() - { + public static AgiChannel getChannel() { return AgiConnectionHandler.channel.get(); } } diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AgiReplyImpl.java b/src/main/java/org/asteriskjava/fastagi/internal/AgiReplyImpl.java index 323383d7f..2bded2bd1 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiReplyImpl.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AgiReplyImpl.java @@ -16,11 +16,11 @@ */ package org.asteriskjava.fastagi.internal; -import java.util.*; -import java.util.regex.*; - import org.asteriskjava.fastagi.reply.AgiReply; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Default implementation of the AgiReply interface. @@ -28,8 +28,7 @@ * @author srt * @version $Id$ */ -public class AgiReplyImpl implements AgiReply -{ +public class AgiReplyImpl implements AgiReply { private static final Pattern STATUS_PATTERN = Pattern.compile("^(\\d{3})[ -]"); private static final Pattern RESULT_PATTERN = Pattern.compile("^200 result=(\\S+)"); private static final Pattern PARENTHESIS_PATTERN = Pattern.compile("^200 result=\\S* +\\((.*)\\)"); @@ -77,177 +76,140 @@ public class AgiReplyImpl implements AgiReply */ private String usage; - AgiReplyImpl() - { + AgiReplyImpl() { super(); this.status = null; } - AgiReplyImpl(List lines) - { + AgiReplyImpl(List lines) { this(); - if (lines != null) - { - this.lines = new ArrayList(lines); - if (!lines.isEmpty()) - { + if (lines != null) { + this.lines = new ArrayList<>(lines); + if (!lines.isEmpty()) { firstLine = lines.get(0); } } } - public String getFirstLine() - { + public String getFirstLine() { return firstLine; } - public List getLines() - { + public List getLines() { return lines; } - public int getResultCode() - { + public int getResultCode() { String result; result = getResult(); - if (result == null) - { + if (result == null) { return -1; } - try - { + try { return Integer.parseInt(result); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return -1; } } - public char getResultCodeAsChar() - { + public char getResultCodeAsChar() { int resultCode; resultCode = getResultCode(); - if (resultCode < 0) - { + if (resultCode < 0) { return 0x0; } return (char) resultCode; } - public String getResult() - { - if (result != null) - { + public String getResult() { + if (result != null) { return result; } final Matcher matcher = RESULT_PATTERN.matcher(firstLine); - if (matcher.find()) - { + if (matcher.find()) { result = matcher.group(1); - } - else + } else result = ""; return result; } - public int getStatus() - { - if (status != null) - { + public int getStatus() { + if (status != null) { return status; } + if (firstLine == null) { + return -1; + } + final Matcher matcher = STATUS_PATTERN.matcher(firstLine); - if (matcher.find()) - { + if (matcher.find()) { status = Integer.parseInt(matcher.group(1)); return status; } return -1; } - public String getAttribute(String name) - { - if (getStatus() != SC_SUCCESS) - { + public String getAttribute(String name) { + if (getStatus() != SC_SUCCESS) { return null; } - if ("result".equalsIgnoreCase(name)) - { + if ("result".equalsIgnoreCase(name)) { return getResult(); } return getAttributes().get(name.toLowerCase(Locale.ENGLISH)); } - protected Map getAttributes() - { - if (attributes != null) - { + protected Map getAttributes() { + if (attributes != null) { return attributes; } - attributes = new HashMap(); + attributes = new HashMap<>(); final Matcher matcher = ADDITIONAL_ATTRIBUTES_PATTERN.matcher(firstLine); - if (matcher.find()) - { + if (matcher.find()) { attributes.putAll(parseAttributes(matcher.group(2))); } return attributes; } - Map parseAttributes(String s) - { + Map parseAttributes(String s) { StringBuilder keyBuilder = new StringBuilder(); StringBuilder valueBuilder = new StringBuilder(); - Map map = new HashMap(); + Map map = new HashMap<>(); boolean inKey = true; boolean inQuotes = false; char previousChar = 0x0; - for (int i = 0; i < s.length(); i++) - { + for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); - if (c == '=' && inKey) - { + if (c == '=' && inKey) { inKey = false; inQuotes = false; - } - else if ((c == ' ' && !inKey && !inQuotes)) - { + } else if (c == ' ' && !inKey && !inQuotes) { map.put(keyBuilder.toString().toLowerCase(Locale.ENGLISH), valueBuilder.toString()); keyBuilder.delete(0, keyBuilder.length()); valueBuilder.delete(0, valueBuilder.length()); inKey = true; - } - else if (c == '"' && !inKey) - { - if (previousChar == '\\') - { + } else if (c == '"' && !inKey) { + if (previousChar == '\\') { valueBuilder.deleteCharAt(valueBuilder.length() - 1); valueBuilder.append(c); - } - else - { + } else { inQuotes = !inQuotes; } - } - else - { - if (inKey) - { + } else { + if (inKey) { keyBuilder.append(c); - } - else - { + } else { valueBuilder.append(c); } } @@ -255,8 +217,7 @@ else if (c == '"' && !inKey) previousChar = c; } - if (keyBuilder.length() > 0) - { + if (keyBuilder.length() > 0) { map.put(keyBuilder.toString().toLowerCase(Locale.ENGLISH), valueBuilder.toString()); } return map; @@ -264,43 +225,35 @@ else if (c == '"' && !inKey) private boolean extraCreated; - public String getExtra() - { - if (getStatus() != SC_SUCCESS) - { + public String getExtra() { + if (getStatus() != SC_SUCCESS) { return null; } - if (extraCreated) - { + if (extraCreated) { return extra; } final Matcher matcher = PARENTHESIS_PATTERN.matcher(firstLine); - if (matcher.find()) - { + if (matcher.find()) { extra = matcher.group(1); } extraCreated = true; return extra; } - public String getSynopsis() - { - if (getStatus() != SC_INVALID_COMMAND_SYNTAX) - { + public String getSynopsis() { + if (getStatus() != SC_INVALID_COMMAND_SYNTAX) { return null; } - if (synopsis == null && lines.size() > 1) - { + if (synopsis == null && lines.size() > 1) { final String secondLine; final Matcher synopsisMatcher; secondLine = lines.get(1); synopsisMatcher = SYNOPSIS_PATTERN.matcher(secondLine); - if (synopsisMatcher.find()) - { + if (synopsisMatcher.find()) { synopsis = synopsisMatcher.group(1); } } @@ -311,23 +264,19 @@ public String getSynopsis() * Returns the usage of the command sent if Asterisk expected a different * syntax (getStatus() == SC_INVALID_COMMAND_SYNTAX). * - * @return the usage of the command sent, null if there were - * no syntax errors. + * @return the usage of the command sent, null if there were no + * syntax errors. */ - public String getUsage() - { - if (usage == null) - { + public String getUsage() { + if (usage == null) { StringBuilder usageSB; usageSB = new StringBuilder(); - for (int i = 2; i < lines.size(); i++) - { + for (int i = 2; i < lines.size(); i++) { String line; line = lines.get(i); - if (END_OF_PROPER_USAGE.equals(line)) - { + if (END_OF_PROPER_USAGE.equals(line)) { break; } @@ -340,20 +289,17 @@ public String getUsage() } @Override - public String toString() - { + public String toString() { StringBuilder sb; sb = new StringBuilder("AgiReply["); sb.append("status=").append(getStatus()).append(","); - if (status == SC_SUCCESS) - { + if (status == SC_SUCCESS) { sb.append("result='").append(getResult()).append("',"); sb.append("extra='").append(getExtra()).append("',"); sb.append("attributes=").append(getAttributes()).append(","); } - if (status == SC_INVALID_COMMAND_SYNTAX) - { + if (status == SC_INVALID_COMMAND_SYNTAX) { sb.append("synopsis='").append(getSynopsis()).append("',"); } sb.append("systemHashcode=").append(System.identityHashCode(this)); diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AgiRequestImpl.java b/src/main/java/org/asteriskjava/fastagi/internal/AgiRequestImpl.java index a8bd5e060..a24b8453d 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiRequestImpl.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AgiRequestImpl.java @@ -16,6 +16,7 @@ */ package org.asteriskjava.fastagi.internal; +import org.asteriskjava.AsteriskVersion; import org.asteriskjava.fastagi.AgiRequest; import org.asteriskjava.util.AstUtil; import org.asteriskjava.util.Log; @@ -28,15 +29,13 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; - /** * Default implementation of the AGIRequest interface. - * + * * @author srt * @version $Id$ */ -public class AgiRequestImpl implements AgiRequest -{ +public class AgiRequestImpl implements AgiRequest { private final Log logger = LogFactory.getLog(getClass()); private static final Pattern SCRIPT_PATTERN = Pattern.compile("^([^\\?]*)\\?(.*)$"); private static final Pattern PARAMETER_PATTERN = Pattern.compile("^(.*)=(.*)$"); @@ -63,31 +62,28 @@ public class AgiRequestImpl implements AgiRequest /** * Creates a new AGIRequestImpl. - * + * * @param environment the first lines as received from Asterisk containing - * the environment. + * the environment. */ - AgiRequestImpl(final List environment) - { + AgiRequestImpl(final List environment) { this(buildMap(environment)); } /** * Creates a new AgiRequestImpl based on a preparsed map of parameters. * - * @param request a map representing the AGI request. Keys must not contain the "agi_" or "ogi_" prefix. + * @param request a map representing the AGI request. Keys must not contain + * the "agi_" or "ogi_" prefix. * @since 1.0.0 */ - private AgiRequestImpl(final Map request) - { + private AgiRequestImpl(final Map request) { this.request = request; script = request.get("network_script"); - if (script != null) - { + if (script != null) { Matcher scriptMatcher = SCRIPT_PATTERN.matcher(script); - if (scriptMatcher.matches()) - { + if (scriptMatcher.matches()) { script = scriptMatcher.group(1); parameters = scriptMatcher.group(2); } @@ -95,27 +91,26 @@ private AgiRequestImpl(final Map request) } /** - * Builds a map containing variable names as key (with the "agi_" or "ogi_" prefix - * stripped) and the corresponding values.

    + * Builds a map containing variable names as key (with the "agi_" or "ogi_" + * prefix stripped) and the corresponding values. + *

    * Syntactically invalid and empty variables are skipped. - * + * * @param lines the environment to transform. - * @return a map with the variables set corresponding to the given environment. + * @return a map with the variables set corresponding to the given + * environment. * @throws IllegalArgumentException if lines is null */ - private static Map buildMap(final Collection lines) throws IllegalArgumentException - { + private static Map buildMap(final Collection lines) throws IllegalArgumentException { final Map map; - if (lines == null) - { + if (lines == null) { throw new IllegalArgumentException("Environment must not be null."); } - map = new HashMap(); + map = new HashMap<>(); - for (String line : lines) - { + for (String line : lines) { int colonPosition; String key; String value; @@ -123,28 +118,24 @@ private static Map buildMap(final Collection lines) thro colonPosition = line.indexOf(':'); // no colon on the line? - if (colonPosition < 0) - { + if (colonPosition < 0) { continue; } // key doesn't start with agi_ or ogi_? - if (!line.startsWith("agi_") && !line.startsWith("ogi_")) - { + if (!line.startsWith("agi_") && !line.startsWith("ogi_")) { continue; } // first colon in line is last character -> no value present? - if (line.length() < colonPosition + 2) - { + if (line.length() < colonPosition + 2) { continue; } key = line.substring(4, colonPosition).toLowerCase(Locale.ENGLISH); value = line.substring(colonPosition + 2); - if (value.length() != 0) - { + if (value.length() != 0) { map.put(key, value); } } @@ -152,149 +143,128 @@ private static Map buildMap(final Collection lines) thro return map; } - public Map getRequest() - { + public Map getRequest() { return request; } /** * Returns the name of the script to execute. - * + * * @return the name of the script to execute. */ - public synchronized String getScript() - { + public synchronized String getScript() { return script; } /** * Returns the full URL of the request in the form * agi://host[:port][/script]. - * + * * @return the full URL of the request in the form - * agi://host[:port][/script]. + * agi://host[:port][/script]. */ - public String getRequestURL() - { + public String getRequestURL() { return request.get("request"); } + @Override + public AsteriskVersion getAsteriskVersion() { + AsteriskVersion detected = AsteriskVersion.getDetermineVersionFromString("Asterisk " + request.get("version")); + return detected != null ? detected : AsteriskVersion.DEFAULT_VERSION; + } + /** * Returns the name of the channel. - * + * * @return the name of the channel. */ - public String getChannel() - { + public String getChannel() { return request.get("channel"); } /** * Returns the unqiue id of the channel. - * + * * @return the unqiue id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return request.get("uniqueid"); } - public String getType() - { + public String getType() { return request.get("type"); } - public String getLanguage() - { + public String getLanguage() { return request.get("language"); } - @Deprecated public String getCallerId() - { + @Deprecated + public String getCallerId() { return getCallerIdNumber(); } - public String getCallerIdNumber() - { + public String getCallerIdNumber() { String callerIdName; String callerId; callerIdName = request.get("calleridname"); callerId = request.get("callerid"); - if (callerIdName != null) - { + if (callerIdName != null) { // Asterisk 1.2 - if (callerId == null || "unknown".equals(callerId)) - { + if (callerId == null || "unknown".equals(callerId)) { return null; } return callerId; } - else - { - // Asterisk 1.0 - return getCallerId10(); - } + // Asterisk 1.0 + return getCallerId10(); } - public String getCallerIdName() - { + public String getCallerIdName() { String callerIdName; callerIdName = request.get("calleridname"); - if (callerIdName != null) - { + if (callerIdName != null) { // Asterisk 1.2 - if ("unknown".equals(callerIdName)) - { + if ("unknown".equals(callerIdName)) { return null; } return callerIdName; } - else - { - // Asterisk 1.0 - return getCallerIdName10(); - } + // Asterisk 1.0 + return getCallerIdName10(); } /** * Returns the Caller*ID number using Asterisk 1.0 logic. - * + * * @return the Caller*ID number */ - private synchronized String getCallerId10() - { + private synchronized String getCallerId10() { final String[] parsedCallerId; - if (!callerIdCreated) - { + if (!callerIdCreated) { rawCallerId = request.get("callerid"); callerIdCreated = true; } parsedCallerId = AstUtil.parseCallerId(rawCallerId); - if (parsedCallerId[1] == null) - { + if (parsedCallerId[1] == null) { return parsedCallerId[0]; } - else - { - return parsedCallerId[1]; - } + return parsedCallerId[1]; } /** * Returns the Caller*ID name using Asterisk 1.0 logic. - * + * * @return the Caller*ID name */ - private synchronized String getCallerIdName10() - { - if (!callerIdCreated) - { + private synchronized String getCallerIdName10() { + if (!callerIdCreated) { rawCallerId = request.get("callerid"); callerIdCreated = true; } @@ -302,160 +272,121 @@ private synchronized String getCallerIdName10() return AstUtil.parseCallerId(rawCallerId)[0]; } - public String getDnid() - { + public String getDnid() { String dnid; - + dnid = request.get("dnid"); - - if (dnid == null || "unknown".equals(dnid)) - { + + if (dnid == null || "unknown".equals(dnid)) { return null; } - - return dnid; + + return dnid; } - public String getRdnis() - { + public String getRdnis() { String rdnis; - + rdnis = request.get("rdnis"); - - if (rdnis == null || "unknown".equals(rdnis)) - { + + if (rdnis == null || "unknown".equals(rdnis)) { return null; } - - return rdnis; + + return rdnis; } - public String getContext() - { + public String getContext() { return request.get("context"); } - public String getExtension() - { + public String getExtension() { return request.get("extension"); } - public Integer getPriority() - { - if (request.get("priority") != null) - { + public Integer getPriority() { + if (request.get("priority") != null) { return Integer.valueOf(request.get("priority")); } return null; } - public Boolean getEnhanced() - { - if (request.get("enhanced") != null) - { - if ("1.0".equals(request.get("enhanced"))) - { + public Boolean getEnhanced() { + if (request.get("enhanced") != null) { + if ("1.0".equals(request.get("enhanced"))) { return Boolean.TRUE; } - else - { - return Boolean.FALSE; - } + return Boolean.FALSE; } return null; } - public String getAccountCode() - { + public String getAccountCode() { return request.get("accountcode"); } - public Integer getCallingAni2() - { - if (request.get("callingani2") == null) - { + public Integer getCallingAni2() { + if (request.get("callingani2") == null) { return null; } - try - { + try { return Integer.valueOf(request.get("callingani2")); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return null; } } - public Integer getCallingPres() - { - if (request.get("callingpres") == null) - { + public Integer getCallingPres() { + if (request.get("callingpres") == null) { return null; } - - try - { + + try { return Integer.valueOf(request.get("callingpres")); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return null; } } - public Integer getCallingTns() - { - if (request.get("callingtns") == null) - { + public Integer getCallingTns() { + if (request.get("callingtns") == null) { return null; } - - try - { + + try { return Integer.valueOf(request.get("callingtns")); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return null; } } - public Integer getCallingTon() - { - if (request.get("callington") == null) - { + public Integer getCallingTon() { + if (request.get("callington") == null) { return null; } - - try - { + + try { return Integer.valueOf(request.get("callington")); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return null; } } - public String getParameter(String name) - { + public String getParameter(String name) { String[] values; values = getParameterValues(name); - if (values == null || values.length == 0) - { + if (values == null || values.length == 0) { return null; } return values[0]; } - public synchronized String[] getParameterValues(String name) - { - if (getParameterMap().isEmpty()) - { + public synchronized String[] getParameterValues(String name) { + if (getParameterMap().isEmpty()) { return new String[0]; } @@ -463,10 +394,8 @@ public synchronized String[] getParameterValues(String name) return values == null ? new String[0] : values; } - public synchronized Map getParameterMap() - { - if (parameterMap == null) - { + public synchronized Map getParameterMap() { + if (parameterMap == null) { parameterMap = parseParameters(parameters); } return parameterMap; @@ -474,27 +403,24 @@ public synchronized Map getParameterMap() /** * Parses the given parameter string and caches the result. - * + * * @param s the parameter string to parse * @return a Map made up of parameter names their values */ - private synchronized Map parseParameters(String s) - { + private synchronized Map parseParameters(String s) { Map> parameterMap; Map result; StringTokenizer st; - parameterMap = new HashMap>(); - result = new HashMap(); + parameterMap = new HashMap<>(); + result = new HashMap<>(); - if (s == null) - { + if (s == null) { return result; } st = new StringTokenizer(s, "&"); - while (st.hasMoreTokens()) - { + while (st.hasMoreTokens()) { String parameter; Matcher parameterMatcher; String name; @@ -503,48 +429,35 @@ private synchronized Map parseParameters(String s) parameter = st.nextToken(); parameterMatcher = PARAMETER_PATTERN.matcher(parameter); - if (parameterMatcher.matches()) - { - try - { + if (parameterMatcher.matches()) { + try { name = URLDecoder.decode(parameterMatcher.group(1), "UTF-8"); value = URLDecoder.decode(parameterMatcher.group(2), "UTF-8"); - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { logger.error("Unable to decode parameter '" + parameter + "'", e); continue; } - } - else - { - try - { + } else { + try { name = URLDecoder.decode(parameter, "UTF-8"); value = ""; - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { logger.error("Unable to decode parameter '" + parameter + "'", e); continue; } } - if (parameterMap.get(name) == null) - { - values = new ArrayList(); + if (parameterMap.get(name) == null) { + values = new ArrayList<>(); values.add(value); parameterMap.put(name, values); - } - else - { + } else { values = parameterMap.get(name); values.add(value); } } - for (Map.Entry> entry : parameterMap.entrySet()) - { + for (Map.Entry> entry : parameterMap.entrySet()) { String[] valueArray; valueArray = new String[entry.getValue().size()]; @@ -554,85 +467,70 @@ private synchronized Map parseParameters(String s) return result; } - public synchronized String[] getArguments() - { - if (arguments != null) - { + public synchronized String[] getArguments() { + if (arguments != null) { return arguments.clone(); } - final Map map = new HashMap(); + final Map map = new HashMap<>(); int maxIndex = 0; - for (Map.Entry entry : request.entrySet()) - { - if (! entry.getKey().startsWith("arg_")) - { + for (Map.Entry entry : request.entrySet()) { + if (!entry.getKey().startsWith("arg_")) { continue; } - int index = Integer.valueOf(entry.getKey().substring(4)); - if (index > maxIndex) - { + int index = Integer.parseInt(entry.getKey().substring(4)); + if (index > maxIndex) { maxIndex = index; } map.put(index, entry.getValue()); } arguments = new String[maxIndex]; - for (int i = 0; i < maxIndex; i++) - { + for (int i = 0; i < maxIndex; i++) { arguments[i] = map.get(i + 1); } - + return arguments.clone(); } - public InetAddress getLocalAddress() - { + public InetAddress getLocalAddress() { return localAddress; } - void setLocalAddress(InetAddress localAddress) - { + void setLocalAddress(InetAddress localAddress) { this.localAddress = localAddress; } - public int getLocalPort() - { + public int getLocalPort() { return localPort; } - void setLocalPort(int localPort) - { + void setLocalPort(int localPort) { this.localPort = localPort; } - public InetAddress getRemoteAddress() - { + public InetAddress getRemoteAddress() { return remoteAddress; } - void setRemoteAddress(InetAddress remoteAddress) - { + void setRemoteAddress(InetAddress remoteAddress) { this.remoteAddress = remoteAddress; } - public int getRemotePort() - { + public int getRemotePort() { return remotePort; } - void setRemotePort(int remotePort) - { + void setRemotePort(int remotePort) { this.remotePort = remotePort; } @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; - sb = new StringBuffer("AgiRequest["); + sb = new StringBuilder("AgiRequest["); sb.append("script='").append(getScript()).append("',"); sb.append("requestURL='").append(getRequestURL()).append("',"); sb.append("channel='").append(getChannel()).append("',"); diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiConnectionHandler.java b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiConnectionHandler.java index be76bc63a..4fce51751 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiConnectionHandler.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiConnectionHandler.java @@ -16,27 +16,25 @@ */ package org.asteriskjava.fastagi.internal; +import org.asteriskjava.fastagi.*; +import org.asteriskjava.fastagi.command.AsyncAgiBreakCommand; +import org.asteriskjava.manager.ManagerConnection; +import org.asteriskjava.manager.event.AsyncAgiEvent; + import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -import org.asteriskjava.fastagi.AgiException; -import org.asteriskjava.fastagi.MappingStrategy; -import org.asteriskjava.fastagi.command.AsyncAgiBreakCommand; -import org.asteriskjava.manager.event.AsyncAgiEvent; -import org.asteriskjava.manager.ManagerConnection; - /** * An AgiConnectionHandler for AsyncAGI. - *

    + *
    * It reads the request using a AsyncAgiReader and runs the AgiScript configured to * handle this type of request. Finally it sends an {@link org.asteriskjava.fastagi.command.AsyncAgiBreakCommand}. * * @author srt * @version $Id$ */ -public class AsyncAgiConnectionHandler extends AgiConnectionHandler -{ +public class AsyncAgiConnectionHandler extends AgiConnectionHandler { private final ManagerConnection connection; private volatile String channelName; private final List environment; @@ -51,62 +49,51 @@ public class AsyncAgiConnectionHandler extends AgiConnectionHandler * @param agiChannelFactory The factory to use for creating new AgiChannel instances. * @throws IllegalArgumentException if asyncAgiStartEvent is not a start sub type". */ - public AsyncAgiConnectionHandler(MappingStrategy mappingStrategy, AsyncAgiEvent asyncAgiStartEvent, AgiChannelFactory agiChannelFactory) throws IllegalArgumentException - { + public AsyncAgiConnectionHandler(MappingStrategy mappingStrategy, AsyncAgiEvent asyncAgiStartEvent, AgiChannelFactory agiChannelFactory) throws IllegalArgumentException { super(mappingStrategy, agiChannelFactory); - if (!asyncAgiStartEvent.isStart()) - { + if (!asyncAgiStartEvent.isStart()) { throw new IllegalArgumentException("AsyncAgiEvent passed to AsyncAgiConnectionHandler is not a start sub event"); } connection = (ManagerConnection) asyncAgiStartEvent.getSource(); channelName = asyncAgiStartEvent.getChannel(); environment = asyncAgiStartEvent.decodeEnv(); - asyncAgiEvents = new LinkedBlockingQueue(); + asyncAgiEvents = new LinkedBlockingQueue<>(); setIgnoreMissingScripts(true); } @Override - protected AgiReader createReader() - { + protected AgiReader createReader() { return new AsyncAgiReader(connection, environment, asyncAgiEvents); } @Override - protected AgiWriter createWriter() - { + protected AgiWriter createWriter() { writer = new AsyncAgiWriter(connection, channelName); return writer; } @Override - public void release() - { - if (writer != null && (getScript() != null || ! isIgnoreMissingScripts())) - { - try - { + public void release() { + if (writer != null && (getScript() != null || !isIgnoreMissingScripts())) { + try { writer.sendCommand(new AsyncAgiBreakCommand()); - } - catch (AgiException e) // NOPMD + } catch (AgiException e) // NOPMD { // ignore } } } - public void onAsyncAgiExecEvent(AsyncAgiEvent event) - { + public void onAsyncAgiExecEvent(AsyncAgiEvent event) { asyncAgiEvents.offer(event); } - public void onAsyncAgiEndEvent(AsyncAgiEvent event) - { + public void onAsyncAgiEndEvent(AsyncAgiEvent event) { asyncAgiEvents.offer(event); } - public void updateChannelName(String channelName) - { + public void updateChannelName(String channelName) { this.channelName = channelName; writer.updateChannelName(channelName); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiReader.java b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiReader.java index e1a4614cc..631fc956d 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiReader.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiReader.java @@ -1,21 +1,20 @@ package org.asteriskjava.fastagi.internal; import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiReader; import org.asteriskjava.fastagi.AgiRequest; import org.asteriskjava.fastagi.reply.AgiReply; -import org.asteriskjava.manager.event.AsyncAgiEvent; import org.asteriskjava.manager.ManagerConnection; +import org.asteriskjava.manager.event.AsyncAgiEvent; import java.util.List; import java.util.concurrent.BlockingQueue; -public class AsyncAgiReader implements AgiReader -{ +public class AsyncAgiReader implements AgiReader { private final AgiRequestImpl request; private final BlockingQueue asyncAgiEvents; - public AsyncAgiReader(ManagerConnection connection, List environment, BlockingQueue asyncAgiEvents) - { + public AsyncAgiReader(ManagerConnection connection, List environment, BlockingQueue asyncAgiEvents) { this.request = new AgiRequestImpl(environment); this.asyncAgiEvents = asyncAgiEvents; @@ -25,19 +24,14 @@ public AsyncAgiReader(ManagerConnection connection, List environment, Bl request.setRemotePort(connection.getRemotePort()); } - public AgiRequest readRequest() throws AgiException - { + public AgiRequest readRequest() throws AgiException { return request; } - public AgiReply readReply() throws AgiException - { - try - { + public AgiReply readReply() throws AgiException { + try { return new AgiReplyImpl(asyncAgiEvents.take().decodeResult()); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AgiException("Interrupted while waiting for AsyncAgiEvent", e); } diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiWriter.java b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiWriter.java index d8f800f48..bfe44849e 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiWriter.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiWriter.java @@ -1,12 +1,13 @@ package org.asteriskjava.fastagi.internal; -import org.asteriskjava.fastagi.command.AgiCommand; import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiWriter; +import org.asteriskjava.fastagi.command.AgiCommand; import org.asteriskjava.manager.ManagerConnection; import org.asteriskjava.manager.TimeoutException; -import org.asteriskjava.manager.response.ManagerResponse; -import org.asteriskjava.manager.response.ManagerError; import org.asteriskjava.manager.action.AgiAction; +import org.asteriskjava.manager.response.ManagerError; +import org.asteriskjava.manager.response.ManagerResponse; import java.io.IOException; @@ -16,50 +17,40 @@ * * @see org.asteriskjava.manager.ManagerConnection * @see org.asteriskjava.manager.action.AgiAction - * @since 1.0.0 + * @since 1.0.0 */ -public class AsyncAgiWriter implements AgiWriter -{ +public class AsyncAgiWriter implements AgiWriter { private final ManagerConnection connection; private volatile String channelName; - public AsyncAgiWriter(ManagerConnection connection, String channelName) - { + public AsyncAgiWriter(ManagerConnection connection, String channelName) { this.connection = connection; this.channelName = channelName; } - public void sendCommand(AgiCommand command) throws AgiException - { + public void sendCommand(AgiCommand command) throws AgiException { final AgiAction agiAction; final ManagerResponse response; agiAction = new AgiAction(channelName, command.buildCommand()); - try - { + try { response = connection.sendAction(agiAction); - } - catch (IOException e) - { + } catch (IOException e) { throw new AgiException("Unable to send AsyncAGI command to " + connection.getHostname() + " for channel " + channelName, e); - } - catch (TimeoutException e) - { + } catch (TimeoutException e) { throw new AgiException("Timeout while sending AsyncAGI command to " + connection.getHostname() + - " for channel " + channelName , e); + " for channel " + channelName, e); } - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new AgiException("Unable to send AsyncAGI command to " + connection.getHostname() + " for channel " + channelName + ": " + response.getMessage()); } } - public void updateChannelName(String channelName) - { + public void updateChannelName(String channelName) { this.channelName = channelName; } } diff --git a/src/main/java/org/asteriskjava/fastagi/internal/DefaultAgiChannelFactory.java b/src/main/java/org/asteriskjava/fastagi/internal/DefaultAgiChannelFactory.java old mode 100755 new mode 100644 index 9193bdd45..a5b7e9c6b --- a/src/main/java/org/asteriskjava/fastagi/internal/DefaultAgiChannelFactory.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/DefaultAgiChannelFactory.java @@ -1,18 +1,15 @@ -package org.asteriskjava.fastagi.internal; - -import org.asteriskjava.fastagi.AgiChannel; -import org.asteriskjava.fastagi.AgiRequest; - -/** - * If no other factory is passed to DefaultAgiServer's constructor, - * an instance of this one will be used. The DefaultAgiChannelFactory - * creates AgiChannelImpl instances, that are passed to the agi scripts. - */ -public class DefaultAgiChannelFactory implements AgiChannelFactory -{ - @Override - public AgiChannel createAgiChannel(AgiRequest request, AgiWriter agiWriter, AgiReader agiReader) - { - return new AgiChannelImpl(request, agiWriter, agiReader); - } -} +package org.asteriskjava.fastagi.internal; + +import org.asteriskjava.fastagi.*; + +/** + * If no other factory is passed to DefaultAgiServer's constructor, + * an instance of this one will be used. The DefaultAgiChannelFactory + * creates AgiChannelImpl instances, that are passed to the agi scripts. + */ +public class DefaultAgiChannelFactory implements AgiChannelFactory { + @Override + public AgiChannel createAgiChannel(AgiRequest request, AgiWriter agiWriter, AgiReader agiReader) { + return new AgiChannelImpl(request, agiWriter, agiReader); + } +} diff --git a/src/main/java/org/asteriskjava/fastagi/internal/FastAgiConnectionHandler.java b/src/main/java/org/asteriskjava/fastagi/internal/FastAgiConnectionHandler.java index 3e8a55979..99e4005c4 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/FastAgiConnectionHandler.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/FastAgiConnectionHandler.java @@ -16,22 +16,24 @@ */ package org.asteriskjava.fastagi.internal; -import java.io.IOException; - +import org.asteriskjava.fastagi.AgiChannelFactory; +import org.asteriskjava.fastagi.AgiReader; +import org.asteriskjava.fastagi.AgiWriter; import org.asteriskjava.fastagi.MappingStrategy; import org.asteriskjava.util.SocketConnectionFacade; +import java.io.IOException; + /** * An AgiConnectionHandler for FastAGI. - *

    + *
    * It reads the request using a FastAgiReader and runs the AgiScript configured to * handle this type of request. Finally it closes the socket connection. * * @author srt * @version $Id$ */ -public class FastAgiConnectionHandler extends AgiConnectionHandler -{ +public class FastAgiConnectionHandler extends AgiConnectionHandler { /** * The socket connection. */ @@ -44,34 +46,28 @@ public class FastAgiConnectionHandler extends AgiConnectionHandler * @param socket the socket connection to handle. * @param agiChannelFactory The factory to use for creating new AgiChannel instances. */ - public FastAgiConnectionHandler(MappingStrategy mappingStrategy, SocketConnectionFacade socket, AgiChannelFactory agiChannelFactory) - { + public FastAgiConnectionHandler(MappingStrategy mappingStrategy, SocketConnectionFacade socket, AgiChannelFactory agiChannelFactory) { super(mappingStrategy, agiChannelFactory); this.socket = socket; } @Override - protected AgiReader createReader() - { + protected AgiReader createReader() { return new FastAgiReader(socket); } @Override - protected AgiWriter createWriter() - { + protected AgiWriter createWriter() { return new FastAgiWriter(socket); } @Override - public void release() - { - try - { + public void release() { + try { socket.close(); - } - catch (IOException e) // NOPMD + } catch (IOException e) // NOPMD { // swallow } } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/fastagi/internal/FastAgiReader.java b/src/main/java/org/asteriskjava/fastagi/internal/FastAgiReader.java index 57e4b4f01..92323dc50 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/FastAgiReader.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/FastAgiReader.java @@ -16,54 +16,43 @@ */ package org.asteriskjava.fastagi.internal; +import org.asteriskjava.fastagi.*; +import org.asteriskjava.fastagi.reply.AgiReply; +import org.asteriskjava.util.SocketConnectionFacade; + import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.asteriskjava.fastagi.AgiException; -import org.asteriskjava.fastagi.AgiHangupException; -import org.asteriskjava.fastagi.AgiNetworkException; -import org.asteriskjava.fastagi.AgiRequest; -import org.asteriskjava.fastagi.reply.AgiReply; -import org.asteriskjava.util.SocketConnectionFacade; - /** * Default implementation of the AgiReader implementation. - * + * * @author srt * @version $Id$ */ -class FastAgiReader implements AgiReader -{ +class FastAgiReader implements AgiReader { private final SocketConnectionFacade socket; - FastAgiReader(SocketConnectionFacade socket) - { + FastAgiReader(SocketConnectionFacade socket) { this.socket = socket; } - public AgiRequest readRequest() throws AgiException - { + public AgiRequest readRequest() throws AgiException { AgiRequestImpl request; String line; List lines; - lines = new ArrayList(); + lines = new ArrayList<>(); - try - { - while ((line = socket.readLine()) != null) - { - if (line.length() == 0) - { + try { + while ((line = socket.readLine()) != null) { + if (line.length() == 0) { break; } lines.add(line); } - } - catch (IOException e) - { + } catch (IOException e) { throw new AgiNetworkException("Unable to read request from Asterisk: " + e.getMessage(), e); } @@ -76,39 +65,30 @@ public AgiRequest readRequest() throws AgiException return request; } - public AgiReply readReply() throws AgiException - { + public AgiReply readReply() throws AgiException { AgiReply reply; List lines; String line; - lines = new ArrayList(); + lines = new ArrayList<>(); - try - { + try { line = socket.readLine(); - } - catch (IOException e) - { + } catch (IOException e) { // readline throws IOException if the connection has been closed throw new AgiHangupException(); } - if (line == null) - { + if (line == null) { throw new AgiHangupException(); } // TODO Asterisk 1.6 sends "HANGUP" when the channel is hung up. - //System.out.println(line); - if (line.startsWith("HANGUP")) - { - if (line.length() > 6) - { + // System.out.println(line); + if (line.startsWith("HANGUP")) { + if (line.length() > 6) { line = line.substring(6); - } - else - { + } else { return readReply(); } } @@ -116,21 +96,15 @@ public AgiReply readReply() throws AgiException lines.add(line); // read synopsis and usage if statuscode is 520 - if (line.startsWith(Integer.toString(AgiReply.SC_INVALID_COMMAND_SYNTAX))) - { - try - { - while ((line = socket.readLine()) != null) - { + if (line.startsWith(Integer.toString(AgiReply.SC_INVALID_COMMAND_SYNTAX))) { + try { + while ((line = socket.readLine()) != null) { lines.add(line); - if (line.startsWith(Integer.toString(AgiReply.SC_INVALID_COMMAND_SYNTAX))) - { + if (line.startsWith(Integer.toString(AgiReply.SC_INVALID_COMMAND_SYNTAX))) { break; } } - } - catch (IOException e) - { + } catch (IOException e) { throw new AgiNetworkException("Unable to read reply from Asterisk: " + e.getMessage(), e); } } @@ -138,13 +112,9 @@ public AgiReply readReply() throws AgiException reply = new AgiReplyImpl(lines); // Special handling for gosub, see AJ-257 - if (reply.getStatus() == AgiReply.SC_TRYING) - { - return readReply(); - } - else - { - return reply; + if (reply.getStatus() == AgiReply.SC_TRYING) { + return readReply(); } + return reply; } } diff --git a/src/main/java/org/asteriskjava/fastagi/internal/FastAgiWriter.java b/src/main/java/org/asteriskjava/fastagi/internal/FastAgiWriter.java index 031f89f04..8c144c1e9 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/FastAgiWriter.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/FastAgiWriter.java @@ -16,38 +16,33 @@ */ package org.asteriskjava.fastagi.internal; -import java.io.IOException; - import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiNetworkException; +import org.asteriskjava.fastagi.AgiWriter; import org.asteriskjava.fastagi.command.AgiCommand; import org.asteriskjava.util.SocketConnectionFacade; +import java.io.IOException; + /** * Default implementation of the AGIWriter interface. - * + * * @author srt * @version $Id$ */ -class FastAgiWriter implements AgiWriter -{ +class FastAgiWriter implements AgiWriter { private final SocketConnectionFacade socket; - FastAgiWriter(SocketConnectionFacade socket) - { + FastAgiWriter(SocketConnectionFacade socket) { this.socket = socket; } - public void sendCommand(AgiCommand command) throws AgiException - { - try - { + public void sendCommand(AgiCommand command) throws AgiException { + try { socket.write(command.buildCommand() + "\n"); socket.flush(); - } - catch (IOException e) - { + } catch (IOException e) { throw new AgiNetworkException( "Unable to send command to Asterisk: " + e.getMessage(), e); } diff --git a/src/main/java/org/asteriskjava/fastagi/internal/package.html b/src/main/java/org/asteriskjava/fastagi/internal/package.html index e6959c54c..aaf08fc28 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/package.html +++ b/src/main/java/org/asteriskjava/fastagi/internal/package.html @@ -1,28 +1,28 @@ - +

    Provides private implementations for interfaces defined in the - org.asteriskjava.fastagi package.

    + org.asteriskjava.fastagi package.

    - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/fastagi/package.html b/src/main/java/org/asteriskjava/fastagi/package.html index 3dd3a37a2..f5fb4a4ff 100644 --- a/src/main/java/org/asteriskjava/fastagi/package.html +++ b/src/main/java/org/asteriskjava/fastagi/package.html @@ -1,27 +1,27 @@ - +

    Provides an implementaion of Asterisk's FastAGI.

    - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/fastagi/reply/AgiReply.java b/src/main/java/org/asteriskjava/fastagi/reply/AgiReply.java index 4b8602f80..4b3e91519 100644 --- a/src/main/java/org/asteriskjava/fastagi/reply/AgiReply.java +++ b/src/main/java/org/asteriskjava/fastagi/reply/AgiReply.java @@ -16,8 +16,8 @@ */ package org.asteriskjava.fastagi.reply; -import java.util.List; import java.io.Serializable; +import java.util.List; /** * Reply received in response to an AgiCommand.

    @@ -25,13 +25,12 @@ * of an AgiCommand and - depending on the command sent - additional information * returned, for example the value of a variable requested by a * GetVariableCommand. - * - * @see org.asteriskjava.fastagi.command.AgiCommand + * * @author srt * @version $Id$ + * @see org.asteriskjava.fastagi.command.AgiCommand */ -public interface AgiReply extends Serializable -{ +public interface AgiReply extends Serializable { /** * Status code (100) indicating Asterisk needs to process the * AgiCommand and will report a final result code soon. @@ -75,28 +74,28 @@ public interface AgiReply extends Serializable /** * Returns the first line of the raw reply. - * + * * @return the first line of the raw reply. */ String getFirstLine(); /** * Returns a List containing the lines of the raw reply. - * + * * @return a List containing the lines of the raw reply. */ List getLines(); /** * Returns the return code (the result as int). - * + * * @return the return code or -1 if the result is not an int. */ int getResultCode(); /** * Returns the return code as character. - * + * * @return the return code as character. */ char getResultCodeAsChar(); @@ -104,7 +103,7 @@ public interface AgiReply extends Serializable /** * Returns the result, that is the part directly following the "result=" * string. - * + * * @return the result. */ String getResult(); @@ -119,7 +118,7 @@ public interface AgiReply extends Serializable *

  • 511 Command Not Permitted on a dead channel (since Asterisk 1.6) *
  • 520 Invalid command syntax *
- * + * * @return the status code. * @see #SC_TRYING * @see #SC_SUCCESS @@ -135,11 +134,11 @@ public interface AgiReply extends Serializable * endpos attribute indicating the frame where the playback was stopped. * This can be retrieved by calling getAttribute("endpos") on the * corresponding reply. - * + * * @param name the name of the attribute to retrieve. The name is case - * insensitive. + * insensitive. * @return the value of the attribute or null if it is not - * set. + * set. */ String getAttribute(String name); @@ -148,7 +147,7 @@ public interface AgiReply extends Serializable * The meaning of this property depends on the command sent. Sometimes it * contains a flag like "timeout" or "hangup" or - in case of the * GetVariableCommand - the value of the variable. - * + * * @return the text in the parenthesis or null if not set. */ String getExtra(); @@ -156,18 +155,18 @@ public interface AgiReply extends Serializable /** * Returns the synopsis of the command sent if Asterisk expected a different * syntax (getStatus() == SC_INVALID_COMMAND_SYNTAX). - * + * * @return the synopsis of the command sent, null if there - * were no syntax errors. + * were no syntax errors. */ String getSynopsis(); /** * Returns the usage of the command sent if Asterisk expected a different * syntax (getStatus() == SC_INVALID_COMMAND_SYNTAX). - * + * * @return the usage of the command sent, null if there were - * no syntax errors. + * no syntax errors. */ String getUsage(); } diff --git a/src/main/java/org/asteriskjava/fastagi/reply/package.html b/src/main/java/org/asteriskjava/fastagi/reply/package.html index 738721be9..7f310c491 100644 --- a/src/main/java/org/asteriskjava/fastagi/reply/package.html +++ b/src/main/java/org/asteriskjava/fastagi/reply/package.html @@ -1,29 +1,29 @@ - +

Provides a class that represents the reply that is received - from an Asterisk server in response to a command sent via - the FastAGI.

+ from an Asterisk server in response to a command sent via + the FastAGI.

- \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/live/AbstractAsteriskServerListener.java b/src/main/java/org/asteriskjava/live/AbstractAsteriskServerListener.java index 1caa62c67..2af37f138 100644 --- a/src/main/java/org/asteriskjava/live/AbstractAsteriskServerListener.java +++ b/src/main/java/org/asteriskjava/live/AbstractAsteriskServerListener.java @@ -19,21 +19,18 @@ /** * Empty implementation of the {@link org.asteriskjava.live.AsteriskServerListener} * interface. Use this class as a base class for your own listeners if you only want - * to implement a subset of the methods in {@link org.asteriskjava.live.AsteriskServerListener}. - * + * to implement a subset of the methods in {@link org.asteriskjava.live.AsteriskServerListener}. + * * @author srt * @version $Id$ * @since 0.3 */ -public abstract class AbstractAsteriskServerListener implements AsteriskServerListener -{ - public void onNewAsteriskChannel(AsteriskChannel channel) - { +public abstract class AbstractAsteriskServerListener implements AsteriskServerListener { + public void onNewAsteriskChannel(AsteriskChannel channel) { } - public void onNewMeetMeUser(MeetMeUser user) - { + public void onNewMeetMeUser(MeetMeUser user) { } } diff --git a/src/main/java/org/asteriskjava/live/AgentState.java b/src/main/java/org/asteriskjava/live/AgentState.java index 76b624baa..cee935137 100644 --- a/src/main/java/org/asteriskjava/live/AgentState.java +++ b/src/main/java/org/asteriskjava/live/AgentState.java @@ -18,13 +18,12 @@ /** * The lifecycle status of an {@link org.asteriskjava.live.AsteriskAgent}. - * - * @since 0.3.1 - * @author Patrick Breucking + * + * @author Patrick Breucking * @version $Id$ + * @since 0.3.1 */ -public enum AgentState -{ +public enum AgentState { /** * Agent isn't logged in. */ diff --git a/src/main/java/org/asteriskjava/live/AmaFlags.java b/src/main/java/org/asteriskjava/live/AmaFlags.java index eac1b5946..05dbff8fc 100644 --- a/src/main/java/org/asteriskjava/live/AmaFlags.java +++ b/src/main/java/org/asteriskjava/live/AmaFlags.java @@ -16,8 +16,7 @@ */ package org.asteriskjava.live; -public enum AmaFlags -{ +public enum AmaFlags { BILLING, DOCUMENTATION, OMIT, diff --git a/src/main/java/org/asteriskjava/live/AsteriskAgent.java b/src/main/java/org/asteriskjava/live/AsteriskAgent.java index c6407a125..7fa231b43 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskAgent.java +++ b/src/main/java/org/asteriskjava/live/AsteriskAgent.java @@ -23,32 +23,28 @@ *
    *
  • state
  • *
- * - *

- * - * @since 0.3.1 - * @author Patrick Breucking + * + * @author Patrick Breucking * @version $Id$ + * @since 0.3.1 */ -public interface AsteriskAgent extends LiveObject -{ +public interface AsteriskAgent extends LiveObject { String PROPERTY_STATE = "state"; /** * @return the name */ - public String getName(); + String getName(); /** * @return the agentId */ - public String getAgentId(); + String getAgentId(); /** * Returns the state of this agent. * * @return the state the state of this agent. */ - public AgentState getState(); - + AgentState getState(); } diff --git a/src/main/java/org/asteriskjava/live/AsteriskChannel.java b/src/main/java/org/asteriskjava/live/AsteriskChannel.java index e3f86a54b..06da80821 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskChannel.java +++ b/src/main/java/org/asteriskjava/live/AsteriskChannel.java @@ -16,6 +16,8 @@ */ package org.asteriskjava.live; +import org.asteriskjava.util.MixMonitorDirection; + import java.util.Date; import java.util.List; import java.util.Map; @@ -38,14 +40,14 @@ *
  • meetMeUser *
  • queueEntry *
  • parkedAt + *
  • parkingLot *
  • dtmfReceived *
  • dtmfSent * - * + * * @author srt */ -public interface AsteriskChannel extends LiveObject -{ +public interface AsteriskChannel extends LiveObject { String PROPERTY_ID = "id"; String PROPERTY_NAME = "name"; String PROPERTY_CALLER_ID = "callerId"; @@ -59,36 +61,43 @@ public interface AsteriskChannel extends LiveObject String PROPERTY_MEET_ME_USER = "meetMeUser"; String PROPERTY_QUEUE_ENTRY = "queueEntry"; String PROPERTY_PARKED_AT = "parkedAt"; + String PROPERTY_PARKING_LOT = "parkingLot"; String PROPERTY_DTMF_RECEIVED = "dtmfReceived"; String PROPERTY_DTMF_SENT = "dtmfSent"; + String PROPERTY_MONITORED = "monitored"; String VARIABLE_MONITOR_EXEC = "MONITOR_EXEC"; String VARIABLE_MONITOR_EXEC_ARGS = "MONITOR_EXEC_ARGS"; + /** + * Pseudo-variable to store {@link org.asteriskjava.manager.event.DialEvent#getDialStatus()} + */ + String VAR_AJ_DIAL_STATUS = "AJ_DIAL_STATUS"; + /** * Returns the unique id of this channel, for example "1099015093.165". - * + * * @return the unique id of this channel. */ String getId(); /** * Returns the name of this channel, for example "SIP/1310-20da". - * + * * @return the name of this channel. */ String getName(); /** * Returns the caller id of this channel. - * + * * @return the caller id of this channel. */ CallerId getCallerId(); /** * Returns the state of this channel. - * + * * @return the state of this channel. */ ChannelState getState(); @@ -98,37 +107,37 @@ public interface AsteriskChannel extends LiveObject *

    * For example you can use this method the check if this channel had been * answered: - * + * *

          * boolean answered = channel.wasInState(ChannelState.UP);
          * 
    - * + * * @param state the state to look for. * @return true if this channel was at least once in the - * given state; false otherwise. + * given state; false otherwise. * @since 0.3 */ boolean wasInState(ChannelState state); /** * Checks if this channel was busy. - * + * * @return true if this channel was busy; false - * otherwise. + * otherwise. * @since 0.3 */ boolean wasBusy(); /** * Returns the account code used to bill this channel. - * + * * @return the account code used to bill this channel. */ String getAccount(); /** * Returns the last visited dialplan entry. - * + * * @return the last visited dialplan entry. * @since 0.2 */ @@ -136,7 +145,7 @@ public interface AsteriskChannel extends LiveObject /** * Returns the first visited dialplan entry. - * + * * @return the first visited dialplan entry. * @since 0.2 */ @@ -144,7 +153,7 @@ public interface AsteriskChannel extends LiveObject /** * Returns a list of all visited dialplan entries. - * + * * @return a list of all visited dialplan entries. * @since 0.3 */ @@ -154,7 +163,7 @@ public interface AsteriskChannel extends LiveObject * Returns the date this channel has been created. *

    * This property is immutable. - * + * * @return the date this channel has been created. */ Date getDateOfCreation(); @@ -162,39 +171,39 @@ public interface AsteriskChannel extends LiveObject /** * Returns the date this channel has left the Asterisk server for example by * a hangup. - * + * * @return the date this channel has left the Asterisk server or - * null if this channel is still active. + * null if this channel is still active. * @since 0.3 */ Date getDateOfRemoval(); /** * Returns the reason for hangup. - * + * * @return the reason for hangup or null if the channel has - * not yet been hung up or no hangup cause is available for this - * type of channel. + * not yet been hung up or no hangup cause is available for this + * type of channel. * @since 0.3 */ HangupCause getHangupCause(); /** * Returns a textual representation of the reason for hangup. - * + * * @return the textual representation of the reason for hangup or - * null if the channel has not yet been hung up or no - * hangup cause is available for this type of channel. If no hangup - * cause is available an empty String may be returned, too. + * null if the channel has not yet been hung up or no + * hangup cause is available for this type of channel. If no hangup + * cause is available an empty String may be returned, too. * @since 0.3 */ String getHangupCauseText(); /** * Returns the call detail record for this channel. - * + * * @return the call detail record for this channel or null if - * none has (yet) been received. + * none has (yet) been received. */ CallDetailRecord getCallDetailRecord(); @@ -202,15 +211,15 @@ public interface AsteriskChannel extends LiveObject * Returns the channel that has been dialed by this channel most recently, * this is the destination channel that was created because this channel * dialed it. - * + * * @return the channel that has been dialed by this channel or - * null if none has been dialed. + * null if none has been dialed. */ AsteriskChannel getDialedChannel(); /** * Returns a list of all channels that have been dialed by this channel. - * + * * @return a list of all channels that have been dialed by this channel. */ List getDialedChannelHistory(); @@ -218,32 +227,41 @@ public interface AsteriskChannel extends LiveObject /** * Returns the channel that was dialing this channel, this is the source * channel that created this channel by dialing it. - * + * * @return the channel that was dialing this channel or null - * if none was dialing. + * if none was dialing. */ AsteriskChannel getDialingChannel(); + /** + * Returns the channel set that are dialing this channel, this is the source + * channel that created this channel by dialing it. + * + * @return the channel set that is dialing this channel or null + * if none was dialing. + */ + List getDialedChannels(); + /** * Returns the channel this channel is currently bridged with, if any. - * + * * @return the channel this channel is bridged with, or null - * if this channel is currently not bridged to another channel. + * if this channel is currently not bridged to another channel. */ AsteriskChannel getLinkedChannel(); /** * Returns a list of all channels this channel was briged with. - * + * * @return a list of all channels this channel was briged with. */ List getLinkedChannelHistory(); /** * Indicates if this channel was linked to another channel at least once. - * + * * @return true if this channel was linked to another channel - * at least once, false otherwise. + * at least once, false otherwise. * @since 0.2 */ boolean wasLinked(); @@ -251,10 +269,10 @@ public interface AsteriskChannel extends LiveObject /** * Returns the MeetMeUser associated with this channel if this channel is * currently taking part in a MeetMe conference. - * + * * @return the MeetMeUser associated with this channel or null - * if this channel is currently not taking part in a MeetMe - * conference. + * if this channel is currently not taking part in a MeetMe + * conference. */ MeetMeUser getMeetMeUser(); @@ -264,7 +282,7 @@ public interface AsteriskChannel extends LiveObject * @return the queue entry associated with this channel if any, null otherwise. */ AsteriskQueueEntry getQueueEntry(); - + /** * Return the extension to dial to pickup he channel of the parking if the channel is * currently parked. @@ -273,6 +291,13 @@ public interface AsteriskChannel extends LiveObject */ Extension getParkedAt(); + /** + * Return the name of the parkinglot where the channel is currently parked. + * + * @return the name of the parkinglot used to park, null if not currently parked. + */ + String getParkingLot(); + /** * Returns the channel variables as received by * {@link org.asteriskjava.manager.event.VarSetEvent VarSetEvents}.

    @@ -299,15 +324,23 @@ public interface AsteriskChannel extends LiveObject */ Character getDtmfSent(); + /** + * Return the actual MONITOR state. + * + * @return the actual Monitor state of this channel. + * @since 1.0.1 + */ + boolean isMonitored(); + /* Actions */ - + /** * Hangs up this channel. - * + * * @throws ManagerCommunicationException if the hangup action cannot be sent - * to Asterisk. - * @throws NoSuchChannelException if this channel had already been hung up - * before the hangup was sent. + * to Asterisk. + * @throws NoSuchChannelException if this channel had already been hung up + * before the hangup was sent. * @since 0.3 */ void hangup() throws ManagerCommunicationException, NoSuchChannelException; @@ -316,12 +349,12 @@ public interface AsteriskChannel extends LiveObject * Hangs up this channel using a given cause code. The cause code is mainly * used for Zap PRI channels where it makes Asterisk send a PRI DISCONNECT * message with the set CAUSE element to the switch. - * + * * @param cause the cause code to send. * @throws ManagerCommunicationException if the hangup action cannot be sent - * to Asterisk. - * @throws NoSuchChannelException if this channel had already been hung up - * before the hangup was sent. + * to Asterisk. + * @throws NoSuchChannelException if this channel had already been hung up + * before the hangup was sent. * @since 0.3 */ void hangup(HangupCause cause) throws ManagerCommunicationException, NoSuchChannelException; @@ -332,16 +365,16 @@ public interface AsteriskChannel extends LiveObject *

    * Time is counted from when you call setAbsoluteTimeout, not from the * beginning of the call. - * + * * @param seconds maximum duration of the call in seconds, 0 for unlimited - * call length. + * call length. * @throws ManagerCommunicationException if the absolute timeout action - * cannot be sent to Asterisk. - * @throws NoSuchChannelException if this channel had already been hung up - * before the absolute timeout was set. + * cannot be sent to Asterisk. + * @throws NoSuchChannelException if this channel had already been hung up + * before the absolute timeout was set. * @since 0.3 */ - //TODO exception when setting it to 0: NoSuchChannelException: Channel + //TODO exception when setting it to 0: NoSuchChannelException: Channel // 'SIP/248-0a02fcd0' is not available: No timeout specified void setAbsoluteTimeout(int seconds) throws ManagerCommunicationException, NoSuchChannelException; @@ -350,14 +383,14 @@ public interface AsteriskChannel extends LiveObject *

    * If this channel is linked to another channel, the linked channel is hung * up. - * - * @param context the destination context. - * @param exten the destination extension. + * + * @param context the destination context. + * @param exten the destination extension. * @param priority the destination priority. * @throws ManagerCommunicationException if the redirect action cannot be - * sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * the redirect was sent. + * sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * the redirect was sent. * @since 0.3 */ void redirect(String context, String exten, int priority) throws ManagerCommunicationException, NoSuchChannelException; @@ -368,14 +401,14 @@ public interface AsteriskChannel extends LiveObject *

    * If this channel is not linked to another channel only this channel is * redirected. - * - * @param context the destination context. - * @param exten the destination extension. + * + * @param context the destination context. + * @param exten the destination extension. * @param priority the destination priority. * @throws ManagerCommunicationException if the redirect action cannot be - * sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * the redirect was sent. + * sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * the redirect was sent. * @since 0.3 */ void redirectBothLegs(String context, String exten, int priority) throws ManagerCommunicationException, @@ -387,27 +420,27 @@ void redirectBothLegs(String context, String exten, int priority) throws Manager * Currently Asterisk does not support the retrieval of built-in variables * like EXTEN or CALLERIDNUM but only custom variables set via Asterisk's * Set command or via {@link #setVariable(String, String)}. - * + * * @param variable the name of the channel variable to return. * @return the value of the channel variable or null if it is - * not set. + * not set. * @throws ManagerCommunicationException if the get variable action cannot - * be sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * the variable was requested. + * be sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * the variable was requested. * @since 0.3 */ String getVariable(String variable) throws ManagerCommunicationException, NoSuchChannelException; /** * Sets the value of the given channel variable. - * + * * @param variable the name of the channel variable to set. - * @param value the value of the channel variable to set. + * @param value the value of the channel variable to set. * @throws ManagerCommunicationException if the set variable action cannot - * be sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * the variable was set. + * be sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * the variable was set. * @since 0.3 */ void setVariable(String variable, String value) throws ManagerCommunicationException, NoSuchChannelException; @@ -416,13 +449,13 @@ void redirectBothLegs(String context, String exten, int priority) throws Manager * Plays the given DTMF digit on this channel. *

    * Available since Asterisk 1.2.8 - * + * * @param digit the DTMF digit to play. * @throws ManagerCommunicationException if the play DTMF action cannot be - * sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * the DTMF digit was set. - * @throws IllegalArgumentException if the digit is null. + * sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * the DTMF digit was set. + * @throws IllegalArgumentException if the digit is null. * @since 0.3 */ void playDtmf(String digit) throws ManagerCommunicationException, NoSuchChannelException, IllegalArgumentException; @@ -433,14 +466,14 @@ void redirectBothLegs(String context, String exten, int priority) throws Manager * The format of the files is "wav", they are not mixed. *

    * The files are called filename-in.wav and filename-out.wav. - * + * * @param filename the basename of the files created in the monitor spool - * directory. If null the channel name (with - * slashed replaced by dashes) is used. + * directory. If null the channel name (with + * slashed replaced by dashes) is used. * @throws ManagerCommunicationException if the monitor action cannot be - * sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * starting monitoring. + * sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * starting monitoring. * @see #stopMonitoring() * @see #pauseMonitoring() * @since 0.3 @@ -453,16 +486,16 @@ void redirectBothLegs(String context, String exten, int priority) throws Manager * The files are not mixed. *

    * The files are called filename-in.format and filename-out.format. - * + * * @param filename the basename of the files created in the monitor spool - * directory. If null the channel name (with - * slashed replaced by dashes) is used. - * @param format the audio recording format. If null wav is - * used. + * directory. If null the channel name (with + * slashed replaced by dashes) is used. + * @param format the audio recording format. If null wav is + * used. * @throws ManagerCommunicationException if the monitor action cannot be - * sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * starting monitoring. + * sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * starting monitoring. * @see #stopMonitoring() * @see #pauseMonitoring() * @since 0.3 @@ -487,31 +520,31 @@ void redirectBothLegs(String context, String exten, int priority) throws Manager * spaces). *

    * Example: - * + * *

          *      AsteriskChannel c;
    -     *      
    +     *
          *      [...]
          *      c.setVariable(AsteriskChannel.VARIABLE_MONITOR_EXEC, "/usr/local/bin/2wav2mp3");
          *      c.startMonitoring("my-recording", "wav", true);
          * 
    - * + *

    * Side note: 2wav2mp3 is a nice script by Dietmar Zlabinger to mix the two * legs to a stero mp3 file, for details see * voip-info.org. - * + * * @param filename the basename of the file(s) created in the monitor spool - * directory. If null the channel name (with - * slashed replaced by dashes) is used. - * @param format the audio recording format. If null wav is - * used. - * @param mix true to mix input and output data together - * after recording is finished, false to not mix - * them. + * directory. If null the channel name (with + * slashed replaced by dashes) is used. + * @param format the audio recording format. If null wav is + * used. + * @param mix true to mix input and output data together + * after recording is finished, false to not mix + * them. * @throws ManagerCommunicationException if the monitor action cannot be - * sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * starting monitoring. + * sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * starting monitoring. * @see #VARIABLE_MONITOR_EXEC * @see #VARIABLE_MONITOR_EXEC_ARGS * @see #stopMonitoring() @@ -528,14 +561,14 @@ void startMonitoring(String filename, String format, boolean mix) throws Manager * ignored and a warning message is written to Asterisk's CLI. *

    * Use with care, this doesn't always seem to work. - * + * * @param filename the basename of the file(s) created in the monitor spool - * directory. + * directory. * @throws ManagerCommunicationException if the change monitor action cannot - * be sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * changing monitoring. - * @throws IllegalArgumentException if filename is null. + * be sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * changing monitoring. + * @throws IllegalArgumentException if filename is null. * @see #stopMonitoring() * @see #pauseMonitoring() * @since 0.3 @@ -548,11 +581,11 @@ void changeMonitoring(String filename) throws ManagerCommunicationException, NoS *

    * If the channel exists but is not currently monitored your request is * ignored. - * + * * @throws ManagerCommunicationException if the stop monitor action cannot - * be sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * stopping monitoring. + * be sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * stopping monitoring. * @see #startMonitoring(String) * @see #startMonitoring(String, String) * @see #startMonitoring(String, String, boolean) @@ -567,11 +600,11 @@ void changeMonitoring(String filename) throws ManagerCommunicationException, NoS * ignored. *

    * This method is available since Asterisk 1.4. - * + * * @throws ManagerCommunicationException if the pause monitor action cannot - * be sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * temporarily stopping monitoring. + * be sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * temporarily stopping monitoring. * @see #unpauseMonitoring() * @since 0.3 */ @@ -585,13 +618,50 @@ void changeMonitoring(String filename) throws ManagerCommunicationException, NoS * ignored. *

    * This method is available since Asterisk 1.4. - * - * @throws ManagerCommunicationException if the unpasue monitor action - * cannot be sent to Asterisk. - * @throws NoSuchChannelException if this channel had been hung up before - * re-enabling monitoring. + * + * @throws ManagerCommunicationException if the unpause monitor action + * cannot be sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * re-enabling monitoring. * @see #pauseMonitoring() * @since 0.3 */ void unpauseMonitoring() throws ManagerCommunicationException, NoSuchChannelException; + + + /** + * Temporarily stops monitoring this channel if this is monitored with MixMonitor. + *

    + * If the channel exists but is not currently monitored your request is + * ignored. + *

    + * + * @throws ManagerCommunicationException if the pause monitor action cannot + * be sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * temporarily stopping monitoring. + * @see #unPauseMixMonitor(org.asteriskjava.util.MixMonitorDirection) + * @since 1.0.0 + */ + void pauseMixMonitor(MixMonitorDirection direction) throws ManagerCommunicationException, NoSuchChannelException; + + + /** + * Re-enables monitoring this channel after calling + * {@link #pauseMixMonitor(org.asteriskjava.util.MixMonitorDirection)} ()} + * if this is monitored with MixMonitor + *

    + * If the channel exists but monitoring has not been paused your request is + * ignored. + *

    + * + * @throws ManagerCommunicationException if the unpause monitor action + * cannot be sent to Asterisk. + * @throws NoSuchChannelException if this channel had been hung up before + * re-enabling monitoring. + * @see #pauseMixMonitor(org.asteriskjava.util.MixMonitorDirection) + * @since 1.0.0 + */ + void unPauseMixMonitor(MixMonitorDirection direction) throws ManagerCommunicationException, NoSuchChannelException; + } diff --git a/src/main/java/org/asteriskjava/live/AsteriskQueue.java b/src/main/java/org/asteriskjava/live/AsteriskQueue.java index 6d83d4907..9393c6119 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskQueue.java +++ b/src/main/java/org/asteriskjava/live/AsteriskQueue.java @@ -23,10 +23,10 @@ * An Asterisk ACD queue. * * @author srt + * @author itaqua * @version $Id$ */ -public interface AsteriskQueue -{ +public interface AsteriskQueue { String STRATEGY_RINGALL = "ringall"; String STRATEGY_ROUNDROBIN = "roundrobin"; String STRATAGY_LEAST_RECENT = "leastrecent"; @@ -45,7 +45,7 @@ public interface AsteriskQueue /** * Returns the maximum number of people allowed to wait in this queue or 0 * for unlimited. - *

    + *
    * Corresponds to the maxlen option in Asterisk's * queues.conf. * @@ -55,7 +55,7 @@ public interface AsteriskQueue /** * Returns the strategy used for this queue. - *

    + *
    * Possible values are: *

      *
    • ringall
    • @@ -82,15 +82,15 @@ public interface AsteriskQueue /** * Returns the weight of this queue. - *

      + *
      * A queue can be assigned a 'weight' to ensure calls waiting in a higher * priority queue will deliver its calls first. Only delays the lower weight * queue's call if the member is also in the higher weight queue. - *

      + *
      * Available since Asterisk 1.2 * * @return the weight of this queue or null if not supported - * by your version of Asterisk. + * by your version of Asterisk. */ Integer getWeight(); @@ -134,4 +134,74 @@ public interface AsteriskQueue * @since 0.3 */ void removeAsteriskQueueListener(AsteriskQueueListener listener); + + /** + * Returns the number of abandoned calls. + * + * @return the number of abandoned calls. + * @author itaqua + */ + Integer getAbandoned(); + + /** + * Returns the ratio of calls answered within the specified service level per total completed + * calls (in percent). + * + * @return the ratio of calls answered within the specified service level per total completed + * calls (in percent). + * @author itaqua + */ + Double getServiceLevelPerf(); + + /** + * Returns the number of completed calls. + * + * @return the number of completed calls. + * @author itaqua + */ + Integer getCompleted(); + + /** + * Returns the current average talk time for this queue based on an exponential average. + * + * @return the current average talk time for this queue. + */ + Integer getTalkTime(); + + /** + * Returns the current average holdtime for this queue (in seconds). + * + * @return the current average holdtime for this queue (in seconds). + * @author itaqua + */ + Integer getHoldTime(); + + /** + * Returns the number of calls currently waiting in the queue. + * Is better to use get Waiting() + * + * @return the number of calls currently waiting in the queue. + * @author itaqua + * @see getWaiting() + */ + Integer getCalls(); + + /** + * Returns the number of calls currently waiting in the queue. + * More verbose Method than getCalls() + * + * @return the number of calls currently waiting in the queue. + * @author itaqua + */ + Integer getWaiting(); + + /** + * timestamp (miliseconds) of last update of this object + * + * @return + * @todo maybe change this to an immutable object + * @author itaqua + */ + long getLastUpdateMillis(); + } diff --git a/src/main/java/org/asteriskjava/live/AsteriskQueueEntry.java b/src/main/java/org/asteriskjava/live/AsteriskQueueEntry.java index b91688e7e..066a44d06 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskQueueEntry.java +++ b/src/main/java/org/asteriskjava/live/AsteriskQueueEntry.java @@ -13,8 +13,7 @@ * * @author gmi */ -public interface AsteriskQueueEntry extends LiveObject -{ +public interface AsteriskQueueEntry extends LiveObject { String PROPERTY_STATE = "state"; String PROPERTY_POSITION = "position"; String PROPERTY_REPORTED_POSITION = "reportedPosition"; @@ -36,7 +35,7 @@ public interface AsteriskQueueEntry extends LiveObject * member left when entering {@link QueueEntryState#LEFT}. * * @return the date this member left the Queue or - * null if the user did not yet leave. + * null if the user did not yet leave. */ Date getDateLeft(); diff --git a/src/main/java/org/asteriskjava/live/AsteriskQueueListener.java b/src/main/java/org/asteriskjava/live/AsteriskQueueListener.java index 0cee29a1d..27b1a3ee2 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskQueueListener.java +++ b/src/main/java/org/asteriskjava/live/AsteriskQueueListener.java @@ -8,8 +8,7 @@ * @author gmi * @since 0.3 */ -public interface AsteriskQueueListener -{ +public interface AsteriskQueueListener { /** * Called whenever an entry appears in the queue. * @@ -36,7 +35,7 @@ public interface AsteriskQueueListener * @param entry */ void onEntryServiceLevelExceeded(AsteriskQueueEntry entry); - + /** * Called whenever a new member is added to the queue. * diff --git a/src/main/java/org/asteriskjava/live/AsteriskQueueMember.java b/src/main/java/org/asteriskjava/live/AsteriskQueueMember.java index e38851285..c88dbe7df 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskQueueMember.java +++ b/src/main/java/org/asteriskjava/live/AsteriskQueueMember.java @@ -27,14 +27,16 @@ *

    * * @author Patrick Breucking + * @author itaqua * @version $Id$ * @since 0.3.1 */ -public interface AsteriskQueueMember extends LiveObject -{ +public interface AsteriskQueueMember extends LiveObject { String PROPERTY_STATE = "state"; String PROPERTY_PENALTY = "penalty"; String PROPERTY_PAUSED = "paused"; + String PROPERTY_CALLSTAKEN = "callsTaken"; + String PROPERTY_LASTCALL = "lastCall"; /** * Returns the location of this member. @@ -63,7 +65,8 @@ public interface AsteriskQueueMember extends LiveObject * @return paused true is this queue member is paused, false otherwise. * @deprecated as of 1.0.0. Use {@link #isPaused()} instead. */ - @Deprecated boolean getPaused(); + @Deprecated + boolean getPaused(); /** * Returns whether this member is currently paused.. @@ -99,30 +102,30 @@ public interface AsteriskQueueMember extends LiveObject * statically defined in queues.conf. * * @return "dynamic" if the added member is a dynamic queue member, "static" - * if the added member is a static queue member. + * if the added member is a static queue member. * @since 1.0.0 */ - public String getMembership(); + String getMembership(); /** * Convenience method that checks whether this member has been statically * defined in queues.conf. * * @return true if this member has been statically defined in - * queues.conf, false otherwise. + * queues.conf, false otherwise. * @since 1.0.0 */ - public boolean isStatic(); + boolean isStatic(); /** * Convenience method that checks whether this member has been dynamically * added by the QueueAdd command. * * @return true if this member has been dynamically added by - * the QueueAdd command, false otherwise. + * the QueueAdd command, false otherwise. * @since 1.0.0 */ - public boolean isDynamic(); + boolean isDynamic(); /** * Returns the penalty of this member. @@ -143,4 +146,20 @@ public interface AsteriskQueueMember extends LiveObject * @since 1.0.0 */ void setPenalty(int penalty) throws IllegalArgumentException, ManagerCommunicationException, InvalidPenaltyException; + + /** + * get the timestamp when the last call was terminated + * + * @return + * @author itaqua + */ + Long getLastCall(); + + /** + * total calls taken + * + * @return + * @author itaqua + */ + Integer getCallsTaken(); } diff --git a/src/main/java/org/asteriskjava/live/AsteriskServer.java b/src/main/java/org/asteriskjava/live/AsteriskServer.java index 7ebabaa22..6e2e2c13e 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskServer.java +++ b/src/main/java/org/asteriskjava/live/AsteriskServer.java @@ -16,386 +16,384 @@ */ package org.asteriskjava.live; -import java.util.Collection; -import java.util.Map; -import java.util.List; - +import org.asteriskjava.config.ConfigFile; import org.asteriskjava.manager.ManagerConnection; +import org.asteriskjava.manager.ManagerEventListener; import org.asteriskjava.manager.action.OriginateAction; -import org.asteriskjava.config.ConfigFile; + +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; /** * The AsteriskServer is built on top of the * {@link org.asteriskjava.manager.ManagerConnection} and is an attempt to - * simplify interaction with Asterisk by abstracting the interface.

    You - * will certainly have less freedom using AsteriskServer but it will make life - * easier for easy things (like originating a call or getting a list of open - * channels).

    AsteriskServer is still in an early state of development. So, - * when using AsteriskServer be aware that it might change in the future. - * + * simplify interaction with Asterisk by abstracting the interface.
    + * You will certainly have less freedom using AsteriskServer but it will make + * life easier for easy things (like originating a call or getting a list of + * open channels).
    + * AsteriskServer is still in an early state of development. So, when using + * AsteriskServer be aware that it might change in the future. + * * @author srt * @version $Id$ */ -public interface AsteriskServer -{ - /** - * Returns the underlying ManagerConnection.

    - * Unlike the methods operating on the manager connection this method does not implicitly initialize the - * connection. Thus you can use this method to add custom - * {@linkplain org.asteriskjava.manager.ManagerEventListener ManagerEventListeners} before the connection - * to the Asterisk server is established. If you want to ensure that the connection is established call - * {@link #initialize()}. - * +public interface AsteriskServer { + /** + * Returns the underlying ManagerConnection. + *

    + * Unlike the methods operating on the manager connection this method does + * not implicitly initialize the connection. Thus you can use this method to + * add custom {@linkplain org.asteriskjava.manager.ManagerEventListener + * ManagerEventListeners} before the connection to the Asterisk server is + * established. If you want to ensure that the connection is established + * call {@link #initialize()}. + * * @return the underlying ManagerConnection. */ ManagerConnection getManagerConnection(); /** * Generates an outgoing channel. - * @param originateAction the action that contains parameters for the originate + * + * @param originateAction the action that contains parameters for the + * originate * @return the generated channel - * @throws NoSuchChannelException if the channel is not available on the - * Asterisk server, for example because you used "SIP/1310" and 1310 - * is not a valid SIP user, the SIP channel module hasn't been - * loaded or the SIP or IAX peer is not registered currently. + * @throws NoSuchChannelException if the channel is not available on the + * Asterisk server, for example because you used "SIP/1310" and + * 1310 is not a valid SIP user, the SIP channel module hasn't + * been loaded or the SIP or IAX peer is not registered + * currently. * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - public AsteriskChannel originate(OriginateAction originateAction) throws ManagerCommunicationException, NoSuchChannelException; - + AsteriskChannel originate(OriginateAction originateAction) + throws ManagerCommunicationException, NoSuchChannelException; + /** * Asynchronously generates an outgoing channel. - * @param originateAction the action that contains parameters for the originate - * @param cb callback to inform about the result + * + * @param originateAction the action that contains parameters for the + * originate + * @param cb callback to inform about the result * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - public void originateAsync(OriginateAction originateAction, OriginateCallback cb) throws ManagerCommunicationException; - + void originateAsync(OriginateAction originateAction, OriginateCallback cb) throws ManagerCommunicationException; + /** * Generates an outgoing channel to a dialplan entry (extension, context, * priority). - * - * @param channel channel name to call, for example "SIP/1310". - * @param context context to connect to - * @param exten extension to connect to + * + * @param channel channel name to call, for example "SIP/1310". + * @param context context to connect to + * @param exten extension to connect to * @param priority priority to connect to - * @param timeout how long to wait for the channel to be answered before its - * considered to have failed (in ms) + * @param timeout how long to wait for the channel to be answered before its + * considered to have failed (in ms) * @return the generated channel - * @throws NoSuchChannelException if the channel is not available on the - * Asterisk server, for example because you used "SIP/1310" and 1310 - * is not a valid SIP user, the SIP channel module hasn't been - * loaded or the SIP or IAX peer is not registered currently. + * @throws NoSuchChannelException if the channel is not available on the + * Asterisk server, for example because you used "SIP/1310" and + * 1310 is not a valid SIP user, the SIP channel module hasn't + * been loaded or the SIP or IAX peer is not registered + * currently. * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - AsteriskChannel originateToExtension(String channel, String context, - String exten, int priority, long timeout) - throws ManagerCommunicationException, NoSuchChannelException; + AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) + throws ManagerCommunicationException, NoSuchChannelException; /** * Generates an outgoing channel to a dialplan entry (extension, context, * priority) and sets an optional map of channel variables. - * - * @param channel channel name to call, for example "SIP/1310". - * @param context context to connect to - * @param exten extension to connect to - * @param priority priority to connect to - * @param timeout how long to wait for the channel to be answered before its - * considered to have failed (in ms) - * @param callerId callerId to use for the outgoing channel, may be - * null. + * + * @param channel channel name to call, for example "SIP/1310". + * @param context context to connect to + * @param exten extension to connect to + * @param priority priority to connect to + * @param timeout how long to wait for the channel to be answered before its + * considered to have failed (in ms) + * @param callerId callerId to use for the outgoing channel, may be + * null. * @param variables channel variables to set, may be null. * @return the generated channel - * @throws NoSuchChannelException if the channel is not available on the - * Asterisk server, for example because you used "SIP/1310" and 1310 - * is not a valid SIP user, the SIP channel module hasn't been - * loaded or the SIP or IAX peer is not registered currently. + * @throws NoSuchChannelException if the channel is not available on the + * Asterisk server, for example because you used "SIP/1310" and + * 1310 is not a valid SIP user, the SIP channel module hasn't + * been loaded or the SIP or IAX peer is not registered + * currently. * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - AsteriskChannel originateToExtension(String channel, String context, - String exten, int priority, long timeout, CallerId callerId, - Map variables) - throws ManagerCommunicationException, NoSuchChannelException; + AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout, + CallerId callerId, Map variables) throws ManagerCommunicationException, NoSuchChannelException; /** * Generates an outgoing channel to an application. - * - * @param channel channel name to call, for example "SIP/1310". + * + * @param channel channel name to call, for example "SIP/1310". * @param application application to connect to, for example "MeetMe" - * @param data data to pass to the application, for example "1000|d", may be - * null. - * @param timeout how long to wait for the channel to be answered before its - * considered to have failed (in ms) + * @param data data to pass to the application, for example "1000|d", may be + * null. + * @param timeout how long to wait for the channel to be answered before its + * considered to have failed (in ms) * @return the generated channel - * @throws NoSuchChannelException if the channel is not available on the - * Asterisk server, for example because you used "SIP/1310" and 1310 - * is not a valid SIP user, the SIP channel module hasn't been - * loaded or the SIP or IAX peer is not registered currently. + * @throws NoSuchChannelException if the channel is not available on the + * Asterisk server, for example because you used "SIP/1310" and + * 1310 is not a valid SIP user, the SIP channel module hasn't + * been loaded or the SIP or IAX peer is not registered + * currently. * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - AsteriskChannel originateToApplication(String channel, String application, - String data, long timeout) throws ManagerCommunicationException, - NoSuchChannelException; + AsteriskChannel originateToApplication(String channel, String application, String data, long timeout) + throws ManagerCommunicationException, NoSuchChannelException; /** * Generates an outgoing channel to an application and sets an optional map * of channel variables. - * - * @param channel channel name to call, for example "SIP/1310". + * + * @param channel channel name to call, for example "SIP/1310". * @param application application to connect to, for example "MeetMe" - * @param data data to pass to the application, for example "1000|d", may be - * null. - * @param timeout how long to wait for the channel to be answered before its - * considered to have failed (in ms) - * @param callerId callerId to use for the outgoing channel, may be - * null. - * @param variables channel variables to set, may be null. + * @param data data to pass to the application, for example "1000|d", may be + * null. + * @param timeout how long to wait for the channel to be answered before its + * considered to have failed (in ms) + * @param callerId callerId to use for the outgoing channel, may be + * null. + * @param variables channel variables to set, may be null. * @return the generated channel - * @throws NoSuchChannelException if the channel is not available on the - * Asterisk server, for example because you used "SIP/1310" and 1310 - * is not a valid SIP user, the SIP channel module hasn't been - * loaded or the SIP or IAX peer is not registered currently. + * @throws NoSuchChannelException if the channel is not available on the + * Asterisk server, for example because you used "SIP/1310" and + * 1310 is not a valid SIP user, the SIP channel module hasn't + * been loaded or the SIP or IAX peer is not registered + * currently. * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - AsteriskChannel originateToApplication(String channel, String application, - String data, long timeout, CallerId callerId, - Map variables) - throws ManagerCommunicationException, NoSuchChannelException; + AsteriskChannel originateToApplication(String channel, String application, String data, long timeout, CallerId callerId, + Map variables) throws ManagerCommunicationException, NoSuchChannelException; /** * Asynchronously generates an outgoing channel to a dialplan entry * (extension, context, priority). - * - * @param channel channel name to call, for example "SIP/1310". - * @param context context to connect to - * @param exten extension to connect to + * + * @param channel channel name to call, for example "SIP/1310". + * @param context context to connect to + * @param exten extension to connect to * @param priority priority to connect to - * @param timeout how long to wait for the channel to be answered before its - * considered to have failed (in ms) + * @param timeout how long to wait for the channel to be answered before its + * considered to have failed (in ms) * @param callback callback to inform about the result * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - void originateToExtensionAsync(String channel, String context, - String exten, int priority, long timeout, OriginateCallback callback) - throws ManagerCommunicationException; + void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, + OriginateCallback callback) throws ManagerCommunicationException; /** * Asynchronously generates an outgoing channel to a dialplan entry * (extension, context, priority) and sets an optional map of channel * variables. - * - * @param channel channel name to call, for example "SIP/1310". - * @param context context to connect to - * @param exten extension to connect to - * @param priority priority to connect to - * @param timeout how long to wait for the channel to be answered before its - * considered to have failed (in ms) - * @param callerId callerId to use for the outgoing channel, may be - * null. + * + * @param channel channel name to call, for example "SIP/1310". + * @param context context to connect to + * @param exten extension to connect to + * @param priority priority to connect to + * @param timeout how long to wait for the channel to be answered before its + * considered to have failed (in ms) + * @param callerId callerId to use for the outgoing channel, may be + * null. * @param variables channel variables to set, may be null. - * @param callback callback to inform about the result + * @param callback callback to inform about the result * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - void originateToExtensionAsync(String channel, String context, - String exten, int priority, long timeout, CallerId callerId, - Map variables, OriginateCallback callback) - throws ManagerCommunicationException; + void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, + CallerId callerId, Map variables, OriginateCallback callback) + throws ManagerCommunicationException; /** * Asynchronously generates an outgoing channel to an application. - * - * @param channel channel name to call, for example "SIP/1310". + * + * @param channel channel name to call, for example "SIP/1310". * @param application application to connect to, for example "MeetMe" - * @param data data to pass to the application, for example "1000|d", may be - * null. - * @param timeout how long to wait for the channel to be answered before its - * considered to have failed (in ms) - * @param callback callback to inform about the result + * @param data data to pass to the application, for example "1000|d", may be + * null. + * @param timeout how long to wait for the channel to be answered before its + * considered to have failed (in ms) + * @param callback callback to inform about the result * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - void originateToApplicationAsync(String channel, String application, - String data, long timeout, OriginateCallback callback) - throws ManagerCommunicationException; + void originateToApplicationAsync(String channel, String application, String data, long timeout, + OriginateCallback callback) throws ManagerCommunicationException; /** * Asynchronously generates an outgoing channel to an application and sets * an optional map of channel variables. - * - * @param channel channel name to call, for example "SIP/1310". + * + * @param channel channel name to call, for example "SIP/1310". * @param application application to connect to, for example "MeetMe" - * @param data data to pass to the application, for example "1000|d", may be - * null. - * @param timeout how long to wait for the channel to be answered before its - * considered to have failed (in ms) - * @param callerId callerId to use for the outgoing channel, may be - * null. - * @param variables channel variables to set, may be null. - * @param callback callback to inform about the result + * @param data data to pass to the application, for example "1000|d", may be + * null. + * @param timeout how long to wait for the channel to be answered before its + * considered to have failed (in ms) + * @param callerId callerId to use for the outgoing channel, may be + * null. + * @param variables channel variables to set, may be null. + * @param callback callback to inform about the result * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ - void originateToApplicationAsync(String channel, String application, - String data, long timeout, CallerId callerId, - Map variables, OriginateCallback callback) - throws ManagerCommunicationException; + void originateToApplicationAsync(String channel, String application, String data, long timeout, CallerId callerId, + Map variables, OriginateCallback callback) throws ManagerCommunicationException; /** * Returns the active channels of the Asterisk server. - * + * * @return a Collection of active channels. * @throws ManagerCommunicationException if there is a problem communication - * with Asterisk + * with Asterisk */ - Collection getChannels() - throws ManagerCommunicationException; + Collection getChannels() throws ManagerCommunicationException; /** * Returns a channel by its name. - * + * * @param name name of the channel to return - * @return the channel with the given name or null if there - * is no such channel. + * @return the channel with the given name or null if there is + * no such channel. * @throws ManagerCommunicationException if there is a problem communication - * with Asterisk + * with Asterisk */ - AsteriskChannel getChannelByName(String name) - throws ManagerCommunicationException; + AsteriskChannel getChannelByName(String name) throws ManagerCommunicationException; /** * Returns a channel by its unique id. - * + * * @param id the unique id of the channel to return * @return the channel with the given unique id or null if - * there is no such channel. + * there is no such channel. * @throws ManagerCommunicationException if there is a problem communication - * with Asterisk + * with Asterisk */ - AsteriskChannel getChannelById(String id) - throws ManagerCommunicationException; + AsteriskChannel getChannelById(String id) throws ManagerCommunicationException; /** * Returns the acitve MeetMe rooms on the Asterisk server. - * + * * @return a Collection of MeetMeRooms * @throws ManagerCommunicationException if there is a problem communication - * with Asterisk + * with Asterisk */ - Collection getMeetMeRooms() - throws ManagerCommunicationException; + Collection getMeetMeRooms() throws ManagerCommunicationException; /** * Returns the MeetMe room with the given number, if the room does not yet * exist a new {@link MeetMeRoom} object is created. - * + * * @param roomNumber the number of the room to return * @return the MeetMe room with the given number. * @throws ManagerCommunicationException if there is a problem communication - * with Asterisk + * with Asterisk */ - MeetMeRoom getMeetMeRoom(String roomNumber) - throws ManagerCommunicationException; + MeetMeRoom getMeetMeRoom(String roomNumber) throws ManagerCommunicationException; /** * Returns the queues served by the Asterisk server. - * + * * @return a Collection of queues. * @throws ManagerCommunicationException if there is a problem communication - * with Asterisk + * with Asterisk */ Collection getQueues() throws ManagerCommunicationException; /** * Return the agents, registered at Asterisk server. (Consider remarks for * {@link AsteriskAgent}) - * + * * @return a Collection of agents * @throws ManagerCommunicationException if there is a problem communication - * with Asterisk + * with Asterisk */ Collection getAgents() throws ManagerCommunicationException; /** - * Returns the exact version string of this Asterisk server.

    This - * typically looks like "Asterisk 1.2.9.1-BRIstuffed-0.3.0-PRE-1q built by - * root @ pbx0 on a i686 running Linux on 2006-06-20 20:21:30 UTC". - * + * Returns the exact version string of this Asterisk server.
    + * This typically looks like "Asterisk 1.2.9.1-BRIstuffed-0.3.0-PRE-1q built + * by root @ pbx0 on a i686 running Linux on 2006-06-20 20:21:30 UTC". + * * @return the version of this Asterisk server * @throws ManagerCommunicationException if the version cannot be retrieved - * from Asterisk + * from Asterisk * @since 0.2 */ String getVersion() throws ManagerCommunicationException; /** - * Returns the CVS revision of a given source file of this Asterisk server. - *

    For example getVersion("app_meetme.c") may return {1, 102} for CVS - * revision "1.102".

    Note that this feature is not available with - * Asterisk 1.0.x.

    You can use this feature if you need to write - * applications that behave different depending on specific modules being - * available in a specific version or not. - * + * Returns the CVS revision of a given source file of this + * Asterisk server.
    + * For example getVersion("app_meetme.c") may return {1, 102} for + * CVS revision "1.102".
    + * Note that this feature is not available with Asterisk 1.0.x.
    + * You can use this feature if you need to write applications that behave + * different depending on specific modules being available in a specific + * version or not. + * * @param file the file for which to get the version like "app_meetme.c" * @return the CVS revision of the file, or null if that file - * is not part of the Asterisk instance you are connected to (maybe - * due to a module that provides it has not been loaded) or if you - * are connected to an Astersion 1.0.x + * is not part of the Asterisk instance you are connected to (maybe + * due to a module that provides it has not been loaded) or if you + * are connected to an Astersion 1.0.x * @throws ManagerCommunicationException if the version cannot be retrieved - * from Asterisk + * from Asterisk * @since 0.2 */ int[] getVersion(String file) throws ManagerCommunicationException; /** * Returns the value of the given global variable. - * + * * @param variable the name of the global variable to return. * @return the value of the global variable or null if it is - * not set. + * not set. * @throws ManagerCommunicationException if the get variable action cannot - * be sent to Asterisk. + * be sent to Asterisk. * @since 0.3 */ - String getGlobalVariable(String variable) - throws ManagerCommunicationException; + String getGlobalVariable(String variable) throws ManagerCommunicationException; /** * Sets the value of the given global variable. - * + * * @param variable the name of the global variable to set. - * @param value the value of the global variable to set. + * @param value the value of the global variable to set. * @throws ManagerCommunicationException if the set variable action cannot - * be sent to Asterisk. + * be sent to Asterisk. * @since 0.3 */ - void setGlobalVariable(String variable, String value) - throws ManagerCommunicationException; + void setGlobalVariable(String variable, String value) throws ManagerCommunicationException; /** * Returns a collection of all voicemailboxes configured for this Asterisk * server with the number of new and old messages they contain. - * + * * @return a collection of all voicemailboxes configured for this Asterisk - * server + * server * @throws ManagerCommunicationException if the voicemailboxes can't be - * retrieved. + * retrieved. * @since 0.3 */ Collection getVoicemailboxes() throws ManagerCommunicationException; /** * Executes a command line interface (CLI) command. - * + * * @param command the command to execute, for example "sip show peers". * @return a List containing strings representing the lines returned by the - * CLI command. + * CLI command. * @throws ManagerCommunicationException if the command can't be executed. * @see org.asteriskjava.manager.action.CommandAction * @since 0.3 @@ -403,47 +401,57 @@ void setGlobalVariable(String variable, String value) List executeCliCommand(String command) throws ManagerCommunicationException; /** - * Checks whether a module is currently loaded.

    + * Checks whether a module is currently loaded. + *

    * Available since Asterisk 1.6 * - * @param module name of the module to load (with out without the ".so" extension). - * @return true if the module is currently loaded, false otherwise. + * @param module name of the module to load (with out without the ".so" + * extension). + * @return true if the module is currently loaded, + * false otherwise. * @throws ManagerCommunicationException if the module can't be checked. */ boolean isModuleLoaded(String module) throws ManagerCommunicationException; /** - * Loads a module or subsystem

    + * Loads a module or subsystem + *

    * Available since Asterisk 1.6 * - * @param module name of the module to load (including ".so" extension) or subsystem name. + * @param module name of the module to load (including ".so" extension) or + * subsystem name. * @throws ManagerCommunicationException if the module cannot be loaded. * @since 1.0.0 */ void loadModule(String module) throws ManagerCommunicationException; /** - * Unloads a module or subsystem.

    + * Unloads a module or subsystem. + *

    * Available since Asterisk 1.6 * - * @param module name of the module to unload (including ".so" extension) or subsystem name. + * @param module name of the module to unload (including ".so" extension) or + * subsystem name. * @throws ManagerCommunicationException if the module cannot be unloaded. * @since 1.0.0 */ void unloadModule(String module) throws ManagerCommunicationException; /** - * Reloads a module or subsystem.

    + * Reloads a module or subsystem. + *

    * Available since Asterisk 1.6 * - * @param module name of the module to reload (including ".so" extension) or subsystem name. + * @param module name of the module to reload (including ".so" extension) or + * subsystem name. * @throws ManagerCommunicationException if the module cannot be reloaded. * @since 1.0.0 */ void reloadModule(String module) throws ManagerCommunicationException; /** - * Reloads all currently loaded modules.

    + * Reloads all currently loaded modules. + *

    * Available since Asterisk 1.6 * * @throws ManagerCommunicationException if the modules cannot be reloaded. @@ -461,31 +469,99 @@ void setGlobalVariable(String variable, String value) ConfigFile getConfig(String filename) throws ManagerCommunicationException; /** - * Adds a listener to this AsteriskServer.

    + * Adds a listener to this AsteriskServer.
    * If this server is not yet connected it will be implicitly connected. - * + * * @param listener the listener to add. * @throws ManagerCommunicationException if the server is not yet connected - * and the connection or initialization fails. + * and the connection or initialization fails. */ void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException; /** * Removes a listener from this Asterisk server. - * + * * @param listener the listener to remove. */ void removeAsteriskServerListener(AsteriskServerListener listener); + /** + * Checks whether the listener is already registered with this Asterisk + * server + * + * @param listener the listener to check + * @return true, if the listener is already registered. + */ + boolean isAsteriskServerListening(AsteriskServerListener listener); + + /** + * The chainListener allows a listener to receive manager events after they + * have been processed by the AsteriskServer. If the AsteriskServer is + * handling messages using the asyncEventHandling then these messages will + * also be async. You would use the chainListener if you are processing raw + * events and using the AJ live ChannelManager. If you don't use the chain + * listener then you can't be certain that a channel name passed in a raw + * event will match the channel name held by the live Channel Manager. By + * chaining events you can be certain that events such as channel Rename + * events have been processed by the live ChannelManager before you receive + * an event and as such the names will always match. Whilst name matching is + * not always critical (as you should be matching by the channels unique id) + * the channel name does also contain state information (Zombie, Masq) in + * these cases it can be critical that you have the same name otherwise your + * state information will be out of date. + */ + void addChainListener(ManagerEventListener chainListener); + + /** + * remove the chain listener. + * + * @param chainListener + */ + void removeChainListener(ManagerEventListener chainListener); + /** * Closes the connection to this server. */ void shutdown(); - /** - * Opens the connection to this server. - * - * @throws ManagerCommunicationException if login fails - */ - void initialize() throws ManagerCommunicationException; + /** + * Opens the connection to this server. + * + * @throws ManagerCommunicationException if login fails + */ + void initialize() throws ManagerCommunicationException; + + /** + * get Asterisk Queue by name + * + * @param queueName Name of the queue to retrieve + * @return + * @author itaqua + */ + AsteriskQueue getQueueByName(String queueName); + + /** + * List of Queues Objects updated after certain date + * + * @param date + * @return + * @author itaqua + */ + List getQueuesUpdatedAfter(Date date); + + /** + * every time we get an event of a queue we reload the information about it + * from the Asterisk Server + * + * @author itaqua + */ + void forceQueuesMonitor(boolean force); + + /** + * Check if the Queue Information is forced + * + * @return + * @author itaqua + */ + boolean isQueuesMonitorForced(); } diff --git a/src/main/java/org/asteriskjava/live/AsteriskServerListener.java b/src/main/java/org/asteriskjava/live/AsteriskServerListener.java index 16166bd75..4cbf1ee92 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskServerListener.java +++ b/src/main/java/org/asteriskjava/live/AsteriskServerListener.java @@ -1,7 +1,5 @@ package org.asteriskjava.live; -import org.asteriskjava.live.internal.AsteriskAgentImpl; - /** * You can register an AsteriskServerListener with an * {@link org.asteriskjava.live.AsteriskServer} to be notified about new @@ -10,37 +8,36 @@ * Usually it is better to extend {@link AbstractAsteriskServerListener} than to * implement this interface directly as additonal methods will probably be added * in future versions of Asterisk-Java. - * + * * @author srt * @version $Id$ * @since 0.3 */ -public interface AsteriskServerListener -{ +public interface AsteriskServerListener { /** * Called whenever a new channel appears on the Asterisk server. - * + * * @param channel the new channel. */ void onNewAsteriskChannel(AsteriskChannel channel); /** * Called whenever a user joins a {@link MeetMeRoom}. - * + * * @param user the user that joined. */ void onNewMeetMeUser(MeetMeUser user); /** * Called whenever a new agent will be registered at Asterisk server. - * + * * @param agent */ - void onNewAgent(AsteriskAgentImpl agent); - + void onNewAgent(AsteriskAgent agent); + /** - * Called whenever a queue entry ( ~ wapper over channel) joins a {@link AstriskQueue}. - * + * Called whenever a queue entry ( ~ wapper over channel) joins a {@link org.asteriskjava.live.AsteriskQueue}. + * * @param entry the queue entry that joined. */ void onNewQueueEntry(AsteriskQueueEntry entry); diff --git a/src/main/java/org/asteriskjava/live/CallDetailRecord.java b/src/main/java/org/asteriskjava/live/CallDetailRecord.java index 46caef42f..53d2d7eaa 100644 --- a/src/main/java/org/asteriskjava/live/CallDetailRecord.java +++ b/src/main/java/org/asteriskjava/live/CallDetailRecord.java @@ -20,14 +20,13 @@ /** * Represents an Asterisk Call Detail Record (CDR). - * - * @see org.asteriskjava.manager.event.CdrEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.CdrEvent * @since 0.3 */ -public interface CallDetailRecord -{ +public interface CallDetailRecord { AsteriskChannel getChannel(); AsteriskChannel getDestinationChannel(); @@ -35,7 +34,7 @@ public interface CallDetailRecord /** * Returns the account number that is usually used to identify the party to bill for the call.

    * Corresponds to CDR field accountcode. - * + * * @return the account number. */ String getAccountCode(); @@ -45,7 +44,7 @@ public interface CallDetailRecord /** * Returns the destination context.

    * Corresponds to CDR field dcontext. - * + * * @return the destination context. */ String getDestinationContext(); @@ -53,7 +52,7 @@ public interface CallDetailRecord /** * Returns the destination extension.

    * Corresponds to CDR field dst. - * + * * @return the destination extension. */ String getDestinationExtension(); @@ -69,7 +68,7 @@ public interface CallDetailRecord /** * Returns the total time (in seconds) the caller spent in the system from dial to hangup.

    * Corresponds to CDR field duration. - * + * * @return the total time in system in seconds. */ Integer getDuration(); @@ -77,7 +76,7 @@ public interface CallDetailRecord /** * Returns the total time (in seconds) the call was up from answer to hangup.

    * Corresponds to CDR field billsec. - * + * * @return the total time in call in seconds. */ Integer getBillableSeconds(); @@ -85,7 +84,7 @@ public interface CallDetailRecord /** * Returns the last application if appropriate, for example "VoiceMail".

    * Corresponds to CDR field lastapp. - * + * * @return the last application or null if not avaialble. */ String getLastApplication(); @@ -93,7 +92,7 @@ public interface CallDetailRecord /** * Returns the last application's data (arguments), for example "s1234".

    * Corresponds to CDR field lastdata. - * + * * @return the last application's data or null if not avaialble. */ String getLastAppData(); @@ -101,7 +100,7 @@ public interface CallDetailRecord /** * Returns the user-defined field as set by Set(CDR(userfield)=Value).

    * Corresponds to CDR field userfield. - * + * * @return the user-defined field. */ String getUserField(); diff --git a/src/main/java/org/asteriskjava/live/CallerId.java b/src/main/java/org/asteriskjava/live/CallerId.java index 62ca9efde..216eccc67 100644 --- a/src/main/java/org/asteriskjava/live/CallerId.java +++ b/src/main/java/org/asteriskjava/live/CallerId.java @@ -22,15 +22,14 @@ /** * Represents a Caller*ID containing name and number. - *

    + *
    * Objects of this type are immutable. * * @author srt * @version $Id$ * @since 0.3 */ -public class CallerId implements Serializable -{ +public class CallerId implements Serializable { /** * Serial version identifier. */ @@ -44,8 +43,7 @@ public class CallerId implements Serializable * @param name the Caller*ID name. * @param number the Caller*ID number. */ - public CallerId(String name, String number) - { + public CallerId(String name, String number) { this.name = (AstUtil.isNull(name)) ? null : name; this.number = (AstUtil.isNull(number)) ? null : number; } @@ -55,8 +53,7 @@ public CallerId(String name, String number) * * @return the Caller*ID name. */ - public String getName() - { + public String getName() { return name; } @@ -65,8 +62,7 @@ public String getName() * * @return the Caller*ID number. */ - public String getNumber() - { + public String getNumber() { return number; } @@ -78,8 +74,7 @@ public String getNumber() * @return the corresponding CallerId object which is never null. * @see AstUtil#parseCallerId(String) */ - public static CallerId valueOf(String s) - { + public static CallerId valueOf(String s) { final String[] parsedCallerId; parsedCallerId = AstUtil.parseCallerId(s); @@ -91,24 +86,20 @@ public static CallerId valueOf(String s) * "Some Name" <1234>. */ @Override - public String toString() - { + public String toString() { final StringBuilder sb; sb = new StringBuilder(); - if (name != null) - { + if (name != null) { sb.append("\""); sb.append(name); sb.append("\""); - if (number != null) - { + if (number != null) { sb.append(" "); } } - if (number != null) - { + if (number != null) { sb.append("<"); sb.append(number); sb.append(">"); @@ -117,25 +108,20 @@ public String toString() } @Override - public boolean equals(Object o) - { - if (this == o) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) - { + if (o == null || getClass() != o.getClass()) { return false; } CallerId callerId = (CallerId) o; - if (name != null ? !name.equals(callerId.name) : callerId.name != null) - { + if (name != null ? !name.equals(callerId.name) : callerId.name != null) { return false; } - if (number != null ? !number.equals(callerId.number) : callerId.number != null) - { + if (number != null ? !number.equals(callerId.number) : callerId.number != null) { return false; } @@ -143,8 +129,7 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (number != null ? number.hashCode() : 0); return result; diff --git a/src/main/java/org/asteriskjava/live/ChannelState.java b/src/main/java/org/asteriskjava/live/ChannelState.java index 0394a5cac..a27f4b2bd 100644 --- a/src/main/java/org/asteriskjava/live/ChannelState.java +++ b/src/main/java/org/asteriskjava/live/ChannelState.java @@ -22,12 +22,11 @@ * The lifecycle status of an {@link org.asteriskjava.live.AsteriskChannel}. *
    * Defined in channel.c function ast_state2str. - * + * * @author srt * @version $Id$ */ -public enum ChannelState -{ +public enum ChannelState { /** * Channel is down and available. * This is the initial state of the channel when it is not yet in use. @@ -91,8 +90,7 @@ public enum ChannelState * * @param status the numerical status code. */ - ChannelState(int status) - { + ChannelState(int status) { this.status = status; } @@ -101,8 +99,7 @@ public enum ChannelState * * @return the numerical status code. */ - public int getStatus() - { + public int getStatus() { return status; } @@ -113,17 +110,13 @@ public int getStatus() * @param status integer representation of the status. * @return corresponding ChannelState object or null if none matches. */ - public static ChannelState valueOf(Integer status) - { - if (status == null) - { + public static ChannelState valueOf(Integer status) { + if (status == null) { return null; } - for (ChannelState tmp : ChannelState.values()) - { - if (tmp.getStatus() == status) - { + for (ChannelState tmp : ChannelState.values()) { + if (tmp.getStatus() == status) { return tmp; } } diff --git a/src/main/java/org/asteriskjava/live/ChannelStateHistoryEntry.java b/src/main/java/org/asteriskjava/live/ChannelStateHistoryEntry.java index f07a85327..746e12a45 100644 --- a/src/main/java/org/asteriskjava/live/ChannelStateHistoryEntry.java +++ b/src/main/java/org/asteriskjava/live/ChannelStateHistoryEntry.java @@ -26,8 +26,7 @@ * @version $Id$ * @since 0.3 */ -public class ChannelStateHistoryEntry implements Serializable -{ +public class ChannelStateHistoryEntry implements Serializable { /** * Serial version identifier. */ @@ -41,8 +40,7 @@ public class ChannelStateHistoryEntry implements Serializable * @param date the date the channel entered the state. * @param state the state the channel entered. */ - public ChannelStateHistoryEntry(Date date, ChannelState state) - { + public ChannelStateHistoryEntry(Date date, ChannelState state) { this.date = date; this.state = state; } @@ -52,8 +50,7 @@ public ChannelStateHistoryEntry(Date date, ChannelState state) * * @return the date the channel entered the state. */ - public Date getDate() - { + public Date getDate() { return date; } @@ -62,14 +59,12 @@ public Date getDate() * * @return the state the channel entered. */ - public ChannelState getState() - { + public ChannelState getState() { return state; } @Override - public String toString() - { + public String toString() { final StringBuilder sb; sb = new StringBuilder("ChannelStateHistoryEntry["); diff --git a/src/main/java/org/asteriskjava/live/DefaultAsteriskServer.java b/src/main/java/org/asteriskjava/live/DefaultAsteriskServer.java index 7b7aba35c..0d919c280 100644 --- a/src/main/java/org/asteriskjava/live/DefaultAsteriskServer.java +++ b/src/main/java/org/asteriskjava/live/DefaultAsteriskServer.java @@ -16,15 +16,17 @@ */ package org.asteriskjava.live; -import java.util.Collection; -import java.util.Map; -import java.util.List; - +import org.asteriskjava.config.ConfigFile; import org.asteriskjava.live.internal.AsteriskServerImpl; import org.asteriskjava.manager.DefaultManagerConnection; import org.asteriskjava.manager.ManagerConnection; +import org.asteriskjava.manager.ManagerEventListener; import org.asteriskjava.manager.action.OriginateAction; -import org.asteriskjava.config.ConfigFile; + +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; /** * Default implementation of the AsteriskServer interface. @@ -33,8 +35,7 @@ * @version $Id$ * @see org.asteriskjava.live.AsteriskServer */ -public class DefaultAsteriskServer implements AsteriskServer -{ +public class DefaultAsteriskServer implements AsteriskServer { private final AsteriskServerImpl impl; /** @@ -43,9 +44,8 @@ public class DefaultAsteriskServer implements AsteriskServer * {@link #setManagerConnection(ManagerConnection)} before you can use this * AsteriskServer. */ - public DefaultAsteriskServer() - { - impl = new AsteriskServerImpl(); + public DefaultAsteriskServer() { + this.impl = new AsteriskServerImpl(); } /** @@ -56,11 +56,10 @@ public DefaultAsteriskServer() * @param username the username to use for login * @param password the password to use for login */ - public DefaultAsteriskServer(String hostname, String username, String password) - { + public DefaultAsteriskServer(String hostname, String username, String password) { final ManagerConnection connection; connection = createManagerConnection(hostname, 0, username, password); - impl = new AsteriskServerImpl(connection); + this.impl = new AsteriskServerImpl(connection); } /** @@ -73,15 +72,13 @@ public DefaultAsteriskServer(String hostname, String username, String password) * @param username the username to use for login * @param password the password to use for login */ - public DefaultAsteriskServer(String hostname, int port, String username, String password) - { + public DefaultAsteriskServer(String hostname, int port, String username, String password) { final ManagerConnection connection; connection = createManagerConnection(hostname, port, username, password); - impl = new AsteriskServerImpl(connection); + this.impl = new AsteriskServerImpl(connection); } - protected DefaultManagerConnection createManagerConnection(String hostname, int port, String username, String password) - { + protected DefaultManagerConnection createManagerConnection(String hostname, int port, String username, String password) { DefaultManagerConnection dmc; dmc = new DefaultManagerConnection(hostname, port, username, password); return dmc; @@ -93,224 +90,207 @@ protected DefaultManagerConnection createManagerConnection(String hostname, int * @param eventConnection the ManagerConnection to use for receiving events * from Asterisk. */ - public DefaultAsteriskServer(ManagerConnection eventConnection) - { - impl = new AsteriskServerImpl(eventConnection); + public DefaultAsteriskServer(ManagerConnection eventConnection) { + this.impl = new AsteriskServerImpl(eventConnection); } /** * Determines if queue status is retrieved at startup. If you don't need * queue information and still run Asterisk 1.0.x you can set this to * true to circumvent the startup delay caused by the missing - * QueueStatusComplete event. - *

    + * QueueStatusComplete event.
    * Default is false. * * @param skipQueues true to skip queue initialization, * false to not skip. * @since 0.2 */ - public void setSkipQueues(boolean skipQueues) - { - impl.setSkipQueues(skipQueues); + public void setSkipQueues(boolean skipQueues) { + this.impl.setSkipQueues(skipQueues); } - public void setManagerConnection(ManagerConnection eventConnection) - { - impl.setManagerConnection(eventConnection); + public void setManagerConnection(ManagerConnection eventConnection) { + this.impl.setManagerConnection(eventConnection); } - public void initialize() throws ManagerCommunicationException - { - impl.initialize(); + public void initialize() throws ManagerCommunicationException { + this.impl.initialize(); } /* Implementation of the AsteriskServer interface */ - public ManagerConnection getManagerConnection() - { - return impl.getManagerConnection(); + public ManagerConnection getManagerConnection() { + return this.impl.getManagerConnection(); + } + + public AsteriskChannel originate(OriginateAction originateAction) + throws ManagerCommunicationException, NoSuchChannelException { + return this.impl.originate(originateAction); + } + + public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) + throws ManagerCommunicationException, NoSuchChannelException { + return this.impl.originateToExtension(channel, context, exten, priority, timeout); } - - public AsteriskChannel originate(OriginateAction originateAction) throws ManagerCommunicationException, NoSuchChannelException - { - return impl.originate(originateAction); - } + public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout, + CallerId callerId, Map variables) throws ManagerCommunicationException, NoSuchChannelException { + return this.impl.originateToExtension(channel, context, exten, priority, timeout, callerId, variables); + } + + public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout) + throws ManagerCommunicationException, NoSuchChannelException { + return this.impl.originateToApplication(channel, application, data, timeout); + } + + public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout, + CallerId callerId, Map variables) throws ManagerCommunicationException, NoSuchChannelException { + return this.impl.originateToApplication(channel, application, data, timeout, callerId, variables); + } + + public void originateAsync(OriginateAction originateAction, OriginateCallback cb) throws ManagerCommunicationException { + this.impl.originateAsync(originateAction, cb); + } - public AsteriskChannel originateToExtension(String channel, String context, - String exten, int priority, long timeout) - throws ManagerCommunicationException, NoSuchChannelException - { - return impl.originateToExtension(channel, context, exten, priority, timeout); + public void originateToApplicationAsync(String channel, String application, String data, long timeout, CallerId callerId, + Map variables, OriginateCallback cb) throws ManagerCommunicationException { + this.impl.originateToApplicationAsync(channel, application, data, timeout, callerId, variables, cb); } - public AsteriskChannel originateToExtension(String channel, String context, - String exten, int priority, long timeout, CallerId callerId, - Map variables) - throws ManagerCommunicationException, NoSuchChannelException - { - return impl.originateToExtension(channel, context, exten, priority, timeout, callerId, variables); + public void originateToApplicationAsync(String channel, String application, String data, long timeout, + OriginateCallback cb) throws ManagerCommunicationException { + this.impl.originateToApplicationAsync(channel, application, data, timeout, cb); } - public AsteriskChannel originateToApplication(String channel, - String application, String data, long timeout) - throws ManagerCommunicationException, NoSuchChannelException - { - return impl.originateToApplication(channel, application, data, timeout); + public void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, + CallerId callerId, Map variables, OriginateCallback cb) throws ManagerCommunicationException { + this.impl.originateToExtensionAsync(channel, context, exten, priority, timeout, callerId, variables, cb); } - public AsteriskChannel originateToApplication(String channel, - String application, String data, long timeout, CallerId callerId, - Map variables) - throws ManagerCommunicationException, NoSuchChannelException - { - return impl.originateToApplication(channel, application, data, timeout, callerId, variables); + public void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, + OriginateCallback cb) throws ManagerCommunicationException { + this.impl.originateToExtensionAsync(channel, context, exten, priority, timeout, cb); } - - public void originateAsync(OriginateAction originateAction, - OriginateCallback cb) throws ManagerCommunicationException - { - impl.originateAsync(originateAction, cb); - } - public void originateToApplicationAsync(String channel, String application, - String data, long timeout, CallerId callerId, - Map variables, OriginateCallback cb) - throws ManagerCommunicationException - { - impl.originateToApplicationAsync(channel, application, data, timeout, callerId, variables, cb); + public Collection getChannels() throws ManagerCommunicationException { + return this.impl.getChannels(); } - public void originateToApplicationAsync(String channel, String application, - String data, long timeout, OriginateCallback cb) - throws ManagerCommunicationException - { - impl.originateToApplicationAsync(channel, application, data, timeout, cb); + public AsteriskChannel getChannelByName(String name) throws ManagerCommunicationException { + return this.impl.getChannelByName(name); } - public void originateToExtensionAsync(String channel, String context, - String exten, int priority, long timeout, CallerId callerId, - Map variables, OriginateCallback cb) - throws ManagerCommunicationException - { - impl.originateToExtensionAsync(channel, context, exten, priority, timeout, callerId, variables, cb); + public AsteriskChannel getChannelById(String id) throws ManagerCommunicationException { + return this.impl.getChannelById(id); } - public void originateToExtensionAsync(String channel, String context, - String exten, int priority, long timeout, OriginateCallback cb) - throws ManagerCommunicationException - { - impl.originateToExtensionAsync(channel, context, exten, priority, timeout, cb); + public Collection getMeetMeRooms() throws ManagerCommunicationException { + return this.impl.getMeetMeRooms(); } - public Collection getChannels() throws ManagerCommunicationException - { - return impl.getChannels(); + public MeetMeRoom getMeetMeRoom(String name) throws ManagerCommunicationException { + return this.impl.getMeetMeRoom(name); } - public AsteriskChannel getChannelByName(String name) throws ManagerCommunicationException - { - return impl.getChannelByName(name); + public Collection getQueues() throws ManagerCommunicationException { + return this.impl.getQueues(); } - public AsteriskChannel getChannelById(String id) throws ManagerCommunicationException - { - return impl.getChannelById(id); + public String getVersion() throws ManagerCommunicationException { + return this.impl.getVersion(); } - public Collection getMeetMeRooms() throws ManagerCommunicationException - { - return impl.getMeetMeRooms(); + public int[] getVersion(String file) throws ManagerCommunicationException { + return this.impl.getVersion(file); } - public MeetMeRoom getMeetMeRoom(String name) throws ManagerCommunicationException - { - return impl.getMeetMeRoom(name); + public String getGlobalVariable(String variable) throws ManagerCommunicationException { + return this.impl.getGlobalVariable(variable); } - public Collection getQueues() throws ManagerCommunicationException - { - return impl.getQueues(); + public void setGlobalVariable(String variable, String value) throws ManagerCommunicationException { + this.impl.setGlobalVariable(variable, value); } - public String getVersion() throws ManagerCommunicationException - { - return impl.getVersion(); + public Collection getVoicemailboxes() throws ManagerCommunicationException { + return this.impl.getVoicemailboxes(); } - public int[] getVersion(String file) throws ManagerCommunicationException - { - return impl.getVersion(file); + public List executeCliCommand(String command) throws ManagerCommunicationException { + return this.impl.executeCliCommand(command); } - public String getGlobalVariable(String variable) throws ManagerCommunicationException - { - return impl.getGlobalVariable(variable); + public boolean isModuleLoaded(String module) throws ManagerCommunicationException { + return this.impl.isModuleLoaded(module); } - public void setGlobalVariable(String variable, String value) throws ManagerCommunicationException - { - impl.setGlobalVariable(variable, value); + public ConfigFile getConfig(String filename) throws ManagerCommunicationException { + return this.impl.getConfig(filename); } - public Collection getVoicemailboxes() throws ManagerCommunicationException - { - return impl.getVoicemailboxes(); + public void reloadAllModules() throws ManagerCommunicationException { + this.impl.reloadAllModules(); } - public List executeCliCommand(String command) throws ManagerCommunicationException - { - return impl.executeCliCommand(command); + public void reloadModule(String module) throws ManagerCommunicationException { + this.impl.reloadModule(module); } - public boolean isModuleLoaded(String module) throws ManagerCommunicationException - { - return impl.isModuleLoaded(module); + public void unloadModule(String module) throws ManagerCommunicationException { + this.impl.unloadModule(module); } - public ConfigFile getConfig(String filename) throws ManagerCommunicationException - { - return impl.getConfig(filename); + public void loadModule(String module) throws ManagerCommunicationException { + this.impl.loadModule(module); } - public void reloadAllModules() throws ManagerCommunicationException - { - impl.reloadAllModules(); + public void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException { + this.impl.addAsteriskServerListener(listener); } - public void reloadModule(String module) throws ManagerCommunicationException - { - impl.reloadModule(module); + public void removeAsteriskServerListener(AsteriskServerListener listener) { + this.impl.removeAsteriskServerListener(listener); } - public void unloadModule(String module) throws ManagerCommunicationException - { - impl.unloadModule(module); + public boolean isAsteriskServerListening(AsteriskServerListener listener) { + return this.impl.isAsteriskServerListening(listener); } - public void loadModule(String module) throws ManagerCommunicationException - { - impl.loadModule(module); + public void shutdown() { + this.impl.shutdown(); } - public void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException - { - impl.addAsteriskServerListener(listener); + public Collection getAgents() throws ManagerCommunicationException { + return this.impl.getAgents(); } - public void removeAsteriskServerListener(AsteriskServerListener listener) - { - impl.removeAsteriskServerListener(listener); + public AsteriskQueue getQueueByName(String queueName) { + return impl.getQueueByName(queueName); } - public void shutdown() - { - impl.shutdown(); + @Override + public List getQueuesUpdatedAfter(Date date) { + return impl.getQueuesUpdatedAfter(date); } - public Collection getAgents() throws ManagerCommunicationException - { - return impl.getAgents(); + @Override + public void forceQueuesMonitor(boolean force) { + impl.forceQueuesMonitor(force); + } + + @Override + public boolean isQueuesMonitorForced() { + return impl.isQueuesMonitorForced(); + } + + @Override + public void addChainListener(ManagerEventListener chainListener) { + this.impl.addChainListener(chainListener); + } + + @Override + public void removeChainListener(ManagerEventListener chainListener) { + this.impl.removeChainListener(chainListener); + } } diff --git a/src/main/java/org/asteriskjava/live/DialedChannelHistoryEntry.java b/src/main/java/org/asteriskjava/live/DialedChannelHistoryEntry.java index a542e7598..a240d3bdf 100644 --- a/src/main/java/org/asteriskjava/live/DialedChannelHistoryEntry.java +++ b/src/main/java/org/asteriskjava/live/DialedChannelHistoryEntry.java @@ -25,8 +25,7 @@ * @version $Id$ * @since 0.3 */ -public class DialedChannelHistoryEntry -{ +public class DialedChannelHistoryEntry { private final Date date; private final AsteriskChannel channel; @@ -36,8 +35,7 @@ public class DialedChannelHistoryEntry * @param date the date the channel was dialed. * @param channel the channel that has been dialed. */ - public DialedChannelHistoryEntry(Date date, AsteriskChannel channel) - { + public DialedChannelHistoryEntry(Date date, AsteriskChannel channel) { this.date = date; this.channel = channel; } @@ -47,8 +45,7 @@ public DialedChannelHistoryEntry(Date date, AsteriskChannel channel) * * @return the date the channel was dialed. */ - public Date getDate() - { + public Date getDate() { return date; } @@ -57,14 +54,12 @@ public Date getDate() * * @return the channel that has been dialed. */ - public AsteriskChannel getChannel() - { + public AsteriskChannel getChannel() { return channel; } @Override - public String toString() - { + public String toString() { final StringBuilder sb; sb = new StringBuilder("DialedChannelHistoryEntry["); diff --git a/src/main/java/org/asteriskjava/live/Disposition.java b/src/main/java/org/asteriskjava/live/Disposition.java index 6823897c1..d71ed3ec0 100644 --- a/src/main/java/org/asteriskjava/live/Disposition.java +++ b/src/main/java/org/asteriskjava/live/Disposition.java @@ -16,11 +16,10 @@ */ package org.asteriskjava.live; -public enum Disposition -{ +public enum Disposition { NO_ANSWER, FAILED, BUSY, ANSWERED, UNKNOWN -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/live/Extension.java b/src/main/java/org/asteriskjava/live/Extension.java index f403d2eda..58c22f745 100644 --- a/src/main/java/org/asteriskjava/live/Extension.java +++ b/src/main/java/org/asteriskjava/live/Extension.java @@ -18,8 +18,7 @@ import java.io.Serializable; -public class Extension implements Serializable -{ +public class Extension implements Serializable { /** * Serial version identifier. */ @@ -35,8 +34,7 @@ public class Extension implements Serializable * @param extension * @param priority */ - public Extension(String context, String extension, Integer priority) - { + public Extension(String context, String extension, Integer priority) { this(context, extension, priority, null, null); } @@ -48,8 +46,7 @@ public Extension(String context, String extension, Integer priority) * @param appData */ public Extension(String context, String extension, - Integer priority, String application, String appData) - { + Integer priority, String application, String appData) { this.context = context; this.extension = extension; this.priority = priority; @@ -57,37 +54,31 @@ public Extension(String context, String extension, this.appData = appData; } - public String getContext() - { + public String getContext() { return context; } - public String getExtension() - { + public String getExtension() { return extension; } - public Integer getPriority() - { + public Integer getPriority() { return priority; } - public String getApplication() - { + public String getApplication() { return application; } - public String getAppData() - { + public String getAppData() { return appData; } @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; - sb = new StringBuffer("Extension["); + sb = new StringBuilder("Extension["); sb.append("context='").append(getContext()).append("',"); sb.append("extension='").append(getExtension()).append("',"); sb.append("priority='").append(getPriority()).append("',"); diff --git a/src/main/java/org/asteriskjava/live/ExtensionHistoryEntry.java b/src/main/java/org/asteriskjava/live/ExtensionHistoryEntry.java index 4f496c108..a5baca7bb 100644 --- a/src/main/java/org/asteriskjava/live/ExtensionHistoryEntry.java +++ b/src/main/java/org/asteriskjava/live/ExtensionHistoryEntry.java @@ -26,8 +26,7 @@ * @version $Id$ * @since 0.3 */ -public class ExtensionHistoryEntry implements Serializable -{ +public class ExtensionHistoryEntry implements Serializable { /** * Serial version identifier. */ @@ -41,8 +40,7 @@ public class ExtensionHistoryEntry implements Serializable * @param date the date the extension has been visited. * @param extension the extension that has been visited. */ - public ExtensionHistoryEntry(Date date, Extension extension) - { + public ExtensionHistoryEntry(Date date, Extension extension) { this.date = date; this.extension = extension; } @@ -52,8 +50,7 @@ public ExtensionHistoryEntry(Date date, Extension extension) * * @return the date the extension has been visited. */ - public Date getDate() - { + public Date getDate() { return date; } @@ -62,14 +59,12 @@ public Date getDate() * * @return the extension that has been visited. */ - public Extension getExtension() - { + public Extension getExtension() { return extension; } @Override - public String toString() - { + public String toString() { final StringBuilder sb; sb = new StringBuilder(100); diff --git a/src/main/java/org/asteriskjava/live/HangupCause.java b/src/main/java/org/asteriskjava/live/HangupCause.java index dc7608a42..c8c81ae91 100644 --- a/src/main/java/org/asteriskjava/live/HangupCause.java +++ b/src/main/java/org/asteriskjava/live/HangupCause.java @@ -26,19 +26,23 @@ * @author srt * @version $Id$ */ -public enum HangupCause -{ +public enum HangupCause { AST_CAUSE_UNALLOCATED(1), AST_CAUSE_NO_ROUTE_TRANSIT_NET(2), AST_CAUSE_NO_ROUTE_DESTINATION(3), + AST_CAUSE_MISDIALLED_TRUNK_PREFIX(5), AST_CAUSE_CHANNEL_UNACCEPTABLE(6), AST_CAUSE_CALL_AWARDED_DELIVERED(7), + AST_CAUSE_NUMBER_PORTED_NOT_HERE(14), AST_CAUSE_NORMAL_CLEARING(16), AST_CAUSE_USER_BUSY(17), AST_CAUSE_NO_USER_RESPONSE(18), AST_CAUSE_NO_ANSWER(19), + AST_CAUSE_SUBSCRIBER_ABSENT(20), AST_CAUSE_CALL_REJECTED(21), AST_CAUSE_NUMBER_CHANGED(22), + AST_CAUSE_REDIRECTED_TO_NEW_DESTINATION(23), + AST_CAUSE_ANSWERED_ELSEWHERE(26), AST_CAUSE_DESTINATION_OUT_OF_ORDER(27), AST_CAUSE_INVALID_NUMBER_FORMAT(28), AST_CAUSE_FACILITY_REJECTED(29), @@ -83,13 +87,11 @@ public enum HangupCause AST_CAUSE_NOTDEFINED(0), AST_CAUSE_NOSUCHDRIVER(AST_CAUSE_CHAN_NOT_IMPLEMENTED); - private HangupCause(int code) - { + HangupCause(int code) { this.code = code; } - private HangupCause(HangupCause cause) - { + HangupCause(HangupCause cause) { this.code = cause.code; } @@ -99,8 +101,7 @@ private HangupCause(HangupCause cause) * * @return the numeric cause code. */ - public int getCode() - { + public int getCode() { return code; } @@ -110,15 +111,12 @@ public int getCode() * * @param code the numeric cause code. * @return the corresponding HangupCode enum or - * null if there is no such HangupCause. + * null if there is no such HangupCause. */ - public static synchronized HangupCause getByCode(int code) - { - if (causes == null) - { - causes = new HashMap(); - for (HangupCause cause : values()) - { + public static synchronized HangupCause getByCode(int code) { + if (causes == null) { + causes = new HashMap<>(); + for (HangupCause cause : values()) { causes.put(cause.code, cause); } } @@ -127,10 +125,8 @@ public static synchronized HangupCause getByCode(int code) } @Override - public String toString() - { - if (name().startsWith("AST_CAUSE_")) - { + public String toString() { + if (name().startsWith("AST_CAUSE_")) { return name().substring(10); } return name(); diff --git a/src/main/java/org/asteriskjava/live/InvalidPenaltyException.java b/src/main/java/org/asteriskjava/live/InvalidPenaltyException.java index 341b321ce..9c37eb4b2 100644 --- a/src/main/java/org/asteriskjava/live/InvalidPenaltyException.java +++ b/src/main/java/org/asteriskjava/live/InvalidPenaltyException.java @@ -22,8 +22,7 @@ * @author srt * @version $Id$ */ -public class InvalidPenaltyException extends LiveException -{ +public class InvalidPenaltyException extends LiveException { /** * Serial version identifier. */ @@ -34,8 +33,7 @@ public class InvalidPenaltyException extends LiveException * * @param message the message */ - public InvalidPenaltyException(String message) - { + public InvalidPenaltyException(String message) { super(message); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/live/LinkedChannelHistoryEntry.java b/src/main/java/org/asteriskjava/live/LinkedChannelHistoryEntry.java index 3b93cda86..525f750db 100644 --- a/src/main/java/org/asteriskjava/live/LinkedChannelHistoryEntry.java +++ b/src/main/java/org/asteriskjava/live/LinkedChannelHistoryEntry.java @@ -25,8 +25,7 @@ * @version $Id$ * @since 0.3 */ -public class LinkedChannelHistoryEntry -{ +public class LinkedChannelHistoryEntry { private final Date dateLinked; private Date dateUnlinked; private final AsteriskChannel channel; @@ -37,8 +36,7 @@ public class LinkedChannelHistoryEntry * @param dateLinked the date the channel was linked. * @param channel the channel that has been linked. */ - public LinkedChannelHistoryEntry(Date dateLinked, AsteriskChannel channel) - { + public LinkedChannelHistoryEntry(Date dateLinked, AsteriskChannel channel) { this.dateLinked = dateLinked; this.channel = channel; } @@ -48,8 +46,7 @@ public LinkedChannelHistoryEntry(Date dateLinked, AsteriskChannel channel) * * @return the date the channel was linked. */ - public Date getDateLinked() - { + public Date getDateLinked() { return dateLinked; } @@ -58,8 +55,7 @@ public Date getDateLinked() * * @return the date the channel was unlinked. */ - public Date getDateUnlinked() - { + public Date getDateUnlinked() { return dateUnlinked; } @@ -68,8 +64,7 @@ public Date getDateUnlinked() * * @param dateUnlinked the date the channel was unlinked. */ - public void setDateUnlinked(Date dateUnlinked) - { + public void setDateUnlinked(Date dateUnlinked) { this.dateUnlinked = dateUnlinked; } @@ -78,14 +73,12 @@ public void setDateUnlinked(Date dateUnlinked) * * @return the channel that has been linked. */ - public AsteriskChannel getChannel() - { + public AsteriskChannel getChannel() { return channel; } @Override - public String toString() - { + public String toString() { final StringBuilder sb; sb = new StringBuilder(100); diff --git a/src/main/java/org/asteriskjava/live/LiveException.java b/src/main/java/org/asteriskjava/live/LiveException.java index 1f095eedd..34ab0fa77 100644 --- a/src/main/java/org/asteriskjava/live/LiveException.java +++ b/src/main/java/org/asteriskjava/live/LiveException.java @@ -18,12 +18,11 @@ /** * Base class for exceptions thrown by the live package. - * + * * @author srt * @version $Id$ */ -public abstract class LiveException extends RuntimeException -{ +public abstract class LiveException extends RuntimeException { /** * Serial version identifier. */ @@ -31,22 +30,20 @@ public abstract class LiveException extends RuntimeException /** * Creates a new instance with the given message. - * + * * @param message the message */ - protected LiveException(String message) - { + protected LiveException(String message) { super(message); } /** * Creates a new instance with the given message and cause. - * + * * @param message the message - * @param cause the cause + * @param cause the cause */ - protected LiveException(String message, Throwable cause) - { + protected LiveException(String message, Throwable cause) { super(message, cause); } } diff --git a/src/main/java/org/asteriskjava/live/LiveObject.java b/src/main/java/org/asteriskjava/live/LiveObject.java index cc0e87321..a956e3a8e 100644 --- a/src/main/java/org/asteriskjava/live/LiveObject.java +++ b/src/main/java/org/asteriskjava/live/LiveObject.java @@ -24,16 +24,15 @@ * Allows you to retrieve the {@link org.asteriskjava.live.AsteriskServer} this * live object belongs to and provides support for * {@link java.beans.PropertyChangeEvent}s. - * + * * @author srt * @version $Id$ * @since 0.3 */ -public interface LiveObject -{ +public interface LiveObject { /** * Returns the AsteriskServer this live object belongs to. - * + * * @return the AsteriskServer this live object belongs to. */ AsteriskServer getServer(); @@ -41,7 +40,7 @@ public interface LiveObject /** * Adds a PropertyChangeListener that is notified whenever a property value * changes. - * + * * @param listener listener to notify */ void addPropertyChangeListener(PropertyChangeListener listener); @@ -49,9 +48,9 @@ public interface LiveObject /** * Adds a PropertyChangeListener that is notified whenever a given property * value changes. - * + * * @param propertyName property to observe - * @param listener listener to notify + * @param listener listener to notify * @see #addPropertyChangeListener(PropertyChangeListener) */ void addPropertyChangeListener(String propertyName, PropertyChangeListener listener); @@ -59,7 +58,7 @@ public interface LiveObject /** * Removes the given PropertyChangeListener that was added by calling * {@link #addPropertyChangeListener(PropertyChangeListener)}. - * + * * @param listener listener to remove */ void removePropertyChangeListener(PropertyChangeListener listener); @@ -67,9 +66,16 @@ public interface LiveObject /** * Removes the given PropertyChangeListener that was added by calling * {@link #addPropertyChangeListener(String, PropertyChangeListener)}. - * + * * @param propertyName property that is observed - * @param listener listener to remove + * @param listener listener to remove */ void removePropertyChangeListener(String propertyName, PropertyChangeListener listener); + + /** + * Timestamp of last update of the Object + * + * @return + */ + long getLastUpdateMillis(); } diff --git a/src/main/java/org/asteriskjava/live/ManagerCommunicationException.java b/src/main/java/org/asteriskjava/live/ManagerCommunicationException.java index 395b543ef..0d54b9aa5 100644 --- a/src/main/java/org/asteriskjava/live/ManagerCommunicationException.java +++ b/src/main/java/org/asteriskjava/live/ManagerCommunicationException.java @@ -17,15 +17,13 @@ package org.asteriskjava.live; -public class ManagerCommunicationException extends LiveException -{ +public class ManagerCommunicationException extends LiveException { /** * Serial version identifier. */ private static final long serialVersionUID = -1183197752451685927L; - public ManagerCommunicationException(String message, Throwable cause) - { + public ManagerCommunicationException(String message, Throwable cause) { super(message, cause); } } diff --git a/src/main/java/org/asteriskjava/live/MeetMeRoom.java b/src/main/java/org/asteriskjava/live/MeetMeRoom.java index 4756f0bfd..07c7de102 100644 --- a/src/main/java/org/asteriskjava/live/MeetMeRoom.java +++ b/src/main/java/org/asteriskjava/live/MeetMeRoom.java @@ -21,23 +21,22 @@ /** * Represents an Asterisk MeetMe room.

    * MeetMe rooms bridge multiple channels. - * + * * @author srt * @since 0.3 */ -public interface MeetMeRoom -{ +public interface MeetMeRoom { /** * Returns the number of this MeetMe room.

    * This property is immutable. - * + * * @return the number of this MeetMe room. */ String getRoomNumber(); /** * Returns a collection of all active users in this MeetMe room. - * + * * @return a collection of all active users in this MeetMe room. */ Collection getUsers(); @@ -52,14 +51,14 @@ public interface MeetMeRoom /** * Locks this room so no addtional users can join. - * + * * @throws ManagerCommunicationException if the room can't be locked. */ void lock() throws ManagerCommunicationException; /** * Unlocks this room so additional users can join again. - * + * * @throws ManagerCommunicationException if the room can't be locked. */ void unlock() throws ManagerCommunicationException; diff --git a/src/main/java/org/asteriskjava/live/MeetMeUser.java b/src/main/java/org/asteriskjava/live/MeetMeUser.java index dc883ee51..1b9e10677 100644 --- a/src/main/java/org/asteriskjava/live/MeetMeUser.java +++ b/src/main/java/org/asteriskjava/live/MeetMeUser.java @@ -26,39 +26,38 @@ *

  • muted *
  • state * - * - * @see org.asteriskjava.live.MeetMeRoom + * * @author srt + * @see org.asteriskjava.live.MeetMeRoom * @since 0.3 */ -public interface MeetMeUser extends LiveObject -{ +public interface MeetMeUser extends LiveObject { String PROPERTY_TALKING = "talking"; String PROPERTY_MUTED = "muted"; String PROPERTY_STATE = "state"; - + /** * Returns whether this user is currently talking or not.

    * Asterisk supports talker detection since version 1.2. - * + * * @return true if this user is currently talking and - * talker detection is supported, false otherwise. + * talker detection is supported, false otherwise. */ boolean isTalking(); /** * Returns whether this user is muted or not.

    * Supported since Asterisk version 1.4. - * + * * @return true if this user is muted and - * mute detection is supported, false otherwise. + * mute detection is supported, false otherwise. */ boolean isMuted(); - + /** * Returns the date this user joined the MeetMe room.

    * This property is immutable. - * + * * @return the date this user joined the MeetMe room. */ Date getDateJoined(); @@ -68,16 +67,16 @@ public interface MeetMeUser extends LiveObject * This property is null as long as the user is * in state {@link MeetMeUserState#JOINED} and set to date the * user left when entering {@link MeetMeUserState#LEFT}. - * - * @return the date this user left the MeetMe room or - * null if the user did not yet leave. + * + * @return the date this user left the MeetMe room or + * null if the user did not yet leave. */ Date getDateLeft(); - + /** * Returns the lifecycle status of this MeetMeUser.

    * Initially the user is in state {@link MeetMeUserState#JOINED}. - * + * * @return the lifecycle status of this MeetMeUser. */ MeetMeUserState getState(); @@ -85,7 +84,7 @@ public interface MeetMeUser extends LiveObject /** * Returns the MeetMe room this user joined.

    * This property is immutable. - * + * * @return the MeetMe room this user joined. */ MeetMeRoom getRoom(); @@ -94,7 +93,7 @@ public interface MeetMeUser extends LiveObject * Returns the user number assigned to this user in the room.

    * Usually you won't need to access this property directly.

    * This property is immutable. - * + * * @return the user number assigned to this user in the room. */ Integer getUserNumber(); @@ -102,28 +101,28 @@ public interface MeetMeUser extends LiveObject /** * Returns the channel associated with this user.

    * This property is immutable. - * + * * @return the channel associated with this user. */ AsteriskChannel getChannel(); /** * Stops sending voice from this user to the MeetMe room. - * + * * @throws ManagerCommunicationException if there is a problem talking to the Asterisk server. */ void mute() throws ManagerCommunicationException; /** * (Re)starts sending voice from this user to the MeetMe room. - * + * * @throws ManagerCommunicationException if there is a problem talking to the Asterisk server. */ void unmute() throws ManagerCommunicationException; /** * Removes this user from the MeetMe room. - * + * * @throws ManagerCommunicationException if there is a problem talking to the Asterisk server. */ void kick() throws ManagerCommunicationException; diff --git a/src/main/java/org/asteriskjava/live/MeetMeUserState.java b/src/main/java/org/asteriskjava/live/MeetMeUserState.java index 5a33f6221..24de928b4 100644 --- a/src/main/java/org/asteriskjava/live/MeetMeUserState.java +++ b/src/main/java/org/asteriskjava/live/MeetMeUserState.java @@ -18,12 +18,11 @@ /** * The lifecycle status of a {@link org.asteriskjava.live.MeetMeUser}. - * + * * @author srt * @version $Id$ */ -public enum MeetMeUserState -{ +public enum MeetMeUserState { /** * The user joined the MeetMe room. */ diff --git a/src/main/java/org/asteriskjava/live/NoSuchChannelException.java b/src/main/java/org/asteriskjava/live/NoSuchChannelException.java index faa73050b..0e0d7a368 100644 --- a/src/main/java/org/asteriskjava/live/NoSuchChannelException.java +++ b/src/main/java/org/asteriskjava/live/NoSuchChannelException.java @@ -18,12 +18,11 @@ /** * Indicates that the channel is not available on the Asterisk server. - * + * * @author srt * @version $Id$ */ -public class NoSuchChannelException extends LiveException -{ +public class NoSuchChannelException extends LiveException { /** * Serial version identifier. */ @@ -31,11 +30,10 @@ public class NoSuchChannelException extends LiveException /** * Creates a new instance with the given message. - * + * * @param message the message */ - public NoSuchChannelException(String message) - { + public NoSuchChannelException(String message) { super(message); } } diff --git a/src/main/java/org/asteriskjava/live/NoSuchInterfaceException.java b/src/main/java/org/asteriskjava/live/NoSuchInterfaceException.java index a0c2714d2..afe79568d 100644 --- a/src/main/java/org/asteriskjava/live/NoSuchInterfaceException.java +++ b/src/main/java/org/asteriskjava/live/NoSuchInterfaceException.java @@ -23,8 +23,7 @@ * @version $Id$ * @since 1.0.0 */ -public class NoSuchInterfaceException extends LiveException -{ +public class NoSuchInterfaceException extends LiveException { /** * Serial version identifier. */ @@ -35,8 +34,7 @@ public class NoSuchInterfaceException extends LiveException * * @param message the message */ - public NoSuchInterfaceException(String message) - { + public NoSuchInterfaceException(String message) { super(message); } } diff --git a/src/main/java/org/asteriskjava/live/OriginateCallback.java b/src/main/java/org/asteriskjava/live/OriginateCallback.java index 32e94121e..62883571b 100644 --- a/src/main/java/org/asteriskjava/live/OriginateCallback.java +++ b/src/main/java/org/asteriskjava/live/OriginateCallback.java @@ -26,20 +26,19 @@ * and it is called exactly once.
    * Otherwise one of {@link #onSuccess(AsteriskChannel)} {@link #onBusy(AsteriskChannel)} or * {@link #onNoAnswer(AsteriskChannel)} is called exactly once. - * + * + * @author srt + * @version $Id$ * @see AsteriskServer#originateToApplicationAsync(String, String, String, long, OriginateCallback) * @see AsteriskServer#originateToApplicationAsync(String, String, String, long, CallerId, java.util.Map, OriginateCallback) * @see AsteriskServer#originateToExtensionAsync(String, String, String, int, long, OriginateCallback) * @see AsteriskServer#originateToExtensionAsync(String, String, String, int, long, CallerId, java.util.Map, OriginateCallback) - * @author srt - * @version $Id$ * @since 0.3 */ -public interface OriginateCallback -{ +public interface OriginateCallback { /** * Called when the channel has been created and before it starts ringing. - * + * * @param channel the channel created. */ void onDialing(AsteriskChannel channel); @@ -47,7 +46,7 @@ public interface OriginateCallback /** * Called if the originate was successful and the called party answered the * call. - * + * * @param channel the channel created. */ void onSuccess(AsteriskChannel channel); @@ -55,7 +54,7 @@ public interface OriginateCallback /** * Called if the originate was unsuccessful because the called party did not * answer the call. - * + * * @param channel the channel created. */ void onNoAnswer(AsteriskChannel channel); @@ -63,7 +62,7 @@ public interface OriginateCallback /** * Called if the originate was unsuccessful because the called party was * busy. - * + * * @param channel the channel created. */ void onBusy(AsteriskChannel channel); @@ -71,7 +70,7 @@ public interface OriginateCallback /** * Called if the originate failed for example due to an invalid channel name * or an originate to an unregistered SIP or IAX peer. - * + * * @param cause the exception that caused the failure. */ void onFailure(LiveException cause); diff --git a/src/main/java/org/asteriskjava/live/QueueEntryState.java b/src/main/java/org/asteriskjava/live/QueueEntryState.java index 24e419263..0480428f3 100644 --- a/src/main/java/org/asteriskjava/live/QueueEntryState.java +++ b/src/main/java/org/asteriskjava/live/QueueEntryState.java @@ -2,11 +2,10 @@ /** * The lifecycle status of a {@link org.asteriskjava.live.AsteriskQueueEntry}. - * + * * @author gmi */ -public enum QueueEntryState -{ +public enum QueueEntryState { /** * The user joined the queue. */ diff --git a/src/main/java/org/asteriskjava/live/QueueMemberState.java b/src/main/java/org/asteriskjava/live/QueueMemberState.java index 03d95d3b7..384f00248 100644 --- a/src/main/java/org/asteriskjava/live/QueueMemberState.java +++ b/src/main/java/org/asteriskjava/live/QueueMemberState.java @@ -19,9 +19,9 @@ import org.asteriskjava.manager.event.QueueMemberEvent; /** - * Represents the status of a Queue memeber. + * Represents the status of a Queue member. * - *

    + *
    * Valid status codes are: *

    *
    AST_DEVICE_UNKNOWN (0)
    @@ -36,15 +36,21 @@ *
    ?
    *
    AST_DEVICE_UNAVAILABLE (5)
    *
    ?
    + *
    AST_DEVICE_RINGING (6)
    + *
    ?
    + *
    AST_DEVICE_RINGINUSE (7)
    + *
    ?
    + *
    AST_DEVICE_ONHOLD (8)
    + *
    ?
    *
    * * @author Patrick Breucking + * @author itaqua * @version $Id$ - * @since 0.3.1 * @see org.asteriskjava.manager.event.QueueMemberEvent + * @since 0.3.1 */ -public enum QueueMemberState -{ +public enum QueueMemberState { DEVICE_UNKNOWN(QueueMemberEvent.AST_DEVICE_UNKNOWN), /** @@ -62,9 +68,25 @@ public enum QueueMemberState DEVICE_INVALID(QueueMemberEvent.AST_DEVICE_INVALID), /** - * Device is not availible for call, eg. Agent is logged off. + * Device is not available for call, eg. Agent is logged off. + */ + DEVICE_UNAVAILABLE(QueueMemberEvent.AST_DEVICE_UNAVAILABLE), + + /** + * Device is ringing. */ - DEVICE_UNAVAILABLE(QueueMemberEvent.AST_DEVICE_UNAVAILABLE); + DEVICE_RINGING(QueueMemberEvent.AST_DEVICE_RINGING), + + /** + * Device is ringing *and* in use. + */ + DEVICE_RINGINUSE(QueueMemberEvent.AST_DEVICE_RINGINUSE), + + /** + * Device is on hold + */ + DEVICE_ONHOLD(QueueMemberEvent.AST_DEVICE_ONHOLD); + private final int status; @@ -73,8 +95,7 @@ public enum QueueMemberState * * @param status the numerical status code. */ - QueueMemberState(int status) - { + QueueMemberState(int status) { this.status = status; } @@ -82,10 +103,9 @@ public enum QueueMemberState * Returns the numerical status code. * * @return the numerical status code. - * @see org.asteriskjava.manager.event.QueueMemberEvent#getStatus() + * @see org.asteriskjava.manager.event.QueueMemberEvent#getStatus() */ - public int getStatus() - { + public int getStatus() { return status; } @@ -96,17 +116,13 @@ public int getStatus() * @param status integer representation of the status. * @return corresponding QueueMemberState object or null if none matches. */ - public static QueueMemberState valueOf(Integer status) - { - if (status == null) - { + public static QueueMemberState valueOf(Integer status) { + if (status == null) { return null; } - for (QueueMemberState tmp : QueueMemberState.values()) - { - if (tmp.getStatus() == status) - { + for (QueueMemberState tmp : QueueMemberState.values()) { + if (tmp.getStatus() == status) { return tmp; } } diff --git a/src/main/java/org/asteriskjava/live/RecordingException.java b/src/main/java/org/asteriskjava/live/RecordingException.java new file mode 100644 index 000000000..25a1aff66 --- /dev/null +++ b/src/main/java/org/asteriskjava/live/RecordingException.java @@ -0,0 +1,40 @@ +/* + * Copyright 2005-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.live; + +/** + * Indicates that a record operation related issue has occured, + * + * @author videanuadrian + * @version $Id$ + */ +public class RecordingException extends LiveException { + /** + * Serial version identifier. + */ + + private static final long serialVersionUID = 7804327171239361017L; + + /** + * Creates a new instance with the given message. + * + * @param message the message + */ + public RecordingException(String message) { + super(message); + } +} diff --git a/src/main/java/org/asteriskjava/live/SecureAsteriskServer.java b/src/main/java/org/asteriskjava/live/SecureAsteriskServer.java index 0fde9ecc0..3a7f80673 100644 --- a/src/main/java/org/asteriskjava/live/SecureAsteriskServer.java +++ b/src/main/java/org/asteriskjava/live/SecureAsteriskServer.java @@ -11,8 +11,7 @@ * @version $Id$ * @see org.asteriskjava.live.AsteriskServer */ -public class SecureAsteriskServer extends DefaultAsteriskServer -{ +public class SecureAsteriskServer extends DefaultAsteriskServer { /** * Creates a new instance and a new SSL secured {@link ManagerConnection} with the given * connection data. @@ -22,14 +21,12 @@ public class SecureAsteriskServer extends DefaultAsteriskServer * @param username the username to use for login * @param password the password to use for login */ - public SecureAsteriskServer(String hostname, int port, String username, String password) - { + public SecureAsteriskServer(String hostname, int port, String username, String password) { super(hostname, port, username, password); } @Override - protected DefaultManagerConnection createManagerConnection(String hostname, int port, String username, String password) - { + protected DefaultManagerConnection createManagerConnection(String hostname, int port, String username, String password) { DefaultManagerConnection dmc; dmc = super.createManagerConnection(hostname, port, username, password); dmc.setSsl(true); diff --git a/src/main/java/org/asteriskjava/live/Voicemailbox.java b/src/main/java/org/asteriskjava/live/Voicemailbox.java index 4aa7812e1..4daf1a860 100644 --- a/src/main/java/org/asteriskjava/live/Voicemailbox.java +++ b/src/main/java/org/asteriskjava/live/Voicemailbox.java @@ -20,13 +20,12 @@ /** * An Asterisk voicemailbox with status. - * + * * @author srt * @version $Id$ * @since 0.3 */ -public class Voicemailbox implements Serializable -{ +public class Voicemailbox implements Serializable { /** * Serial version identifier. */ @@ -39,13 +38,12 @@ public class Voicemailbox implements Serializable /** * Creates a new instance. - * + * * @param mailbox the name of this mailbox as defined in voicemail.conf. * @param context the context of this mailbox as defined in voicemail.conf. - * @param user the user of this mailbox as defined in voicemail.conf. + * @param user the user of this mailbox as defined in voicemail.conf. */ - public Voicemailbox(String mailbox, String context, String user) - { + public Voicemailbox(String mailbox, String context, String user) { this.mailbox = mailbox; this.context = context; this.user = user; @@ -53,80 +51,72 @@ public Voicemailbox(String mailbox, String context, String user) /** * Returns the name of this mailbox as defined in voicemail.conf. - * + * * @return the name of this mailbox as defined in voicemail.conf. */ - public String getMailbox() - { + public String getMailbox() { return mailbox; } /** * Returns the context of this mailbox as defined in voicemail.conf. - * + * * @return the context of this mailbox as defined in voicemail.conf. */ - public String getContext() - { + public String getContext() { return context; } /** * Returns the user (usually the full name) of this mailbox as defined in voicemail.conf. - * + * * @return the user of this mailbox as defined in voicemail.conf. */ - public String getUser() - { + public String getUser() { return user; } /** * Returns the number of new messages. - * + * * @return the number of new messages. */ - public int getNewMessages() - { + public int getNewMessages() { return newMessages; } /** * Sets the number of new messages. - * + * * @param newMessages the number of new messages. */ - public void setNewMessages(int newMessages) - { + public void setNewMessages(int newMessages) { this.newMessages = newMessages; } /** * Returns the number of old messages. - * + * * @return the number of old messages. */ - public int getOldMessages() - { + public int getOldMessages() { return oldMessages; } /** * Sets the number of old messages. - * + * * @param oldMessages the number of old messages. */ - public void setOldMessages(int oldMessages) - { + public void setOldMessages(int oldMessages) { this.oldMessages = oldMessages; } @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; - sb = new StringBuffer(100); + sb = new StringBuilder(100); sb.append("Voicemailbox["); sb.append("mailbox='").append(getMailbox()).append("',"); sb.append("context='").append(getContext()).append("',"); diff --git a/src/main/java/org/asteriskjava/live/internal/AbstractLiveObject.java b/src/main/java/org/asteriskjava/live/internal/AbstractLiveObject.java index f607d99f8..231bb9c0e 100644 --- a/src/main/java/org/asteriskjava/live/internal/AbstractLiveObject.java +++ b/src/main/java/org/asteriskjava/live/internal/AbstractLiveObject.java @@ -16,69 +16,81 @@ */ package org.asteriskjava.live.internal; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; - import org.asteriskjava.live.AsteriskServer; import org.asteriskjava.live.LiveObject; +import org.asteriskjava.lock.Lockable; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; + /** * Abstract base class for all live objects. - * + * * @author srt * @since 0.3 */ -abstract class AbstractLiveObject implements LiveObject -{ +abstract class AbstractLiveObject extends Lockable implements LiveObject { private final Log logger = LogFactory.getLog(this.getClass()); private final PropertyChangeSupport changes; protected final AsteriskServerImpl server; - AbstractLiveObject(AsteriskServerImpl server) - { + // last time this object was updated + private long lastUpdate; + + AbstractLiveObject(AsteriskServerImpl server) { this.server = server; this.changes = new PropertyChangeSupport(this); + stampLastUpdate(); } - public AsteriskServer getServer() - { + public AsteriskServer getServer() { return server; } - public void addPropertyChangeListener(PropertyChangeListener listener) - { + public void addPropertyChangeListener(PropertyChangeListener listener) { changes.addPropertyChangeListener(listener); } - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) - { - changes.addPropertyChangeListener(propertyName, listener); + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { + boolean haveToAdd = true; + for (PropertyChangeListener l : changes.getPropertyChangeListeners()) { + if (l == listener) { + haveToAdd = false; + break; + } + } + if (haveToAdd) { + changes.addPropertyChangeListener(propertyName, listener); + } } - public void removePropertyChangeListener(PropertyChangeListener listener) - { + public void removePropertyChangeListener(PropertyChangeListener listener) { changes.removePropertyChangeListener(listener); } - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) - { + public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { changes.removePropertyChangeListener(propertyName, listener); } - - protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) - { - if (oldValue != null || newValue != null) - { - try - { + + protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + if (oldValue != null || newValue != null) { + stampLastUpdate(); + try { changes.firePropertyChange(propertyName, oldValue, newValue); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Uncaught exception in PropertyChangeListener", e); } } } + + @Override + public long getLastUpdateMillis() { + return lastUpdate; + } + + public void stampLastUpdate() { + lastUpdate = System.currentTimeMillis(); + } } diff --git a/src/main/java/org/asteriskjava/live/internal/AgentManager.java b/src/main/java/org/asteriskjava/live/internal/AgentManager.java index 838d17777..f9f5a2533 100644 --- a/src/main/java/org/asteriskjava/live/internal/AgentManager.java +++ b/src/main/java/org/asteriskjava/live/internal/AgentManager.java @@ -16,40 +16,31 @@ */ package org.asteriskjava.live.internal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - import org.asteriskjava.live.AgentState; import org.asteriskjava.live.AsteriskAgent; import org.asteriskjava.live.ManagerCommunicationException; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.ResponseEvents; import org.asteriskjava.manager.action.AgentsAction; -import org.asteriskjava.manager.event.AgentCallbackLoginEvent; -import org.asteriskjava.manager.event.AgentCallbackLogoffEvent; -import org.asteriskjava.manager.event.AgentCalledEvent; -import org.asteriskjava.manager.event.AgentCompleteEvent; -import org.asteriskjava.manager.event.AgentConnectEvent; -import org.asteriskjava.manager.event.AgentLoginEvent; -import org.asteriskjava.manager.event.AgentLogoffEvent; -import org.asteriskjava.manager.event.AgentsEvent; -import org.asteriskjava.manager.event.ManagerEvent; +import org.asteriskjava.manager.event.*; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; + /** * Manages all events related to agents on Asterisk server. For correct work * ensure enabled AgentCalledEvents. You have to set * eventwhencalled = yes in queues.conf. * - * @author Patrick - * Breucking + * @author Patrick Breucking * @version $Id$ * @since 0.3.1 */ -public class AgentManager -{ +public class AgentManager { private final Log logger = LogFactory.getLog(this.getClass()); @@ -58,19 +49,18 @@ public class AgentManager /** * A Map of agents by thier agentId. */ - private final Map agents; + private final LockableMap agents; /** * A Map of agent in state RINGING by the caller id. Needed to return agent * into idle state, if call was not conneted. */ - private final Map ringingAgents; + private final LockableMap ringingAgents; - AgentManager(AsteriskServerImpl asteriskServerImpl) - { + AgentManager(AsteriskServerImpl asteriskServerImpl) { this.server = asteriskServerImpl; - agents = new HashMap(); - ringingAgents = new HashMap(); + agents = new LockableMap<>(new HashMap<>()); + ringingAgents = new LockableMap<>(new HashMap<>()); } /** @@ -80,26 +70,21 @@ public class AgentManager * @throws ManagerCommunicationException if communication with Asterisk * server fails. */ - void initialize() throws ManagerCommunicationException - { + void initialize() throws ManagerCommunicationException { ResponseEvents re; re = server.sendEventGeneratingAction(new AgentsAction()); - for (ManagerEvent event : re.getEvents()) - { - if (event instanceof AgentsEvent) - { - System.out.println(event); + for (ManagerEvent event : re.getEvents()) { + if (event instanceof AgentsEvent) { + logger.info(event); handleAgentsEvent((AgentsEvent) event); } } } - void disconnected() - { - synchronized (agents) - { + void disconnected() { + try (LockCloser closer = agents.withLock()) { agents.clear(); } } @@ -109,10 +94,9 @@ void disconnected() * * @param event generated by Asterisk server. */ - void handleAgentsEvent(AgentsEvent event) - { - AsteriskAgentImpl agent = new AsteriskAgentImpl(server, - event.getName(), "Agent/" + event.getAgent(), AgentState.valueOf(event.getStatus())); + void handleAgentsEvent(AgentsEvent event) { + AsteriskAgentImpl agent = new AsteriskAgentImpl(server, event.getName(), "Agent/" + event.getAgent(), + AgentState.valueOf(event.getStatus())); logger.info("Adding agent " + agent.getName() + "(" + agent.getAgentId() + ")"); addAgent(agent); @@ -123,10 +107,8 @@ void handleAgentsEvent(AgentsEvent event) * * @param agent agent to add. */ - private void addAgent(AsteriskAgentImpl agent) - { - synchronized (agents) - { + private void addAgent(AsteriskAgentImpl agent) { + try (LockCloser closer = agents.withLock()) { agents.put(agent.getAgentId(), agent); } server.fireNewAgent(agent); @@ -138,10 +120,8 @@ private void addAgent(AsteriskAgentImpl agent) * @param agentId identifier for agent * @return the requested agent */ - AsteriskAgentImpl getAgentByAgentId(String agentId) - { - synchronized (agents) - { + AsteriskAgentImpl getAgentByAgentId(String agentId) { + try (LockCloser closer = agents.withLock()) { return agents.get(agentId); } } @@ -151,11 +131,9 @@ AsteriskAgentImpl getAgentByAgentId(String agentId) * * @param event */ - void handleAgentCalledEvent(AgentCalledEvent event) - { + void handleAgentCalledEvent(AgentCalledEvent event) { AsteriskAgentImpl agent = getAgentByAgentId(event.getAgentCalled()); - if (agent == null) - { + if (agent == null) { logger.error("Ignored AgentCalledEvent for unknown agent " + event.getAgentCalled()); return; } @@ -168,11 +146,9 @@ void handleAgentCalledEvent(AgentCalledEvent event) * * @param agent */ - private void updateAgentState(AsteriskAgentImpl agent, AgentState newState) - { + private void updateAgentState(AsteriskAgentImpl agent, AgentState newState) { logger.info("Set state of agent " + agent.getAgentId() + " to " + newState); - synchronized (agent) - { + try (LockCloser closer = agent.withLock()) { agent.updateState(newState); } } @@ -185,12 +161,9 @@ private void updateAgentState(AsteriskAgentImpl agent, AgentState newState) * @param channelCalling * @param agent */ - private void updateRingingAgents(String channelCalling, AsteriskAgentImpl agent) - { - synchronized (ringingAgents) - { - if (ringingAgents.containsKey(channelCalling)) - { + private void updateRingingAgents(String channelCalling, AsteriskAgentImpl agent) { + try (LockCloser closer = ringingAgents.withLock()) { + if (ringingAgents.containsKey(channelCalling)) { updateAgentState(ringingAgents.get(channelCalling), AgentState.AGENT_IDLE); } ringingAgents.put(channelCalling, agent); @@ -202,31 +175,26 @@ private void updateRingingAgents(String channelCalling, AsteriskAgentImpl agent) * * @param event */ - void handleAgentConnectEvent(AgentConnectEvent event) - { + void handleAgentConnectEvent(AgentConnectEvent event) { AsteriskAgentImpl agent = getAgentByAgentId(event.getChannel()); - if (agent == null) - { + if (agent == null) { logger.error("Ignored AgentConnectEvent for unknown agent " + event.getChannel()); return; } agent.updateState(AgentState.AGENT_ONCALL); } - + /** * Change state if agent logs in. * * @param event */ - void handleAgentLoginEvent(AgentLoginEvent event) - { + void handleAgentLoginEvent(AgentLoginEvent event) { AsteriskAgentImpl agent = getAgentByAgentId("Agent/" + event.getAgent()); - if (agent == null) - { - synchronized (agents) - { - logger.error("Ignored AgentLoginEvent for unknown agent " - + event.getAgent() + ". Agents: " + agents.values().toString()); + if (agent == null) { + try (LockCloser closer = agents.withLock()) { + logger.error("Ignored AgentLoginEvent for unknown agent " + event.getAgent() + ". Agents: " + + agents.values().toString()); } return; @@ -239,13 +207,10 @@ void handleAgentLoginEvent(AgentLoginEvent event) * * @param event */ - void handleAgentLogoffEvent(AgentLogoffEvent event) - { + void handleAgentLogoffEvent(AgentLogoffEvent event) { AsteriskAgentImpl agent = getAgentByAgentId("Agent/" + event.getAgent()); - if (agent == null) - { - logger.error("Ignored AgentLogoffEvent for unknown agent " - + event.getAgent() + ". Agents: " + if (agent == null) { + logger.error("Ignored AgentLogoffEvent for unknown agent " + event.getAgent() + ". Agents: " + agents.values().toString()); return; } @@ -257,15 +222,12 @@ void handleAgentLogoffEvent(AgentLogoffEvent event) * * @param event */ - void handleAgentCallbackLoginEvent(AgentCallbackLoginEvent event) - { + void handleAgentCallbackLoginEvent(AgentCallbackLoginEvent event) { AsteriskAgentImpl agent = getAgentByAgentId("Agent/" + event.getAgent()); - if (agent == null) - { - synchronized (agents) - { - logger.error("Ignored AgentCallbackLoginEvent for unknown agent " - + event.getAgent() + ". Agents: " + agents.values().toString()); + if (agent == null) { + try (LockCloser closer = agents.withLock()) { + logger.error("Ignored AgentCallbackLoginEvent for unknown agent " + event.getAgent() + ". Agents: " + + agents.values().toString()); } return; @@ -278,13 +240,10 @@ void handleAgentCallbackLoginEvent(AgentCallbackLoginEvent event) * * @param event */ - void handleAgentCallbackLogoffEvent(AgentCallbackLogoffEvent event) - { + void handleAgentCallbackLogoffEvent(AgentCallbackLogoffEvent event) { AsteriskAgentImpl agent = getAgentByAgentId("Agent/" + event.getAgent()); - if (agent == null) - { - logger.error("Ignored AgentCallbackLogoffEvent for unknown agent " - + event.getAgent() + ". Agents: " + if (agent == null) { + logger.error("Ignored AgentCallbackLogoffEvent for unknown agent " + event.getAgent() + ". Agents: " + agents.values().toString()); return; } @@ -297,12 +256,10 @@ void handleAgentCallbackLogoffEvent(AgentCallbackLogoffEvent event) * * @return a collection of all agents. */ - Collection getAgents() - { + Collection getAgents() { Collection copy; - synchronized (agents) - { + try (LockCloser closer = agents.withLock()) { copy = new ArrayList(agents.values()); } return copy; @@ -313,11 +270,9 @@ Collection getAgents() * * @param event */ - void handleAgentCompleteEvent(AgentCompleteEvent event) - { + void handleAgentCompleteEvent(AgentCompleteEvent event) { AsteriskAgentImpl agent = getAgentByAgentId(event.getChannel()); - if (agent == null) - { + if (agent == null) { logger.error("Ignored AgentCompleteEvent for unknown agent " + event.getChannel()); return; } diff --git a/src/main/java/org/asteriskjava/live/internal/AsteriskAgentImpl.java b/src/main/java/org/asteriskjava/live/internal/AsteriskAgentImpl.java index 1c92ad268..97d3ef6c7 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskAgentImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskAgentImpl.java @@ -18,24 +18,22 @@ import org.asteriskjava.live.AgentState; import org.asteriskjava.live.AsteriskAgent; +import org.asteriskjava.lock.Locker.LockCloser; /** * Default implementation of the AsteriskAgent interface. * - * @author Patrick Breucking + * @author Patrick Breucking * @version $Id$ */ -public class AsteriskAgentImpl extends AbstractLiveObject implements AsteriskAgent -{ - public String name; - public String agentId; - public AgentState state; +public class AsteriskAgentImpl extends AbstractLiveObject implements AsteriskAgent { + private String name; + private String agentId; + private AgentState state; - AsteriskAgentImpl(AsteriskServerImpl server, String name, String agentId, AgentState state) - { + AsteriskAgentImpl(AsteriskServerImpl server, String name, String agentId, AgentState state) { super(server); - if (server == null || name == null || agentId == null) - { + if (server == null || name == null || agentId == null) { throw new IllegalArgumentException("Parameters passed to AsteriskAgentImpl() must not be null."); } this.name = name; @@ -43,34 +41,32 @@ public class AsteriskAgentImpl extends AbstractLiveObject implements AsteriskAge this.state = state; } - public String getName() - { + public String getName() { return name; } - public String getAgentId() - { + public String getAgentId() { return agentId; } - public AgentState getState() - { + public AgentState getState() { return state; } - synchronized void updateState(AgentState state) - { - final AgentState oldState = this.state; - this.state = state; - firePropertyChange(PROPERTY_STATE, oldState, this.state); + void updateState(AgentState state) { + + try (LockCloser closer = this.withLock()) { + final AgentState oldState = this.state; + this.state = state; + firePropertyChange(PROPERTY_STATE, oldState, this.state); + } } @Override - public String toString() - { - final StringBuffer sb; + public String toString() { + final StringBuilder sb; - sb = new StringBuffer("AsteriskAgent["); + sb = new StringBuilder("AsteriskAgent["); sb.append("agentId='").append(getAgentId()).append("',"); sb.append("name='").append(getName()).append("',"); sb.append("state=").append(getState()).append(","); @@ -79,4 +75,4 @@ public String toString() return sb.toString(); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java b/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java index 70a35dc18..ff1015708 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java @@ -16,34 +16,16 @@ */ package org.asteriskjava.live.internal; -import java.util.*; - -import org.asteriskjava.live.AsteriskChannel; -import org.asteriskjava.live.AsteriskQueueEntry; -import org.asteriskjava.live.CallDetailRecord; -import org.asteriskjava.live.CallerId; -import org.asteriskjava.live.ChannelState; -import org.asteriskjava.live.ChannelStateHistoryEntry; -import org.asteriskjava.live.DialedChannelHistoryEntry; -import org.asteriskjava.live.Extension; -import org.asteriskjava.live.ExtensionHistoryEntry; -import org.asteriskjava.live.HangupCause; -import org.asteriskjava.live.LinkedChannelHistoryEntry; -import org.asteriskjava.live.ManagerCommunicationException; -import org.asteriskjava.live.NoSuchChannelException; -import org.asteriskjava.manager.action.AbsoluteTimeoutAction; -import org.asteriskjava.manager.action.ChangeMonitorAction; -import org.asteriskjava.manager.action.GetVarAction; -import org.asteriskjava.manager.action.HangupAction; -import org.asteriskjava.manager.action.MonitorAction; -import org.asteriskjava.manager.action.PauseMonitorAction; -import org.asteriskjava.manager.action.PlayDtmfAction; -import org.asteriskjava.manager.action.RedirectAction; -import org.asteriskjava.manager.action.SetVarAction; -import org.asteriskjava.manager.action.StopMonitorAction; -import org.asteriskjava.manager.action.UnpauseMonitorAction; +import org.asteriskjava.live.*; +import org.asteriskjava.lock.LockableList; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.manager.action.*; import org.asteriskjava.manager.response.ManagerError; import org.asteriskjava.manager.response.ManagerResponse; +import org.asteriskjava.util.MixMonitorDirection; + +import java.util.*; /** * Default implementation of the AsteriskChannel interface. @@ -51,104 +33,92 @@ * @author srt * @version $Id$ */ -class AsteriskChannelImpl extends AbstractLiveObject implements AsteriskChannel -{ +class AsteriskChannelImpl extends AbstractLiveObject implements AsteriskChannel { private static final String CAUSE_VARIABLE_NAME = "PRI_CAUSE"; - + /** + * Date this channel has been created. + */ + private final Date dateOfCreation; + private final LockableList extensionHistory; + private final LockableList stateHistory; + private final LockableList linkedChannelHistory; + private final LockableList dialedChannelHistory; + private final LockableList dialedChannels; + private final LockableList dialingChannels; + /** + * If this channel is bridged to another channel, the linkedChannels + * contains the channel this channel is bridged with. + */ + private final LockableList linkedChannels; + private final LockableMap variables; /** * Unique id of this channel. */ private String id; - /** * The traceId is used to trace originated channels. */ private String traceId; - - /** - * Date this channel has been created. - */ - private final Date dateOfCreation; - /** * Date this channel has left the Asterisk server. */ private Date dateOfRemoval; - /** * Name of this channel. */ private String name; - /** * Caller*ID of this channel. */ private CallerId callerId; - /** * State of this channel. */ private ChannelState state; - /** * Account code used to bill this channel. */ private String account; - private final List extensionHistory; - private final List stateHistory; - private final List linkedChannelHistory; - private final List dialedChannelHistory; - - private AsteriskChannel dialedChannel; - - private AsteriskChannel dialingChannel; - - /** - * If this channel is bridged to another channel, the linkedChannel contains - * the channel this channel is bridged with. - */ - private AsteriskChannel linkedChannel; - /** * Indicates if this channel was linked to another channel at least once. */ private boolean wasLinked; - private HangupCause hangupCause; - private String hangupCauseText; - private CallDetailRecordImpl callDetailRecord; - /** * MeetMe room user associated with this channel if any, null * otherwise. */ private MeetMeUserImpl meetMeUserImpl; - /** * Queue entry associated with this channel if any, null * otherwise. */ private AsteriskQueueEntryImpl queueEntryImpl; - /** * Extension where the call is parked if it is parked, null * otherwise. */ private Extension parkedAt; - /** - * Last dtmf digit recieved on this channel if any, null otherwise. + * Parkinglot where the call is parked if it is parked, null + * otherwise. + */ + private String parkingLot; + /** + * Last dtmf digit recieved on this channel if any, null + * otherwise. */ private Character dtmfReceived; - /** * Last dtmf digit sent on this channel if any, null otherwise. */ private Character dtmfSent; - - private final Map variables; + /** + * Actual monitor state + */ + private boolean isMonitored; /** * Creates a new Channel. @@ -160,39 +130,37 @@ class AsteriskChannelImpl extends AbstractLiveObject implements AsteriskChannel * @throws IllegalArgumentException if any of the parameters are null. */ AsteriskChannelImpl(final AsteriskServerImpl server, final String name, final String id, final Date dateOfCreation) - throws IllegalArgumentException - { + throws IllegalArgumentException { super(server); - if (server == null) - { + if (server == null) { throw new IllegalArgumentException("Parameter 'server' passed to AsteriskChannelImpl() must not be null."); } - if (name == null) - { + if (name == null) { throw new IllegalArgumentException("Parameter 'name' passed to AsteriskChannelImpl() must not be null."); } - if (id == null) - { + if (id == null) { throw new IllegalArgumentException("Parameter 'id' passed to AsteriskChannelImpl() must not be null."); } - if (dateOfCreation == null) - { - throw new IllegalArgumentException("Parameter 'dateOfCreation' passed to AsteriskChannelImpl() must not be null."); + if (dateOfCreation == null) { + throw new IllegalArgumentException( + "Parameter 'dateOfCreation' passed to AsteriskChannelImpl() must not be null."); } this.name = name; this.id = id; this.dateOfCreation = dateOfCreation; - this.extensionHistory = new ArrayList(); - this.stateHistory = new ArrayList(); - this.linkedChannelHistory = new ArrayList(); - this.dialedChannelHistory = new ArrayList(); - this.variables = new HashMap(); + this.extensionHistory = new LockableList<>(new ArrayList<>()); + this.stateHistory = new LockableList<>(new ArrayList<>()); + this.linkedChannelHistory = new LockableList<>(new ArrayList<>()); + this.dialedChannelHistory = new LockableList<>(new ArrayList<>()); + this.variables = new LockableMap<>(new HashMap<>()); + this.dialedChannels = new LockableList<>(new ArrayList<>()); + this.dialingChannels = new LockableList<>(new ArrayList<>()); + this.linkedChannels = new LockableList<>(new ArrayList<>()); } - public String getId() - { + public String getId() { return id; } @@ -202,12 +170,10 @@ public String getId() * @param date date of the name change. * @param id the new unique id of this channel. */ - void idChanged(Date date, String id) - { + void idChanged(Date date, String id) { final String oldId = this.id; - if (oldId != null && oldId.equals(id)) - { + if (oldId != null && oldId.equals(id)) { return; } @@ -215,18 +181,15 @@ void idChanged(Date date, String id) firePropertyChange(PROPERTY_ID, oldId, id); } - String getTraceId() - { + String getTraceId() { return traceId; } - void setTraceId(String traceId) - { + void setTraceId(String traceId) { this.traceId = traceId; } - public String getName() - { + public String getName() { return name; } @@ -236,12 +199,10 @@ public String getName() * @param date date of the name change. * @param name the new name of this channel. */ - void nameChanged(Date date, String name) - { + void nameChanged(Date date, String name) { final String oldName = this.name; - if (oldName != null && oldName.equals(name)) - { + if (oldName != null && oldName.equals(name)) { return; } @@ -249,8 +210,7 @@ void nameChanged(Date date, String name) firePropertyChange(PROPERTY_NAME, oldName, name); } - public CallerId getCallerId() - { + public CallerId getCallerId() { return callerId; } @@ -259,27 +219,21 @@ public CallerId getCallerId() * * @param callerId the caller id of this channel. */ - void setCallerId(final CallerId callerId) - { + void setCallerId(final CallerId callerId) { final CallerId oldCallerId = this.callerId; this.callerId = callerId; firePropertyChange(PROPERTY_CALLER_ID, oldCallerId, callerId); } - public ChannelState getState() - { + public ChannelState getState() { return state; } - public boolean wasInState(ChannelState state) - { - synchronized (stateHistory) - { - for (ChannelStateHistoryEntry historyEntry : stateHistory) - { - if (historyEntry.getState() == state) - { + public boolean wasInState(ChannelState state) { + try (LockCloser closer = stateHistory.withLock()) { + for (ChannelStateHistoryEntry historyEntry : stateHistory) { + if (historyEntry.getState() == state) { return true; } } @@ -288,10 +242,8 @@ public boolean wasInState(ChannelState state) return false; } - public boolean wasBusy() - { - return wasInState(ChannelState.BUSY) - || hangupCause == HangupCause.AST_CAUSE_BUSY + public boolean wasBusy() { + return wasInState(ChannelState.BUSY) || hangupCause == HangupCause.AST_CAUSE_BUSY || hangupCause == HangupCause.AST_CAUSE_USER_BUSY; } @@ -301,30 +253,29 @@ public boolean wasBusy() * @param date when the state change occurred. * @param state the new state of this channel. */ - synchronized void stateChanged(Date date, ChannelState state) - { - final ChannelStateHistoryEntry historyEntry; - final ChannelState oldState = this.state; + void stateChanged(Date date, ChannelState state) { + try (LockCloser closer = this.withLock()) { + final ChannelStateHistoryEntry historyEntry; + final ChannelState oldState = this.state; - if (oldState == state) - { - return; - } + if (oldState == state) { + return; + } - // System.err.println(id + " state change: " + oldState + " => " + state - // + " (" + name + ")"); - historyEntry = new ChannelStateHistoryEntry(date, state); - synchronized (stateHistory) - { - stateHistory.add(historyEntry); - } + // System.err.println(id + " state change: " + oldState + " => " + + // state + // + " (" + name + ")"); + historyEntry = new ChannelStateHistoryEntry(date, state); + try (LockCloser closer2 = stateHistory.withLock()) { + stateHistory.add(historyEntry); + } - this.state = state; - firePropertyChange(PROPERTY_STATE, oldState, state); + this.state = state; + firePropertyChange(PROPERTY_STATE, oldState, state); + } } - public String getAccount() - { + public String getAccount() { return account; } @@ -333,26 +284,20 @@ public String getAccount() * * @param account the account code used to bill this channel. */ - void setAccount(String account) - { + void setAccount(String account) { final String oldAccount = this.account; this.account = account; firePropertyChange(PROPERTY_ACCOUNT, oldAccount, account); } - public Extension getCurrentExtension() - { + public Extension getCurrentExtension() { final Extension extension; - synchronized (extensionHistory) - { - if (extensionHistory.isEmpty()) - { + try (LockCloser closer = extensionHistory.withLock()) { + if (extensionHistory.isEmpty()) { extension = null; - } - else - { + } else { extension = extensionHistory.get(extensionHistory.size() - 1).getExtension(); } } @@ -360,18 +305,13 @@ public Extension getCurrentExtension() return extension; } - public Extension getFirstExtension() - { + public Extension getFirstExtension() { final Extension extension; - synchronized (extensionHistory) - { - if (extensionHistory.isEmpty()) - { + try (LockCloser closer = extensionHistory.withLock()) { + if (extensionHistory.isEmpty()) { extension = null; - } - else - { + } else { extension = extensionHistory.get(0).getExtension(); } } @@ -379,13 +319,11 @@ public Extension getFirstExtension() return extension; } - public List getExtensionHistory() - { + public List getExtensionHistory() { final List copy; - synchronized (extensionHistory) - { - copy = new ArrayList(extensionHistory); + try (LockCloser closer = extensionHistory.withLock()) { + copy = new ArrayList<>(extensionHistory); } return copy; @@ -397,48 +335,40 @@ public List getExtensionHistory() * @param date the date the extension has been visited. * @param extension the visted dialplan entry to add. */ - void extensionVisited(Date date, Extension extension) - { + void extensionVisited(Date date, Extension extension) { final Extension oldCurrentExtension = getCurrentExtension(); final ExtensionHistoryEntry historyEntry; historyEntry = new ExtensionHistoryEntry(date, extension); - synchronized (extensionHistory) - { + try (LockCloser closer = extensionHistory.withLock()) { extensionHistory.add(historyEntry); } firePropertyChange(PROPERTY_CURRENT_EXTENSION, oldCurrentExtension, extension); } - public Date getDateOfCreation() - { + public Date getDateOfCreation() { return dateOfCreation; } - public Date getDateOfRemoval() - { + public Date getDateOfRemoval() { return dateOfRemoval; } - public HangupCause getHangupCause() - { + public HangupCause getHangupCause() { return hangupCause; } - public String getHangupCauseText() - { + public String getHangupCauseText() { return hangupCauseText; } - public CallDetailRecord getCallDetailRecord() - { + public CallDetailRecord getCallDetailRecord() { return callDetailRecord; } - void callDetailRecordReceived(Date date, CallDetailRecordImpl callDetailRecord) - { + void callDetailRecordReceived(Date date, CallDetailRecordImpl callDetailRecord) { final CallDetailRecordImpl oldCallDetailRecord = this.callDetailRecord; this.callDetailRecord = callDetailRecord; @@ -453,84 +383,122 @@ void callDetailRecordReceived(Date date, CallDetailRecordImpl callDetailRecord) * @param hangupCause cause for hangup * @param hangupCauseText textual representation of hangup cause */ - synchronized void hungup(Date dateOfRemoval, HangupCause hangupCause, String hangupCauseText) - { - this.dateOfRemoval = dateOfRemoval; - this.hangupCause = hangupCause; - this.hangupCauseText = hangupCauseText; - // update state and fire PropertyChangeEvent - stateChanged(dateOfRemoval, ChannelState.HUNGUP); + void hungup(Date dateOfRemoval, HangupCause hangupCause, String hangupCauseText) { + try (LockCloser closer = this.withLock()) { + this.dateOfRemoval = dateOfRemoval; + this.hangupCause = hangupCause; + this.hangupCauseText = hangupCauseText; + // update state and fire PropertyChangeEvent + stateChanged(dateOfRemoval, ChannelState.HUNGUP); + } + } + + /** + * Retrives the conplete List of all dialed channels associated to ths calls + * + * @return List of all dialed channels + */ + public List getDialedChannels() { + final List copy; + + try (LockCloser closer = dialedChannels.withLock()) { + copy = new ArrayList<>(dialedChannels); + } + + return copy; } /* dialed channels */ - public AsteriskChannel getDialedChannel() - { - return dialedChannel; + public AsteriskChannel getDialedChannel() { + try (LockCloser closer = dialedChannels.withLock()) { + for (AsteriskChannel channel : dialedChannels) { + if (channel != null) + return channel; + } + } + return null; } - public List getDialedChannelHistory() - { + public List getDialedChannelHistory() { final List copy; - synchronized (linkedChannelHistory) - { - copy = new ArrayList(dialedChannelHistory); + try (LockCloser closer = dialedChannelHistory.withLock()) { + copy = new ArrayList<>(dialedChannelHistory); } return copy; } - synchronized void channelDialed(Date date, AsteriskChannel dialedChannel) - { - final AsteriskChannel oldDialedChannel = this.dialedChannel; - final DialedChannelHistoryEntry historyEntry; + void channelDialed(Date date, AsteriskChannel dialedChannel) { + try (LockCloser closer = this.withLock()) { + final AsteriskChannel oldDialedChannel; + try (LockCloser closer2 = dialedChannels.withLock()) { + if (dialedChannels.isEmpty()) + oldDialedChannel = null; + else + oldDialedChannel = dialedChannels.get(dialedChannels.size() - 1); + dialedChannels.add(dialedChannel); + } + final DialedChannelHistoryEntry historyEntry; + + historyEntry = new DialedChannelHistoryEntry(date, dialedChannel); + try (LockCloser closer3 = dialedChannelHistory.withLock()) { + dialedChannelHistory.add(historyEntry); + } - historyEntry = new DialedChannelHistoryEntry(date, dialedChannel); - synchronized (dialedChannelHistory) - { - dialedChannelHistory.add(historyEntry); + firePropertyChange(PROPERTY_DIALED_CHANNEL, oldDialedChannel, dialedChannel); } - this.dialedChannel = dialedChannel; - firePropertyChange(PROPERTY_DIALED_CHANNEL, oldDialedChannel, dialedChannel); } /* dialed channels */ - public AsteriskChannel getDialingChannel() - { - return dialingChannel; + public AsteriskChannel getDialingChannel() { + try (LockCloser closer = dialingChannels.withLock()) { + if (dialingChannels.isEmpty()) + return null; + return dialingChannels.get(0); + } } - synchronized void channelDialing(Date date, AsteriskChannel dialingChannel) - { - final AsteriskChannel oldDialingChannel = this.dialingChannel; + void channelDialing(Date date, AsteriskChannel dialingChannel) { + try (LockCloser closer = this.withLock()) { + final AsteriskChannel oldDialingChannel; + try (LockCloser closer2 = this.dialingChannels.withLock()) { + if (this.dialingChannels.isEmpty()) { + oldDialingChannel = null; + this.dialingChannels.add(dialingChannel); + } else { + oldDialingChannel = this.dialingChannels.get(0); + this.dialingChannels.set(0, dialingChannel); + } + } - this.dialingChannel = dialingChannel; - firePropertyChange(PROPERTY_DIALING_CHANNEL, oldDialingChannel, dialingChannel); + firePropertyChange(PROPERTY_DIALING_CHANNEL, oldDialingChannel, dialingChannel); + } } /* linked channels */ - public AsteriskChannel getLinkedChannel() - { - return linkedChannel; + public AsteriskChannel getLinkedChannel() { + try (LockCloser closer = linkedChannels.withLock()) { + if (linkedChannels.isEmpty()) + return null; + return linkedChannels.get(0); + } } - public List getLinkedChannelHistory() - { + public List getLinkedChannelHistory() { final List copy; - synchronized (linkedChannelHistory) - { - copy = new ArrayList(linkedChannelHistory); + try (LockCloser closer = linkedChannelHistory.withLock()) { + copy = new ArrayList<>(linkedChannelHistory); } return copy; } - public boolean wasLinked() - { + public boolean wasLinked() { return wasLinked; } @@ -540,55 +508,68 @@ public boolean wasLinked() * @param date the date this channel was linked. * @param linkedChannel the channel this channel is bridged with. */ - synchronized void channelLinked(Date date, AsteriskChannel linkedChannel) - { - final AsteriskChannel oldLinkedChannel = this.linkedChannel; - final LinkedChannelHistoryEntry historyEntry; - - historyEntry = new LinkedChannelHistoryEntry(date, linkedChannel); - synchronized (linkedChannelHistory) - { - linkedChannelHistory.add(historyEntry); - } - this.linkedChannel = linkedChannel; - this.wasLinked = true; - firePropertyChange(PROPERTY_LINKED_CHANNEL, oldLinkedChannel, linkedChannel); - } - - synchronized void channelUnlinked(Date date) - { - final AsteriskChannel oldLinkedChannel = this.linkedChannel; - final LinkedChannelHistoryEntry historyEntry; - - synchronized (linkedChannelHistory) - { - if (linkedChannelHistory.isEmpty()) - { - historyEntry = null; + void channelLinked(Date date, AsteriskChannel linkedChannel) { + try (LockCloser closer = this.withLock()) { + final AsteriskChannel oldLinkedChannel; + try (LockCloser closer2 = this.linkedChannels.withLock()) { + if (this.linkedChannels.isEmpty()) { + oldLinkedChannel = null; + this.linkedChannels.add(linkedChannel); + } else { + oldLinkedChannel = this.linkedChannels.get(0); + this.linkedChannels.set(0, linkedChannel); + } } - else - { - historyEntry = linkedChannelHistory.get(linkedChannelHistory.size() - 1); + + final LinkedChannelHistoryEntry historyEntry; + + historyEntry = new LinkedChannelHistoryEntry(date, linkedChannel); + try (LockCloser closer3 = linkedChannelHistory.withLock()) { + linkedChannelHistory.add(historyEntry); } + this.wasLinked = true; + firePropertyChange(PROPERTY_LINKED_CHANNEL, oldLinkedChannel, linkedChannel); } + } + + void channelUnlinked(Date date) { + try (LockCloser closer = this.withLock()) { + final AsteriskChannel oldLinkedChannel; + + try (LockCloser closer2 = this.linkedChannels.withLock()) { + if (this.linkedChannels.isEmpty()) { + oldLinkedChannel = null; + } else { + oldLinkedChannel = this.linkedChannels.get(0); + } + linkedChannels.clear(); + } - if (historyEntry != null) - { - historyEntry.setDateUnlinked(date); + final LinkedChannelHistoryEntry historyEntry; + + try (LockCloser closer3 = linkedChannelHistory.withLock()) { + if (linkedChannelHistory.isEmpty()) { + historyEntry = null; + } else { + historyEntry = linkedChannelHistory.get(linkedChannelHistory.size() - 1); + } + } + + if (historyEntry != null) { + historyEntry.setDateUnlinked(date); + } + + firePropertyChange(PROPERTY_LINKED_CHANNEL, oldLinkedChannel, null); } - this.linkedChannel = null; - firePropertyChange(PROPERTY_LINKED_CHANNEL, oldLinkedChannel, null); } /* MeetMe user */ - public MeetMeUserImpl getMeetMeUser() - { + public MeetMeUserImpl getMeetMeUser() { return meetMeUserImpl; } - void setMeetMeUserImpl(MeetMeUserImpl meetMeUserImpl) - { + void setMeetMeUserImpl(MeetMeUserImpl meetMeUserImpl) { final MeetMeUserImpl oldMeetMeUserImpl = this.meetMeUserImpl; this.meetMeUserImpl = meetMeUserImpl; firePropertyChange(PROPERTY_MEET_ME_USER, oldMeetMeUserImpl, meetMeUserImpl); @@ -596,99 +577,81 @@ void setMeetMeUserImpl(MeetMeUserImpl meetMeUserImpl) // action methods - public void hangup() throws ManagerCommunicationException, NoSuchChannelException - { + public void hangup() throws ManagerCommunicationException, NoSuchChannelException { hangup(null); } - public void hangup(HangupCause cause) throws ManagerCommunicationException, NoSuchChannelException - { + public void hangup(HangupCause cause) throws ManagerCommunicationException, NoSuchChannelException { final HangupAction action; final ManagerResponse response; - if (cause != null) - { + if (cause != null) { setVariable(CAUSE_VARIABLE_NAME, Integer.toString(cause.getCode())); action = new HangupAction(name, cause.getCode()); - } - else - { + } else { action = new HangupAction(name); } response = server.sendAction(action); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public void setAbsoluteTimeout(int seconds) throws ManagerCommunicationException, NoSuchChannelException - { + public void setAbsoluteTimeout(int seconds) throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; response = server.sendAction(new AbsoluteTimeoutAction(name, seconds)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public void redirect(String context, String exten, int priority) throws ManagerCommunicationException, - NoSuchChannelException - { + public void redirect(String context, String exten, int priority) + throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; response = server.sendAction(new RedirectAction(name, context, exten, priority)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public void redirectBothLegs(String context, String exten, int priority) throws ManagerCommunicationException, - NoSuchChannelException - { + public void redirectBothLegs(String context, String exten, int priority) + throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; - if (linkedChannel == null) - { - response = server.sendAction(new RedirectAction(name, context, exten, priority)); - } - else - { - response = server.sendAction(new RedirectAction(name, linkedChannel.getName(), context, exten, priority, - context, exten, priority)); + try (LockCloser closer = linkedChannels.withLock()) { + if (linkedChannels.isEmpty()) { + response = server.sendAction(new RedirectAction(name, context, exten, priority)); + } else { + response = server.sendAction(new RedirectAction(name, linkedChannels.get(0).getName(), context, exten, + priority, context, exten, priority)); + } } - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public String getVariable(String variable) throws ManagerCommunicationException, NoSuchChannelException - { + public String getVariable(String variable) throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; String value; - synchronized (variables) - { + try (LockCloser closer = variables.withLock()) { value = variables.get(variable); - if (value != null) - { + if (value != null) { return value; } response = server.sendAction(new GetVarAction(name, variable)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } value = response.getAttribute("Value"); - if (value == null) - { + if (value == null) { value = response.getAttribute(variable); // for Asterisk 1.0.x } @@ -697,239 +660,239 @@ public String getVariable(String variable) throws ManagerCommunicationException, return value; } - public void setVariable(String variable, String value) throws ManagerCommunicationException, NoSuchChannelException - { + public void setVariable(String variable, String value) throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; response = server.sendAction(new SetVarAction(name, variable, value)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } - synchronized (variables) - { + try (LockCloser closer = variables.withLock()) { variables.put(variable, value); } } - public void playDtmf(String digit) throws ManagerCommunicationException, NoSuchChannelException, IllegalArgumentException - { + public void playDtmf(String digit) throws ManagerCommunicationException, NoSuchChannelException, IllegalArgumentException { ManagerResponse response; - if (digit == null) - { + if (digit == null) { throw new IllegalArgumentException("DTMF digit to send must not be null"); } response = server.sendAction(new PlayDtmfAction(name, digit)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public void startMonitoring(String filename) throws ManagerCommunicationException, NoSuchChannelException - { + public void startMonitoring(String filename) throws ManagerCommunicationException, NoSuchChannelException { startMonitoring(filename, null, false); } - public void startMonitoring(String filename, String format) throws ManagerCommunicationException, NoSuchChannelException - { + public void startMonitoring(String filename, String format) throws ManagerCommunicationException, NoSuchChannelException { startMonitoring(filename, format, false); } - public void startMonitoring(String filename, String format, boolean mix) throws ManagerCommunicationException, - NoSuchChannelException - { + public void startMonitoring(String filename, String format, boolean mix) + throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; response = server.sendAction(new MonitorAction(name, filename, format, mix)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public void changeMonitoring(String filename) throws ManagerCommunicationException, NoSuchChannelException, IllegalArgumentException - { + public void changeMonitoring(String filename) + throws ManagerCommunicationException, NoSuchChannelException, IllegalArgumentException { ManagerResponse response; - if (filename == null) - { + if (filename == null) { throw new IllegalArgumentException("New filename must not be null"); } response = server.sendAction(new ChangeMonitorAction(name, filename)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public void stopMonitoring() throws ManagerCommunicationException, NoSuchChannelException - { + public void stopMonitoring() throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; response = server.sendAction(new StopMonitorAction(name)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public void pauseMonitoring() throws ManagerCommunicationException, NoSuchChannelException - { + public void pauseMonitoring() throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; response = server.sendAction(new PauseMonitorAction(name)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public void unpauseMonitoring() throws ManagerCommunicationException, NoSuchChannelException - { + public void unpauseMonitoring() throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; response = server.sendAction(new UnpauseMonitorAction(name)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { + throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); + } + } + + public void pauseMixMonitor(MixMonitorDirection direction) + throws ManagerCommunicationException, NoSuchChannelException, RecordingException { + ManagerResponse response; + response = server.sendAction(new PauseMixMonitorAction(this.name, 1, direction.getStateName())); + if (response instanceof ManagerError) { + if (response.getMessage().equals("Cannot set mute flag")) { + throw new RecordingException(response.getMessage() + " on channel: '" + name); + } throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); } } - public Extension getParkedAt() - { - // warning: the context of this extension will be null until we get the context property from + public void unPauseMixMonitor(MixMonitorDirection direction) + throws ManagerCommunicationException, NoSuchChannelException, RecordingException { + ManagerResponse response; + response = server.sendAction(new PauseMixMonitorAction(this.name, 0, direction.getStateName())); + if (response instanceof ManagerError) { + if (response.getMessage().equals("Cannot set mute flag")) { + throw new RecordingException(response.getMessage() + " on channel: '" + name); + } + throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage()); + } + } + + public Extension getParkedAt() { + // warning: the context of this extension will be null until we get the + // context property from // the parked call event! return parkedAt; } - void updateVariable(String name, String value) - { - synchronized (variables) - { + public String getParkingLot() { + return this.parkingLot; + } + + void setParkedAt(Extension parkedAt, String parkingLot) { + final Extension oldParkedAt = this.parkedAt; + final String oldParkingLot = this.parkingLot; + + this.parkedAt = parkedAt; + this.parkingLot = parkingLot; + firePropertyChange(PROPERTY_PARKED_AT, oldParkedAt, parkedAt); + firePropertyChange(PROPERTY_PARKING_LOT, oldParkingLot, parkingLot); + } + + void updateVariable(String name, String value) { + try (LockCloser closer = variables.withLock()) { // final String oldValue = variables.get(name); variables.put(name, value); // TODO add notification for updated channel variables } } - public Map getVariables() - { - synchronized (variables) - { - return new HashMap(variables); + public Map getVariables() { + try (LockCloser closer = variables.withLock()) { + return new HashMap<>(variables); } } - public Character getDtmfReceived() - { + public Character getDtmfReceived() { return this.dtmfReceived; } - public Character getDtmfSent() - { + public Character getDtmfSent() { return this.dtmfSent; } - void dtmfReceived(Character digit) - { + void dtmfReceived(Character digit) { final Character oldDtmfReceived = this.dtmfReceived; this.dtmfReceived = digit; firePropertyChange(PROPERTY_DTMF_RECEIVED, oldDtmfReceived, digit); } - void dtmfSent(Character digit) - { + void dtmfSent(Character digit) { final Character oldDtmfSent = this.dtmfSent; this.dtmfSent = digit; firePropertyChange(PROPERTY_DTMF_SENT, oldDtmfSent, digit); } - void setParkedAt(Extension parkedAt) - { - final Extension oldParkedAt = this.parkedAt; - - this.parkedAt = parkedAt; - firePropertyChange(PROPERTY_PARKED_AT, oldParkedAt, parkedAt); - } - - public AsteriskQueueEntryImpl getQueueEntry() - { + public AsteriskQueueEntryImpl getQueueEntry() { return queueEntryImpl; } - void setQueueEntry(AsteriskQueueEntryImpl queueEntry) - { + void setQueueEntry(AsteriskQueueEntryImpl queueEntry) { final AsteriskQueueEntry oldQueueEntry = this.queueEntryImpl; this.queueEntryImpl = queueEntry; firePropertyChange(PROPERTY_QUEUE_ENTRY, oldQueueEntry, queueEntry); } + public boolean isMonitored() { + return this.isMonitored; + } + + void setMonitored(boolean monitored) { + final boolean oldMonitored = this.isMonitored; + + this.isMonitored = monitored; + firePropertyChange(PROPERTY_MONITORED, oldMonitored, monitored); + } + @Override - public String toString() - { - final StringBuffer sb; - final AsteriskChannel dialedChannel; - final AsteriskChannel dialingChannel; - final AsteriskChannel linkedChannel; + public String toString() { + final StringBuilder sb; + final LockableList dialingChannel; + final LockableList linkedChannel; - sb = new StringBuffer("AsteriskChannel["); + sb = new StringBuilder("AsteriskChannel["); - synchronized (this) - { + try (LockCloser closer = this.withLock()) { sb.append("id='").append(getId()).append("',"); sb.append("name='").append(getName()).append("',"); sb.append("callerId='").append(getCallerId()).append("',"); sb.append("state='").append(getState()).append("',"); sb.append("account='").append(getAccount()).append("',"); sb.append("dateOfCreation=").append(getDateOfCreation()).append(","); - dialedChannel = this.dialedChannel; - dialingChannel = this.dialingChannel; - linkedChannel = this.linkedChannel; + dialingChannel = this.dialingChannels; + linkedChannel = this.linkedChannels; } - if (dialedChannel == null) - { + if (dialedChannels.isEmpty()) { sb.append("dialedChannel=null,"); - } - else - { + } else { sb.append("dialedChannel=AsteriskChannel["); - synchronized (dialedChannel) - { - sb.append("id='").append(dialedChannel.getId()).append("',"); - sb.append("name='").append(dialedChannel.getName()).append("'],"); + try (LockCloser closer = dialedChannels.withLock()) { + for (AsteriskChannel dialedChannel : dialedChannels) { + sb.append("[id='").append(dialedChannel.getId()).append("',"); + sb.append("name='").append(dialedChannel.getName()).append("'],"); + } + sb.append("],"); } } - if (dialingChannel == null) - { + if (dialingChannel.isEmpty()) { sb.append("dialingChannel=null,"); - } - else - { + } else { sb.append("dialingChannel=AsteriskChannel["); - synchronized (dialingChannel) - { - sb.append("id='").append(dialingChannel.getId()).append("',"); - sb.append("name='").append(dialingChannel.getName()).append("'],"); - } - } - if (linkedChannel == null) - { - sb.append("linkedChannel=null"); - } - else - { - sb.append("linkedChannel=AsteriskChannel["); - synchronized (linkedChannel) - { - sb.append("id='").append(linkedChannel.getId()).append("',"); - sb.append("name='").append(linkedChannel.getName()).append("']"); + sb.append("id='").append(dialingChannel.get(0).getId()).append("',"); + sb.append("name='").append(dialingChannel.get(0).getName()).append("'],"); + } + try (LockCloser closer = linkedChannel.withLock()) { + if (linkedChannel.isEmpty()) { + sb.append("linkedChannel=null"); + } else { + sb.append("linkedChannel=AsteriskChannel["); + { + sb.append("id='").append(linkedChannel.get(0).getId()).append("',"); + sb.append("name='").append(linkedChannel.get(0).getName()).append("']"); + } } } sb.append("]"); diff --git a/src/main/java/org/asteriskjava/live/internal/AsteriskQueueEntryImpl.java b/src/main/java/org/asteriskjava/live/internal/AsteriskQueueEntryImpl.java index 62d45c546..d10f1856b 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskQueueEntryImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskQueueEntryImpl.java @@ -1,17 +1,17 @@ package org.asteriskjava.live.internal; -import java.util.Date; - import org.asteriskjava.live.AsteriskQueueEntry; import org.asteriskjava.live.QueueEntryState; +import org.asteriskjava.lock.Locker.LockCloser; + +import java.util.Date; /** * Default implementation of the AsteriskQueueEntry interface. * * @author gmi */ -class AsteriskQueueEntryImpl extends AbstractLiveObject implements AsteriskQueueEntry -{ +class AsteriskQueueEntryImpl extends AbstractLiveObject implements AsteriskQueueEntry { private final AsteriskQueueImpl queue; private final AsteriskChannelImpl channel; private final Date dateJoined; @@ -20,16 +20,18 @@ class AsteriskQueueEntryImpl extends AbstractLiveObject implements AsteriskQueue private QueueEntryState state; // the position as given by asterisk in the queue entry or join event. - // we cannot work reliably with it because asterisk doesn't tell us when it shifts the entries. + // we cannot work reliably with it because asterisk doesn't tell us when it + // shifts the entries. private int reportedPosition; - // The position of this entry in our representation of the queue. Will be set - // and maintained by the respective queue when the entry is added/removed/shifted + // The position of this entry in our representation of the queue. Will be + // set + // and maintained by the respective queue when the entry is + // added/removed/shifted private int position = POSITION_UNDETERMINED; - AsteriskQueueEntryImpl(AsteriskServerImpl server, AsteriskQueueImpl queue, - AsteriskChannelImpl channel, int reportedPosition, Date dateJoined) - { + AsteriskQueueEntryImpl(AsteriskServerImpl server, AsteriskQueueImpl queue, AsteriskChannelImpl channel, + int reportedPosition, Date dateJoined) { super(server); this.queue = queue; this.channel = channel; @@ -38,41 +40,35 @@ class AsteriskQueueEntryImpl extends AbstractLiveObject implements AsteriskQueue this.reportedPosition = reportedPosition; } - public String getChannelName() - { + public String getChannelName() { return channel.getName(); } - public AsteriskQueueImpl getQueue() - { + public AsteriskQueueImpl getQueue() { return queue; } - public AsteriskChannelImpl getChannel() - { + public AsteriskChannelImpl getChannel() { return channel; } - public Date getDateJoined() - { + public Date getDateJoined() { return dateJoined; } - public Date getDateLeft() - { + public Date getDateLeft() { return dateLeft; } /** - * Sets the status to {@link QueueEntryState#LEFT} and dateLeft to the given date. + * Sets the status to {@link QueueEntryState#LEFT} and dateLeft to the given + * date. * * @param dateLeft the date this member left the queue. */ - void left(Date dateLeft) - { + void left(Date dateLeft) { QueueEntryState oldState; - synchronized (this) - { + try (LockCloser closer = this.withLock()) { oldState = this.state; this.dateLeft = dateLeft; this.state = QueueEntryState.LEFT; @@ -80,82 +76,70 @@ void left(Date dateLeft) firePropertyChange(PROPERTY_STATE, oldState, state); } - public QueueEntryState getState() - { + public QueueEntryState getState() { return state; } /** * Gets the position as reported by Asterisk when the entry was created. - * Currently we don't update this property as the entry shifts through the queue, - * see getPosition() instead. + * Currently we don't update this property as the entry shifts through the + * queue, see getPosition() instead. * * @return the position of the entry in the respective queue, starting at 1 */ - public int getReportedPosition() - { + public int getReportedPosition() { return reportedPosition; } /** - * Gets the position in the queue based on the queue's internal list - *

    - * As Asterisk doesn't send events when it shifts entries in the queue - * we'll base our positions on our internal queue entries ordered list. - * It should be coherent as entries are always added at the end of the queue - * and we don't mind if it is different from asterisk's view as long as the - * relative order stays the same. Most of the time the position will be the same - * but right after asterisk removes an entry it could differ as the shift occurs - * asynchronously in asterisk queues. As a consequence we might have temporary holes - * in the asterisk numbering. + * Gets the position in the queue based on the queue's internal list
    + * As Asterisk doesn't send events when it shifts entries in the queue we'll + * base our positions on our internal queue entries ordered list. It should + * be coherent as entries are always added at the end of the queue and we + * don't mind if it is different from asterisk's view as long as the + * relative order stays the same. Most of the time the position will be the + * same but right after asterisk removes an entry it could differ as the + * shift occurs asynchronously in asterisk queues. As a consequence we might + * have temporary holes in the asterisk numbering. * * @return the position of the entry in the respective queue, starting at 1 */ - public int getPosition() - { + public int getPosition() { return position; } - void setPosition(int position) - { + void setPosition(int position) { int oldPosition = this.position; this.position = position; firePropertyChange(PROPERTY_POSITION, oldPosition, position); } - void setReportedPosition(int reportedPosition) - { + void setReportedPosition(int reportedPosition) { int oldPosition = this.reportedPosition; this.reportedPosition = reportedPosition; firePropertyChange(PROPERTY_REPORTED_POSITION, oldPosition, reportedPosition); } @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; int systemHashcode; - sb = new StringBuffer("AsteriskQueueEntry["); + sb = new StringBuilder("AsteriskQueueEntry["); - synchronized (this) - { + try (LockCloser closer = this.withLock()) { sb.append("dateJoined=").append(getDateJoined()).append(","); sb.append("postition=").append(getPosition()).append(","); sb.append("dateLeft=").append(getDateLeft()).append(","); systemHashcode = System.identityHashCode(this); } - if (channel != null) - { + if (channel != null) { sb.append("channel=AsteriskChannel["); - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { sb.append("id='").append(channel.getId()).append("',"); sb.append("name='").append(channel.getName()).append("'],"); } - } - else - { + } else { sb.append("channel=null,"); } sb.append("systemHashcode=").append(systemHashcode); diff --git a/src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java b/src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java index 2b0bf4c78..b3b922ef6 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java @@ -16,46 +16,40 @@ */ package org.asteriskjava.live.internal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; - import org.asteriskjava.live.AsteriskQueue; import org.asteriskjava.live.AsteriskQueueEntry; import org.asteriskjava.live.AsteriskQueueListener; import org.asteriskjava.live.AsteriskQueueMember; +import org.asteriskjava.lock.LockableList; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.util.AstUtil; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +import java.util.*; + /** * Default implementation of the AsteriskQueue interface. * * @author srt * @version $Id$ */ -class AsteriskQueueImpl extends AbstractLiveObject implements AsteriskQueue -{ +class AsteriskQueueImpl extends AbstractLiveObject implements AsteriskQueue { /** * TimerTask that monitors exceeding service levels. * - * @author Patrick Breucking + * @author Patrick Breucking */ - private class ServiceLevelTimerTask extends TimerTask - { + private class ServiceLevelTimerTask extends TimerTask { private final AsteriskQueueEntry entry; - ServiceLevelTimerTask(AsteriskQueueEntry entry) - { + ServiceLevelTimerTask(AsteriskQueueEntry entry) { this.entry = entry; } @Override - public void run() - { + public void run() { fireServiceLevelExceeded(entry); } } @@ -65,97 +59,244 @@ public void run() private Integer max; private String strategy; private Integer serviceLevel; + + /** + * 101118 Octavio Luna Agregado para Ver cambios en Vivo + **/ + private Integer calls; + private Integer holdTime; + private Integer talkTime; + private Integer completed; + private Integer abandoned; + private Double serviceLevelPerf; + /****/ + private Integer weight; - private final ArrayList entries; + private final LockableList entries; private final Timer timer; - private final HashMap members; - private final List listeners; - private final HashMap serviceLevelTimerTasks; + private final LockableMap members; + private final LockableList listeners; + private final LockableMap serviceLevelTimerTasks; - AsteriskQueueImpl(AsteriskServerImpl server, String name, Integer max, - String strategy, Integer serviceLevel, Integer weight) - { + AsteriskQueueImpl(AsteriskServerImpl server, String name, Integer max, String strategy, Integer serviceLevel, + Integer weight, Integer calls, Integer holdTime, Integer talkTime, Integer completed, Integer abandoned, + Double serviceLevelPerf) { super(server); this.name = name; this.max = max; this.strategy = strategy; this.serviceLevel = serviceLevel; this.weight = weight; - entries = new ArrayList(25); - listeners = new ArrayList(); - members = new HashMap(); + entries = new LockableList<>(new ArrayList<>(25)); + listeners = new LockableList<>(new ArrayList<>()); + members = new LockableMap<>(new HashMap<>()); timer = new Timer("ServiceLevelTimer-" + name, true); - serviceLevelTimerTasks = new HashMap(); + serviceLevelTimerTasks = new LockableMap<>(new HashMap<>()); + this.calls = calls; + this.holdTime = holdTime; + this.talkTime = talkTime; + this.completed = completed; + this.abandoned = abandoned; + this.serviceLevelPerf = serviceLevelPerf; + + stampLastUpdate(); } - void cancelServiceLevelTimer() - { + void cancelServiceLevelTimer() { timer.cancel(); } - public String getName() - { + public String getName() { return name; } - public Integer getMax() - { + public Integer getMax() { return max; } - public String getStrategy() - { + public String getStrategy() { return strategy; } - void setMax(Integer max) - { - this.max = max; + /** + * @param max + * @return true if value updated, false otherwise + */ + boolean setMax(Integer max) { + if (!AstUtil.isEqual(this.max, max)) { + this.max = max; + stampLastUpdate(); + return true; + } + return false; } - public Integer getServiceLevel() - { + public Integer getServiceLevel() { return serviceLevel; } - void setServiceLevel(Integer serviceLevel) - { - this.serviceLevel = serviceLevel; + /** + * @param serviceLevel + * @return + */ + boolean setServiceLevel(Integer serviceLevel) { + if (!AstUtil.isEqual(this.serviceLevel, serviceLevel)) { + this.serviceLevel = serviceLevel; + stampLastUpdate(); + return true; + } + return false; + + } + + @Override + public Integer getCalls() { + return calls; + } + + /** + * @param calls + * @return true if value updated, false otherwise + */ + boolean setCalls(Integer calls) { + if (!AstUtil.isEqual(this.calls, calls)) { + this.calls = calls; + stampLastUpdate(); + return true; + } + return false; + } + + @Override + public Integer getWaiting() { + return calls; + } + + @Override + public Integer getHoldTime() { + return holdTime; + } + + /** + * @param holdTime + * @return true if value updated, false otherwise + */ + boolean setHoldTime(Integer holdTime) { + if (!AstUtil.isEqual(this.holdTime, holdTime)) { + this.holdTime = holdTime; + stampLastUpdate(); + return true; + } + return false; + } + + @Override + public Integer getTalkTime() { + return talkTime; + } + + /** + * @param talkTime + * @return true if value updated, false otherwise + */ + boolean setTalkTime(Integer talkTime) { + if (!AstUtil.isEqual(this.talkTime, talkTime)) { + this.talkTime = talkTime; + stampLastUpdate(); + return true; + } + return false; + } + + @Override + public Integer getCompleted() { + return completed; + } + + /** + * @param completed + * @return true if value updated, false otherwise + */ + boolean setCompleted(Integer completed) { + if (!AstUtil.isEqual(this.completed, completed)) { + this.completed = completed; + stampLastUpdate(); + return true; + } + return false; + } + + @Override + public Integer getAbandoned() { + return abandoned; + } + + /** + * @param abandoned + * @return true if value updated, false otherwise + */ + boolean setAbandoned(Integer abandoned) { + if (!AstUtil.isEqual(this.abandoned, abandoned)) { + this.abandoned = abandoned; + stampLastUpdate(); + return true; + } + + return false; + } + + @Override + public Double getServiceLevelPerf() { + return serviceLevelPerf; + } + + /** + * @param serviceLevelPerf + * @return true if value updated, false otherwise + */ + boolean setServiceLevelPerf(Double serviceLevelPerf) { + if (!AstUtil.isEqual(this.serviceLevelPerf, serviceLevelPerf)) { + this.serviceLevelPerf = serviceLevelPerf; + stampLastUpdate(); + return true; + } + return false; } - public Integer getWeight() - { + public Integer getWeight() { return weight; } - void setWeight(Integer weight) - { - this.weight = weight; + /** + * @param weight + * @return true if value updated, false otherwise + */ + boolean setWeight(Integer weight) { + if (!AstUtil.isEqual(this.weight, weight)) { + this.weight = weight; + stampLastUpdate(); + return true; + } + return false; } - public List getEntries() - { - synchronized (entries) - { + public List getEntries() { + try (LockCloser closer = entries.withLock()) { return new ArrayList(entries); } } /** - * Shifts the position of the queue entries if needed - * (and fire PCE on queue entries if appropriate). + * Shifts the position of the queue entries if needed (and fire PCE on queue + * entries if appropriate). */ - private void shift() - { + private void shift() { int currentPos = 1; // Asterisk starts at 1 - synchronized (entries) - { - for (AsteriskQueueEntryImpl qe : entries) - { + try (LockCloser closer = entries.withLock()) { + for (AsteriskQueueEntryImpl qe : entries) { // Only set (and fire PCE on qe) if necessary - if (qe.getPosition() != currentPos) - { + if (qe.getPosition() != currentPos) { qe.setPosition(currentPos); } currentPos++; @@ -164,7 +305,8 @@ private void shift() } /** - * Creates a new AsteriskQueueEntry, adds it to this queue.

    + * Creates a new AsteriskQueueEntry, adds it to this queue. + *

    * Fires: *

      *
    • PCE on channel
    • @@ -174,26 +316,22 @@ private void shift() *
    * * @param channel the channel that joined the queue - * @param reportedPosition the position as given by Asterisk (currently not used) + * @param reportedPosition the position as given by Asterisk (currently not + * used) * @param dateReceived the date the hannel joined the queue */ - void createNewEntry(AsteriskChannelImpl channel, int reportedPosition, Date dateReceived) - { + void createNewEntry(AsteriskChannelImpl channel, int reportedPosition, Date dateReceived) { AsteriskQueueEntryImpl qe = new AsteriskQueueEntryImpl(server, this, channel, reportedPosition, dateReceived); - long delay = serviceLevel * 1000L; - if (delay > 0) - { - ServiceLevelTimerTask timerTask = new ServiceLevelTimerTask(qe); - timer.schedule(timerTask, delay); - synchronized (serviceLevelTimerTasks) - { - serviceLevelTimerTasks.put(qe, timerTask); + try (LockCloser closer = entries.withLock()) { + if (getEntry(channel.getName()) != null) { + if (logger.isDebugEnabled()) { + logger.debug("Ignored duplicate queue entry during population in queue " + name + " for channel " + + channel.getName()); + } + return; } - } - synchronized (entries) - { entries.add(qe); // at the end of the list // Keep the lock ! @@ -202,9 +340,19 @@ void createNewEntry(AsteriskChannelImpl channel, int reportedPosition, Date date shift(); } + long delay = serviceLevel * 1000L; + if (delay > 0) { + ServiceLevelTimerTask timerTask = new ServiceLevelTimerTask(qe); + timer.schedule(timerTask, delay); + try (LockCloser closer = serviceLevelTimerTasks.withLock()) { + serviceLevelTimerTasks.put(qe, timerTask); + } + } + // Set the channel property ony here as queue entries and channels // maintain a reciprocal reference. - // That way property change on channel and new entry event on queue will be + // That way property change on channel and new entry event on queue will + // be // lanched when BOTH channel and queue are correctly set. channel.setQueueEntry(qe); fireNewEntry(qe); @@ -212,7 +360,8 @@ void createNewEntry(AsteriskChannelImpl channel, int reportedPosition, Date date } /** - * Removes the given queue entry from the queue.

    + * Removes the given queue entry from the queue. + *

    * Fires if needed: *

      *
    • PCE on channel
    • @@ -223,12 +372,9 @@ void createNewEntry(AsteriskChannelImpl channel, int reportedPosition, Date date * @param entry an existing entry object. * @param dateReceived the remove event was received. */ - void removeEntry(AsteriskQueueEntryImpl entry, Date dateReceived) - { - synchronized (serviceLevelTimerTasks) - { - if (serviceLevelTimerTasks.containsKey(entry)) - { + void removeEntry(AsteriskQueueEntryImpl entry, Date dateReceived) { + try (LockCloser closer = serviceLevelTimerTasks.withLock()) { + if (serviceLevelTimerTasks.containsKey(entry)) { ServiceLevelTimerTask timerTask = serviceLevelTimerTasks.get(entry); timerTask.cancel(); serviceLevelTimerTasks.remove(entry); @@ -236,20 +382,17 @@ void removeEntry(AsteriskQueueEntryImpl entry, Date dateReceived) } boolean changed; - synchronized (entries) - { + try (LockCloser closer = entries.withLock()) { changed = entries.remove(entry); - if (changed) - { + if (changed) { // Keep the lock ! shift(); } } // Fire outside lock - if (changed) - { + if (changed) { entry.getChannel().setQueueEntry(null); entry.left(dateReceived); fireEntryLeave(entry); @@ -257,22 +400,26 @@ void removeEntry(AsteriskQueueEntryImpl entry, Date dateReceived) } @Override - public String toString() - { - final StringBuffer sb; + public String toString() { + final StringBuilder sb; - sb = new StringBuffer("AsteriskQueue["); + sb = new StringBuilder("AsteriskQueue["); sb.append("name='").append(getName()).append("',"); sb.append("max='").append(getMax()).append("',"); sb.append("strategy='").append(getStrategy()).append("',"); sb.append("serviceLevel='").append(getServiceLevel()).append("',"); sb.append("weight='").append(getWeight()).append("',"); - synchronized (entries) - { + sb.append("calls='").append(getCalls()).append("',"); + sb.append("holdTime='").append(getHoldTime()).append("',"); + sb.append("talkTime='").append(getTalkTime()).append("',"); + sb.append("completed='").append(getCompleted()).append("',"); + sb.append("abandoned='").append(getAbandoned()).append("',"); + sb.append("serviceLevelPerf='").append(getServiceLevelPerf()).append("',"); + + try (LockCloser closer = entries.withLock()) { sb.append("entries='").append(entries.toString()).append("',"); } - synchronized (members) - { + try (LockCloser closer = members.withLock()) { sb.append("members='").append(members.toString()).append("',"); } sb.append("systemHashcode=").append(System.identityHashCode(this)); @@ -281,18 +428,14 @@ public String toString() return sb.toString(); } - public void addAsteriskQueueListener(AsteriskQueueListener listener) - { - synchronized (listeners) - { + public void addAsteriskQueueListener(AsteriskQueueListener listener) { + try (LockCloser closer = listeners.withLock()) { listeners.add(listener); } } - public void removeAsteriskQueueListener(AsteriskQueueListener listener) - { - synchronized (listeners) - { + public void removeAsteriskQueueListener(AsteriskQueueListener listener) { + try (LockCloser closer = listeners.withLock()) { listeners.remove(listener); } } @@ -302,18 +445,12 @@ public void removeAsteriskQueueListener(AsteriskQueueListener listener) * * @param entry that joins the queue */ - void fireNewEntry(AsteriskQueueEntryImpl entry) - { - synchronized (listeners) - { - for (AsteriskQueueListener listener : listeners) - { - try - { + void fireNewEntry(AsteriskQueueEntryImpl entry) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskQueueListener listener : listeners) { + try { listener.onNewEntry(entry); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in onNewEntry()", e); } } @@ -325,18 +462,12 @@ void fireNewEntry(AsteriskQueueEntryImpl entry) * * @param entry that leaves the queue. */ - void fireEntryLeave(AsteriskQueueEntryImpl entry) - { - synchronized (listeners) - { - for (AsteriskQueueListener listener : listeners) - { - try - { + void fireEntryLeave(AsteriskQueueEntryImpl entry) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskQueueListener listener : listeners) { + try { listener.onEntryLeave(entry); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in onEntryLeave()", e); } } @@ -344,22 +475,17 @@ void fireEntryLeave(AsteriskQueueEntryImpl entry) } /** - * Notifies all registered listener that a member has been added to the queue. + * Notifies all registered listener that a member has been added to the + * queue. * * @param member added to the queue */ - void fireMemberAdded(AsteriskQueueMemberImpl member) - { - synchronized (listeners) - { - for (AsteriskQueueListener listener : listeners) - { - try - { + void fireMemberAdded(AsteriskQueueMemberImpl member) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskQueueListener listener : listeners) { + try { listener.onMemberAdded(member); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in onMemberAdded()", e); } } @@ -367,22 +493,17 @@ void fireMemberAdded(AsteriskQueueMemberImpl member) } /** - * Notifies all registered listener that a member has been removed from the queue. + * Notifies all registered listener that a member has been removed from the + * queue. * * @param member that has been removed. */ - void fireMemberRemoved(AsteriskQueueMemberImpl member) - { - synchronized (listeners) - { - for (AsteriskQueueListener listener : listeners) - { - try - { + void fireMemberRemoved(AsteriskQueueMemberImpl member) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskQueueListener listener : listeners) { + try { listener.onMemberRemoved(member); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in onMemberRemoved()", e); } } @@ -394,15 +515,10 @@ void fireMemberRemoved(AsteriskQueueMemberImpl member) * * @see org.asteriskjava.live.AsteriskQueue#getMembers() */ - public Collection getMembers() - { - ArrayList listOfMembers = new ArrayList(members.size()); - synchronized (members) - { - for (AsteriskQueueMemberImpl asteriskQueueMember : members.values()) - { - listOfMembers.add(asteriskQueueMember); - } + public Collection getMembers() { + List listOfMembers = new ArrayList<>(members.size()); + try (LockCloser closer = members.withLock()) { + listOfMembers.addAll(members.values()); } return listOfMembers; } @@ -413,12 +529,9 @@ public Collection getMembers() * @param location ot the member * @return the member by its location. */ - AsteriskQueueMemberImpl getMember(String location) - { - synchronized (members) - { - if (members.containsKey(location)) - { + AsteriskQueueMemberImpl getMember(String location) { + try (LockCloser closer = members.withLock()) { + if (members.containsKey(location)) { return members.get(location); } } @@ -430,20 +543,17 @@ AsteriskQueueMemberImpl getMember(String location) * * @param member to add */ - void addMember(AsteriskQueueMemberImpl member) - { - synchronized (members) - { + void addMember(AsteriskQueueMemberImpl member) { + try (LockCloser closer = members.withLock()) { // Check if member already exists - if (members.containsValue(member)) - { + if (members.containsValue(member)) { return; } // If not, add the new member. logger.info("Adding new member to the queue " + getName() + ": " + member.toString()); members.put(member.getLocation(), member); } - + fireMemberAdded(member); } @@ -453,15 +563,12 @@ void addMember(AsteriskQueueMemberImpl member) * @param location of the member * @return the requested member. */ - AsteriskQueueMemberImpl getMemberByLocation(String location) - { + AsteriskQueueMemberImpl getMemberByLocation(String location) { AsteriskQueueMemberImpl member; - synchronized (members) - { + try (LockCloser closer = members.withLock()) { member = members.get(location); } - if (member == null) - { + if (member == null) { logger.error("Requested member at location " + location + " not found!"); } return member; @@ -472,18 +579,12 @@ AsteriskQueueMemberImpl getMemberByLocation(String location) * * @param member the changed member. */ - void fireMemberStateChanged(AsteriskQueueMemberImpl member) - { - synchronized (listeners) - { - for (AsteriskQueueListener listener : listeners) - { - try - { + void fireMemberStateChanged(AsteriskQueueMemberImpl member) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskQueueListener listener : listeners) { + try { listener.onMemberStateChange(member); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in onMemberStateChange()", e); } } @@ -496,14 +597,10 @@ void fireMemberStateChanged(AsteriskQueueMemberImpl member) * @param channelName The entry's channel name. * @return the queue entry if found, null otherwise. */ - AsteriskQueueEntryImpl getEntry(String channelName) - { - synchronized (entries) - { - for (AsteriskQueueEntryImpl entry : entries) - { - if (entry.getChannel().getName().equals(channelName)) - { + AsteriskQueueEntryImpl getEntry(String channelName) { + try (LockCloser closer = entries.withLock()) { + for (AsteriskQueueEntryImpl entry : entries) { + if (entry.getChannel().getName().equals(channelName)) { return entry; } } @@ -511,42 +608,31 @@ AsteriskQueueEntryImpl getEntry(String channelName) return null; } - /** * Removes a member from this queue. * * @param member the member to remove. */ - public void removeMember(AsteriskQueueMemberImpl member) - { - synchronized (members) - { + public void removeMember(AsteriskQueueMemberImpl member) { + try (LockCloser closer = members.withLock()) { // Check if member exists - if (!members.containsValue(member)) - { + if (!members.containsValue(member)) { return; } // If so, remove the member. - logger.info("Remove member from the queue " + getName() + ": " - + member.toString()); + logger.info("Remove member from the queue " + getName() + ": " + member.toString()); members.remove(member.getLocation()); } - + fireMemberRemoved(member); } - void fireServiceLevelExceeded(AsteriskQueueEntry entry) - { - synchronized (listeners) - { - for (AsteriskQueueListener listener : listeners) - { - try - { + void fireServiceLevelExceeded(AsteriskQueueEntry entry) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskQueueListener listener : listeners) { + try { listener.onEntryServiceLevelExceeded(entry); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in fireServiceLevelExceeded()", e); } } @@ -559,23 +645,20 @@ void fireServiceLevelExceeded(AsteriskQueueEntry entry) * @param position the position, starting at 1. * @return the queue entry if exiting at this position, null otherwise. */ - AsteriskQueueEntryImpl getEntry(int position) - { + AsteriskQueueEntryImpl getEntry(int position) { // positions in asterisk start at 1, but list starts at 0 position--; AsteriskQueueEntryImpl foundEntry = null; - synchronized (entries) - { - try - { + try (LockCloser closer = entries.withLock()) { + try { foundEntry = entries.get(position); - } - catch (IndexOutOfBoundsException e) - { + } catch (IndexOutOfBoundsException e) { // For consistency with the above method, - // swallow. We might indeed request the 1st one from time to time + // swallow. We might indeed request the 1st one from time to + // time } // NOPMD } return foundEntry; } + } diff --git a/src/main/java/org/asteriskjava/live/internal/AsteriskQueueMemberImpl.java b/src/main/java/org/asteriskjava/live/internal/AsteriskQueueMemberImpl.java index 3f7ed7b43..e37a44f61 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskQueueMemberImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskQueueMemberImpl.java @@ -17,26 +17,29 @@ package org.asteriskjava.live.internal; import org.asteriskjava.live.*; -import org.asteriskjava.manager.response.ManagerResponse; -import org.asteriskjava.manager.response.ManagerError; -import org.asteriskjava.manager.action.QueuePenaltyAction; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.action.QueuePauseAction; +import org.asteriskjava.manager.action.QueuePenaltyAction; +import org.asteriskjava.manager.response.ManagerError; +import org.asteriskjava.manager.response.ManagerResponse; +import org.asteriskjava.util.AstUtil; /** * Default implementation of a queue member. * - * @author Patrick Breucking + * @author Patrick Breucking * @version $Id$ * @see AsteriskQueueMember * @since 0.3.1 */ -class AsteriskQueueMemberImpl extends AbstractLiveObject implements AsteriskQueueMember -{ +class AsteriskQueueMemberImpl extends AbstractLiveObject implements AsteriskQueueMember { private AsteriskQueue queue; private QueueMemberState state; private String location; private Integer penalty; private boolean paused; + private Integer callsTaken; + private Long lastCall; private String membership; /** @@ -46,152 +49,199 @@ class AsteriskQueueMemberImpl extends AbstractLiveObject implements AsteriskQueu * @param queue queue this member is registered to. * @param location location of member. * @param state state of this member. - * @param paused true if this member is currently paused, false otherwise. + * @param paused true if this member is currently paused, + * false otherwise. * @param penalty penalty of this member. - * @param membership "dynamic" if the added member is a dynamic queue member, "static" - * if the added member is a static queue member. + * @param membership "dynamic" if the added member is a dynamic queue + * member, "static" if the added member is a static queue member. */ - AsteriskQueueMemberImpl(final AsteriskServerImpl server, - final AsteriskQueueImpl queue, String location, - QueueMemberState state, boolean paused, - Integer penalty, String membership) - { + AsteriskQueueMemberImpl(final AsteriskServerImpl server, final AsteriskQueueImpl queue, String location, + QueueMemberState state, boolean paused, Integer penalty, String membership, Integer callsTaken, Long lastCall) { super(server); this.queue = queue; this.location = location; this.state = state; this.penalty = penalty; this.paused = paused; + this.callsTaken = callsTaken; + this.lastCall = lastCall; this.membership = membership; } - public AsteriskQueue getQueue() - { + public AsteriskQueue getQueue() { return queue; } - public String getLocation() - { + public String getLocation() { return location; } - public QueueMemberState getState() - { + public QueueMemberState getState() { return state; } - @Deprecated public boolean getPaused() - { + @Override + public Integer getCallsTaken() { + return callsTaken; + } + + public void setCallsTaken(Integer callsTaken) { + this.callsTaken = callsTaken; + } + + /** + * Returns the time the last successful call answered by the added member + * was hungup. + * + * @return the time (in seconds since 01/01/1970) the last successful call + * answered by the added member was hungup. + */ + @Override + public Long getLastCall() { + return lastCall; + } + + public void setLastCall(Long lastCall) { + this.lastCall = lastCall; + } + + @Deprecated + public boolean getPaused() { return isPaused(); } - public boolean isPaused() - { + public boolean isPaused() { return paused; } - public void setPaused(boolean paused) throws ManagerCommunicationException, NoSuchInterfaceException - { + public void setPaused(boolean paused) throws ManagerCommunicationException, NoSuchInterfaceException { sendPauseAction(new QueuePauseAction(location, queue.getName(), paused)); } - public void setPausedAll(boolean paused) throws ManagerCommunicationException, NoSuchInterfaceException - { + public void setPausedAll(boolean paused) throws ManagerCommunicationException, NoSuchInterfaceException { sendPauseAction(new QueuePauseAction(location, paused)); } - private void sendPauseAction(QueuePauseAction action) throws ManagerCommunicationException, NoSuchInterfaceException - { + private void sendPauseAction(QueuePauseAction action) throws ManagerCommunicationException, NoSuchInterfaceException { final ManagerResponse response = server.sendAction(action); - if (response instanceof ManagerError) - { - //Message: Interface not found - if (action.getQueue() != null) - { - //Message: Interface not found - throw new NoSuchInterfaceException("Unable to change paused state for '" + action.getInterface() + "' on '" + - action.getQueue() + "': " + response.getMessage()); - } - else - { - throw new NoSuchInterfaceException("Unable to change paused state for '" + action.getInterface() + - "' on all queues: " + response.getMessage()); + if (response instanceof ManagerError) { + // Message: Interface not found + if (action.getQueue() != null) { + // Message: Interface not found + throw new NoSuchInterfaceException("Unable to change paused state for '" + action.getInterface() + "' on '" + + action.getQueue() + "': " + response.getMessage()); } + throw new NoSuchInterfaceException("Unable to change paused state for '" + action.getInterface() + + "' on all queues: " + response.getMessage()); } } - public String getMembership() - { + public String getMembership() { return membership; } - public boolean isStatic() - { - return membership != null && "static".equals(membership); + public boolean isStatic() { + return "static".equals(membership); } - public boolean isDynamic() - { - return membership != null && "dynamic".equals(membership); + public boolean isDynamic() { + return "dynamic".equals(membership); } - public Integer getPenalty() - { + public Integer getPenalty() { return penalty; } - public void setPenalty(int penalty) throws IllegalArgumentException, ManagerCommunicationException, InvalidPenaltyException - { - if (penalty < 0) - { + public void setPenalty(int penalty) + throws IllegalArgumentException, ManagerCommunicationException, InvalidPenaltyException { + if (penalty < 0) { throw new IllegalArgumentException("Penalty must not be negative"); } - final ManagerResponse response = server.sendAction( - new QueuePenaltyAction(location, penalty, queue.getName())); - if (response instanceof ManagerError) - { - throw new InvalidPenaltyException("Unable to set penalty for '" + location + "' on '" + - queue.getName() + "': " + response.getMessage()); + final ManagerResponse response = server.sendAction(new QueuePenaltyAction(location, penalty, queue.getName())); + if (response instanceof ManagerError) { + throw new InvalidPenaltyException( + "Unable to set penalty for '" + location + "' on '" + queue.getName() + "': " + response.getMessage()); } } @Override - public String toString() - { - final StringBuffer sb; + public String toString() { + final StringBuilder sb; - sb = new StringBuffer("AsteriskQueueMember["); + sb = new StringBuilder("AsteriskQueueMember["); sb.append("location='").append(location).append("'"); sb.append("state='").append(state).append("'"); sb.append("paused='").append(paused).append("'"); sb.append("membership='").append(membership).append("'"); sb.append("queue='").append(queue.getName()).append("'"); + sb.append("callsTaken='").append(getCallsTaken()).append("'"); + sb.append("lastCall='").append(getLastCall()).append("'"); sb.append("systemHashcode=").append(System.identityHashCode(this)); sb.append("]"); return sb.toString(); } - synchronized void stateChanged(QueueMemberState state) - { - QueueMemberState oldState = this.state; - this.state = state; - firePropertyChange(PROPERTY_STATE, oldState, state); + boolean stateChanged(QueueMemberState state) { + try (LockCloser closer = this.withLock()) { + if (!AstUtil.isEqual(this.state, state)) { + QueueMemberState oldState = this.state; + this.state = state; + firePropertyChange(PROPERTY_STATE, oldState, state); + return true; + } + return false; + } } - synchronized void penaltyChanged(Integer penalty) - { - Integer oldPenalty = this.penalty; - this.penalty = penalty; - firePropertyChange(PROPERTY_PENALTY, oldPenalty, penalty); + boolean penaltyChanged(Integer penalty) { + try (LockCloser closer = this.withLock()) { + if (!AstUtil.isEqual(this.penalty, penalty)) { + Integer oldPenalty = this.penalty; + this.penalty = penalty; + firePropertyChange(PROPERTY_PENALTY, oldPenalty, penalty); + return true; + } + + return false; + } } - synchronized void pausedChanged(boolean paused) - { - boolean oldPaused = this.paused; - this.paused = paused; - firePropertyChange(PROPERTY_PAUSED, oldPaused, paused); + boolean pausedChanged(boolean paused) { + try (LockCloser closer = this.withLock()) { + if (!AstUtil.isEqual(this.paused, paused)) { + boolean oldPaused = this.paused; + this.paused = paused; + firePropertyChange(PROPERTY_PAUSED, oldPaused, paused); + return true; + } + return false; + } + } + + boolean callsTakenChanged(Integer callsTaken) { + try (LockCloser closer = this.withLock()) { + if (!AstUtil.isEqual(this.callsTaken, callsTaken)) { + Integer oldcallsTaken = this.callsTaken; + this.callsTaken = callsTaken; + firePropertyChange(PROPERTY_CALLSTAKEN, oldcallsTaken, callsTaken); + return true; + } + return false; + } + } + + boolean lastCallChanged(Long lastCall) { + try (LockCloser closer = this.withLock()) { + if (!AstUtil.isEqual(this.lastCall, lastCall)) { + Long oldlastCall = this.lastCall; + this.lastCall = lastCall; + firePropertyChange(PROPERTY_LASTCALL, oldlastCall, lastCall); + return true; + } + return false; + } } } diff --git a/src/main/java/org/asteriskjava/live/internal/AsteriskServerImpl.java b/src/main/java/org/asteriskjava/live/internal/AsteriskServerImpl.java index d87b5a68c..7062e5ad7 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskServerImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskServerImpl.java @@ -16,17 +16,22 @@ */ package org.asteriskjava.live.internal; +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.config.ConfigFile; import org.asteriskjava.live.*; +import org.asteriskjava.lock.Lockable; +import org.asteriskjava.lock.LockableList; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.LockableSet; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.*; import org.asteriskjava.manager.action.*; import org.asteriskjava.manager.event.*; import org.asteriskjava.manager.response.*; +import org.asteriskjava.util.AstUtil; import org.asteriskjava.util.DateUtil; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -import org.asteriskjava.util.AstUtil; -import org.asteriskjava.config.ConfigFile; -import org.asteriskjava.AsteriskVersion; import java.util.*; import java.util.concurrent.atomic.AtomicLong; @@ -39,8 +44,7 @@ * @author srt * @version $Id$ */ -public class AsteriskServerImpl implements AsteriskServer, ManagerEventListener -{ +public class AsteriskServerImpl extends Lockable implements AsteriskServer, ManagerEventListener { private static final String ACTION_ID_PREFIX_ORIGINATE = "AJ_ORIGINATE_"; private static final String SHOW_VERSION_COMMAND = "show version"; private static final String SHOW_VERSION_1_6_COMMAND = "core show version"; @@ -58,21 +62,17 @@ public class AsteriskServerImpl implements AsteriskServer, ManagerEventListener */ private ManagerConnection eventConnection; private ManagerEventListener eventListener = null; - private ManagerEventListenerProxy managerEventListenerProxy = null; + private ManagerEventListenerProxy managerEventListenerProxy; private boolean initialized = false; + private boolean initializing = false; - /** - * A pool of manager connections to use for sending actions to Asterisk. - */ - private final ManagerConnectionPool connectionPool; - - private final List listeners; + final LockableSet listeners; - private final ChannelManager channelManager; - private final MeetMeManager meetMeManager; - private final QueueManager queueManager; - private final AgentManager agentManager; + final ChannelManager channelManager; + final MeetMeManager meetMeManager; + final QueueManager queueManager; + final AgentManager agentManager; /** * The exact version string of the Asterisk server we are connected to. @@ -89,12 +89,12 @@ public class AsteriskServerImpl implements AsteriskServer, ManagerEventListener *

      * Contains null until lazily initialized. */ - private Map versions; + private LockableMap versions; /** * Maps the traceId to the corresponding callback data. */ - private final Map originateCallbacks; + private final LockableMap originateCallbacks; private final AtomicLong idCounter; @@ -107,20 +107,32 @@ public class AsteriskServerImpl implements AsteriskServer, ManagerEventListener private boolean skipQueues; /** - * Set to true to not handle ManagerEvents in the reader - * tread but process them asynchronously. This is a good idea :) + * Set to true to not handle ManagerEvents in the reader tread + * but process them asynchronously. This is a good idea :) */ private boolean asyncEventHandling = true; + /** + * The chainListener allows a listener to receive manager events after they + * have been processed by the AsteriskServer. If the AsteriskServer is + * handling messages using the asyncEventHandling then these messages will + * also be async. You would use the chainListener if you are processing raw + * events and using the AJ live ChannelManager. If you don't use the chain + * listener then you can't be certain that a channel name passed in a raw + * event will match the channel name held by the Channel Manager. By + * chaining events you can be certain that events such as channel Rename + * events have been processed by the live ChannelManager before you receive + * an event and as such the names will always match. + */ + private LockableList chainListeners = new LockableList<>(new ArrayList<>()); + /** * Creates a new instance. */ - public AsteriskServerImpl() - { - connectionPool = new ManagerConnectionPool(1); + public AsteriskServerImpl() { idCounter = new AtomicLong(); - listeners = new ArrayList(); - originateCallbacks = new HashMap(); + listeners = new LockableSet<>(new LinkedHashSet<>()); + originateCallbacks = new LockableMap<>(new HashMap<>()); channelManager = new ChannelManager(this); agentManager = new AgentManager(this); meetMeManager = new MeetMeManager(this, channelManager); @@ -133,107 +145,97 @@ public AsteriskServerImpl() * @param eventConnection the ManagerConnection to use for receiving events * from Asterisk. */ - public AsteriskServerImpl(ManagerConnection eventConnection) - { + public AsteriskServerImpl(ManagerConnection eventConnection) { this(); - setManagerConnection(eventConnection); //todo: !!! Possible bug !!!: call to overridable method over object construction + setManagerConnection(eventConnection); // todo: !!! Possible bug !!!: + // call to overridable method + // over object construction } /** * Determines if queue status is retrieved at startup. If you don't need * queue information and still run Asterisk 1.0.x you can set this to * true to circumvent the startup delay caused by the missing - * QueueStatusComplete event. - *

      + * QueueStatusComplete event.
      * Default is false. * * @param skipQueues true to skip queue initialization, * false to not skip. * @since 0.2 */ - public void setSkipQueues(boolean skipQueues) - { + public void setSkipQueues(boolean skipQueues) { this.skipQueues = skipQueues; } - public void setManagerConnection(ManagerConnection eventConnection) - { - if (this.eventConnection != null) - { + public void setManagerConnection(ManagerConnection eventConnection) { + if (this.eventConnection != null) { throw new IllegalStateException("ManagerConnection already set."); } this.eventConnection = eventConnection; - this.connectionPool.clear(); - this.connectionPool.add(eventConnection); } - public ManagerConnection getManagerConnection() - { + public ManagerConnection getManagerConnection() { return eventConnection; } - public void initialize() throws ManagerCommunicationException - { + public void initialize() throws ManagerCommunicationException { initializeIfNeeded(); } - private synchronized void initializeIfNeeded() throws ManagerCommunicationException - { - if (initialized) - { - return; - } - - if (eventConnection.getState() == ManagerConnectionState.INITIAL - || eventConnection.getState() == ManagerConnectionState.DISCONNECTED) - { - try - { - eventConnection.login(); + private void initializeIfNeeded() throws ManagerCommunicationException { + try (LockCloser closer = this.withLock()) { + if (initialized || initializing) { + return; } - catch (Exception e) - { - throw new ManagerCommunicationException("Unable to login: " + e.getMessage(), e); + if (asyncEventHandling && managerEventListenerProxy == null) { + managerEventListenerProxy = new ManagerEventListenerProxy(this); + eventConnection.addEventListener(managerEventListenerProxy); + } else if (!asyncEventHandling && eventListener == null) { + eventListener = this; + eventConnection.addEventListener(eventListener); } - } - channelManager.initialize(); - agentManager.initialize(); - meetMeManager.initialize(); - if (!skipQueues) - { - queueManager.initialize(); - } + initializing = true; - if (asyncEventHandling && managerEventListenerProxy == null) - { - managerEventListenerProxy = new ManagerEventListenerProxy(this); - eventConnection.addEventListener(managerEventListenerProxy); - } - else if (!asyncEventHandling && eventListener == null) - { - eventListener = this; - eventConnection.addEventListener(eventListener); + if (eventConnection.getState() == ManagerConnectionState.INITIAL + || eventConnection.getState() == ManagerConnectionState.DISCONNECTED) { + try { + eventConnection.login(); + } catch (Exception e) { + throw new ManagerCommunicationException("Unable to login: " + e.getMessage(), e); + } + } + + channelManager.initialize(); + agentManager.initialize(); + meetMeManager.initialize(); + if (!skipQueues) { + queueManager.initialize(); + } + + if (asyncEventHandling && managerEventListenerProxy == null) { + managerEventListenerProxy = new ManagerEventListenerProxy(this); + eventConnection.addEventListener(managerEventListenerProxy); + } else if (!asyncEventHandling && eventListener == null) { + eventListener = this; + eventConnection.addEventListener(eventListener); + } + logger.info("Initializing done"); + initializing = false; + initialized = true; } - logger.info("Initializing done"); - initialized = true; } /* Implementation of the AsteriskServer interface */ - public AsteriskChannel originateToExtension(String channel, String context, - String exten, int priority, long timeout) - throws ManagerCommunicationException, NoSuchChannelException - { + public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) + throws ManagerCommunicationException, NoSuchChannelException { return originateToExtension(channel, context, exten, priority, timeout, null, null); } - public AsteriskChannel originateToExtension(String channel, String context, - String exten, int priority, long timeout, CallerId callerId, - Map variables) - throws ManagerCommunicationException, NoSuchChannelException - { + public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout, + CallerId callerId, Map variables) throws ManagerCommunicationException, NoSuchChannelException { final OriginateAction originateAction; originateAction = new OriginateAction(); @@ -242,8 +244,7 @@ public AsteriskChannel originateToExtension(String channel, String context, originateAction.setExten(exten); originateAction.setPriority(priority); originateAction.setTimeout(timeout); - if (callerId != null) - { + if (callerId != null) { originateAction.setCallerId(callerId.toString()); } originateAction.setVariables(variables); @@ -251,18 +252,13 @@ public AsteriskChannel originateToExtension(String channel, String context, return originate(originateAction); } - public AsteriskChannel originateToApplication(String channel, - String application, String data, long timeout) - throws ManagerCommunicationException, NoSuchChannelException - { + public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout) + throws ManagerCommunicationException, NoSuchChannelException { return originateToApplication(channel, application, data, timeout, null, null); } - public AsteriskChannel originateToApplication(String channel, - String application, String data, long timeout, CallerId callerId, - Map variables) - throws ManagerCommunicationException, NoSuchChannelException - { + public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout, + CallerId callerId, Map variables) throws ManagerCommunicationException, NoSuchChannelException { final OriginateAction originateAction; originateAction = new OriginateAction(); @@ -270,8 +266,7 @@ public AsteriskChannel originateToApplication(String channel, originateAction.setApplication(application); originateAction.setData(data); originateAction.setTimeout(timeout); - if (callerId != null) - { + if (callerId != null) { originateAction.setCallerId(callerId.toString()); } originateAction.setVariables(variables); @@ -279,8 +274,8 @@ public AsteriskChannel originateToApplication(String channel, return originate(originateAction); } - public AsteriskChannel originate(OriginateAction originateAction) throws ManagerCommunicationException, NoSuchChannelException - { + public AsteriskChannel originate(OriginateAction originateAction) + throws ManagerCommunicationException, NoSuchChannelException { final ResponseEvents responseEvents; final Iterator responseEventIterator; String uniqueId; @@ -295,39 +290,31 @@ public AsteriskChannel originate(OriginateAction originateAction) throws Manager responseEvents = sendEventGeneratingAction(originateAction, originateAction.getTimeout() + 2000); responseEventIterator = responseEvents.getEvents().iterator(); - if (responseEventIterator.hasNext()) - { + if (responseEventIterator.hasNext()) { ResponseEvent responseEvent; responseEvent = responseEventIterator.next(); - if (responseEvent instanceof OriginateResponseEvent) - { + if (responseEvent instanceof OriginateResponseEvent) { uniqueId = ((OriginateResponseEvent) responseEvent).getUniqueId(); logger.debug(responseEvent.getClass().getName() + " received with uniqueId " + uniqueId); channel = getChannelById(uniqueId); } } - if (channel == null) - { + if (channel == null) { throw new NoSuchChannelException("Channel '" + originateAction.getChannel() + "' is not available"); } return channel; } - public void originateToExtensionAsync(String channel, String context, - String exten, int priority, long timeout, OriginateCallback cb) - throws ManagerCommunicationException - { + public void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, + OriginateCallback cb) throws ManagerCommunicationException { originateToExtensionAsync(channel, context, exten, priority, timeout, null, null, cb); } - public void originateToExtensionAsync(String channel, String context, - String exten, int priority, long timeout, CallerId callerId, - Map variables, OriginateCallback cb) - throws ManagerCommunicationException - { + public void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, + CallerId callerId, Map variables, OriginateCallback cb) throws ManagerCommunicationException { final OriginateAction originateAction; originateAction = new OriginateAction(); @@ -336,8 +323,7 @@ public void originateToExtensionAsync(String channel, String context, originateAction.setExten(exten); originateAction.setPriority(priority); originateAction.setTimeout(timeout); - if (callerId != null) - { + if (callerId != null) { originateAction.setCallerId(callerId.toString()); } originateAction.setVariables(variables); @@ -345,18 +331,13 @@ public void originateToExtensionAsync(String channel, String context, originateAsync(originateAction, cb); } - public void originateToApplicationAsync(String channel, String application, - String data, long timeout, OriginateCallback cb) - throws ManagerCommunicationException - { + public void originateToApplicationAsync(String channel, String application, String data, long timeout, + OriginateCallback cb) throws ManagerCommunicationException { originateToApplicationAsync(channel, application, data, timeout, null, null, cb); } - public void originateToApplicationAsync(String channel, String application, - String data, long timeout, CallerId callerId, - Map variables, OriginateCallback cb) - throws ManagerCommunicationException - { + public void originateToApplicationAsync(String channel, String application, String data, long timeout, CallerId callerId, + Map variables, OriginateCallback cb) throws ManagerCommunicationException { final OriginateAction originateAction; originateAction = new OriginateAction(); @@ -364,8 +345,7 @@ public void originateToApplicationAsync(String channel, String application, originateAction.setApplication(application); originateAction.setData(data); originateAction.setTimeout(timeout); - if (callerId != null) - { + if (callerId != null) { originateAction.setCallerId(callerId.toString()); } originateAction.setVariables(variables); @@ -373,23 +353,19 @@ public void originateToApplicationAsync(String channel, String application, originateAsync(originateAction, cb); } - public void originateAsync(OriginateAction originateAction, - OriginateCallback cb) throws ManagerCommunicationException - { + public void originateAsync(OriginateAction originateAction, OriginateCallback cb) throws ManagerCommunicationException { final Map variables; final String traceId; traceId = ACTION_ID_PREFIX_ORIGINATE + idCounter.getAndIncrement(); - if (originateAction.getVariables() == null) - { - variables = new HashMap(); - } - else - { - variables = new HashMap(originateAction.getVariables()); + if (originateAction.getVariables() == null) { + variables = new HashMap<>(); + } else { + variables = new HashMap<>(originateAction.getVariables()); } - // prefix variable name by "__" to enable variable inheritence across channels + // prefix variable name by "__" to enable variable inheritence across + // channels variables.put("__" + Constants.VARIABLE_TRACE_ID, traceId); originateAction.setVariables(variables); @@ -397,14 +373,12 @@ public void originateAsync(OriginateAction originateAction, originateAction.setAsync(Boolean.TRUE); originateAction.setActionId(traceId); - if (cb != null) - { + if (cb != null) { final OriginateCallbackData callbackData; callbackData = new OriginateCallbackData(originateAction, DateUtil.getDate(), cb); // register callback - synchronized (originateCallbacks) - { + try (LockCloser closer = originateCallbacks.withLock()) { originateCallbacks.put(traceId, callbackData); } } @@ -413,119 +387,109 @@ public void originateAsync(OriginateAction originateAction, sendActionOnEventConnection(originateAction); } - public Collection getChannels() throws ManagerCommunicationException - { + public Collection getChannels() throws ManagerCommunicationException { initializeIfNeeded(); return channelManager.getChannels(); } - public AsteriskChannel getChannelByName(String name) throws ManagerCommunicationException - { + public AsteriskChannel getChannelByName(String name) throws ManagerCommunicationException { initializeIfNeeded(); return channelManager.getChannelImplByName(name); } - public AsteriskChannel getChannelById(String id) throws ManagerCommunicationException - { + public AsteriskChannel getChannelById(String id) throws ManagerCommunicationException { initializeIfNeeded(); return channelManager.getChannelImplById(id); } - public Collection getMeetMeRooms() throws ManagerCommunicationException - { + public Collection getMeetMeRooms() throws ManagerCommunicationException { initializeIfNeeded(); return meetMeManager.getMeetMeRooms(); } - public MeetMeRoom getMeetMeRoom(String name) throws ManagerCommunicationException - { + public MeetMeRoom getMeetMeRoom(String name) throws ManagerCommunicationException { initializeIfNeeded(); return meetMeManager.getOrCreateRoomImpl(name); } - public Collection getQueues() throws ManagerCommunicationException - { + public Collection getQueues() throws ManagerCommunicationException { initializeIfNeeded(); return queueManager.getQueues(); } - public synchronized String getVersion() throws ManagerCommunicationException - { - final ManagerResponse response; - final String command; + @Override + public AsteriskQueue getQueueByName(String queueName) { + initializeIfNeeded(); + return queueManager.getQueueByName(queueName); + } + @Override + public List getQueuesUpdatedAfter(Date date) { initializeIfNeeded(); - if (version == null) - { - if (eventConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) - { - command = SHOW_VERSION_1_6_COMMAND; - } - else - { - command = SHOW_VERSION_COMMAND; - } + return queueManager.getQueuesUpdatedAfter(date); + } + + public String getVersion() throws ManagerCommunicationException { + try (LockCloser closer = this.withLock()) { + final ManagerResponse response; + final String command; + + initializeIfNeeded(); + if (version == null) { + if (eventConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) { + command = SHOW_VERSION_1_6_COMMAND; + } else { + command = SHOW_VERSION_COMMAND; + } - response = sendAction(new CommandAction(command)); - if (response instanceof CommandResponse) - { - final List result; + response = sendAction(new CommandAction(command)); + if (response instanceof CommandResponse) { + final List result; - result = ((CommandResponse) response).getResult(); - if (result.size() > 0) - { - version = (String) result.get(0); + result = ((CommandResponse) response).getResult(); + if (!result.isEmpty()) { + version = result.get(0); + } + } else { + logger.error("Response to CommandAction(\"" + command + "\") was not a CommandResponse but " + response); } } - else - { - logger.error("Response to CommandAction(\"" + command + "\") was not a CommandResponse but " + response); - } - } - return version; + return version; + } } - public int[] getVersion(String file) throws ManagerCommunicationException - { + public int[] getVersion(String file) throws ManagerCommunicationException { String fileVersion = null; String[] parts; int[] intParts; initializeIfNeeded(); - if (versions == null) - { - Map map; + if (versions == null) { + LockableMap map; ManagerResponse response; - map = new HashMap(); - try - { + map = new LockableMap<>(new HashMap<>()); + try { final String command; - if (eventConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) - { + if (eventConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) { command = SHOW_VERSION_FILES_1_6_COMMAND; - } - else - { + } else { command = SHOW_VERSION_FILES_COMMAND; } response = sendAction(new CommandAction(command)); - if (response instanceof CommandResponse) - { + if (response instanceof CommandResponse) { List result; result = ((CommandResponse) response).getResult(); - for (int i = 2; i < result.size(); i++) - { + for (int i = 2; i < result.size(); i++) { String line; Matcher matcher; line = result.get(i); matcher = SHOW_VERSION_FILES_PATTERN.matcher(line); - if (matcher.find()) - { + if (matcher.find()) { String key = matcher.group(1); String value = matcher.group(2); @@ -535,42 +499,29 @@ public int[] getVersion(String file) throws ManagerCommunicationException fileVersion = map.get(file); versions = map; + } else { + logger.error("Response to CommandAction(\"" + command + "\") was not a CommandResponse but " + response); } - else - { - logger.error("Response to CommandAction(\"" - + command + "\") was not a CommandResponse but " + response); - } - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Unable to send '" + SHOW_VERSION_FILES_COMMAND + "' command.", e); } - } - else - { - synchronized (versions) - { + } else { + try (LockCloser closer = versions.withLock()) { fileVersion = versions.get(file); } } - if (fileVersion == null) - { + if (fileVersion == null) { return null; } parts = fileVersion.split("\\."); intParts = new int[parts.length]; - for (int i = 0; i < parts.length; i++) - { - try - { + for (int i = 0; i < parts.length; i++) { + try { intParts[i] = Integer.parseInt(parts[i]); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { intParts[i] = 0; } } @@ -578,71 +529,59 @@ public int[] getVersion(String file) throws ManagerCommunicationException return intParts; } - public String getGlobalVariable(String variable) throws ManagerCommunicationException - { + public String getGlobalVariable(String variable) throws ManagerCommunicationException { ManagerResponse response; String value; initializeIfNeeded(); response = sendAction(new GetVarAction(variable)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { return null; } value = response.getAttribute("Value"); - if (value == null) - { + if (value == null) { value = response.getAttribute(variable); // for Asterisk 1.0.x } return value; } - public void setGlobalVariable(String variable, String value) throws ManagerCommunicationException - { + public void setGlobalVariable(String variable, String value) throws ManagerCommunicationException { ManagerResponse response; initializeIfNeeded(); response = sendAction(new SetVarAction(variable, value)); - if (response instanceof ManagerError) - { - logger.error("Unable to set global variable '" + variable - + "' to '" + value + "':" + response.getMessage()); + if (response instanceof ManagerError) { + logger.error("Unable to set global variable '" + variable + "' to '" + value + "':" + response.getMessage()); } } - public Collection getVoicemailboxes() throws ManagerCommunicationException - { + public Collection getVoicemailboxes() throws ManagerCommunicationException { final Collection voicemailboxes; ManagerResponse response; final List result; initializeIfNeeded(); - voicemailboxes = new ArrayList(); - if (eventConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) - { + voicemailboxes = new ArrayList<>(); + if (eventConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) { response = sendAction(new CommandAction(SHOW_VOICEMAIL_USERS_1_6_COMMAND)); - } - else - { + } else { response = sendAction(new CommandAction(SHOW_VOICEMAIL_USERS_COMMAND)); } - if (!(response instanceof CommandResponse)) - { - logger.error("Response to CommandAction(\"" + SHOW_VOICEMAIL_USERS_COMMAND + "\") was not a CommandResponse but " + response); + if (!(response instanceof CommandResponse)) { + logger.error("Response to CommandAction(\"" + SHOW_VOICEMAIL_USERS_COMMAND + "\") was not a CommandResponse but " + + response); return voicemailboxes; } result = ((CommandResponse) response).getResult(); - if (result == null || result.size() < 1) - { + if (result == null || result.isEmpty()) { return voicemailboxes; } // remove headline result.remove(0); - for (String line : result) - { + for (String line : result) { final Matcher matcher; final Voicemailbox voicemailbox; final String context; @@ -650,8 +589,7 @@ public Collection getVoicemailboxes() throws ManagerCommunicationE final String user; matcher = SHOW_VOICEMAIL_USERS_PATTERN.matcher(line); - if (!matcher.find()) - { + if (!matcher.find()) { continue; } @@ -664,23 +602,18 @@ public Collection getVoicemailboxes() throws ManagerCommunicationE } // get message count for each mailbox - for (Voicemailbox voicemailbox : voicemailboxes) - { + for (Voicemailbox voicemailbox : voicemailboxes) { final String fullname; - fullname = voicemailbox.getMailbox() + "@" - + voicemailbox.getContext(); + fullname = voicemailbox.getMailbox() + "@" + voicemailbox.getContext(); response = sendAction(new MailboxCountAction(fullname)); - if (response instanceof MailboxCountResponse) - { + if (response instanceof MailboxCountResponse) { MailboxCountResponse mailboxCountResponse; mailboxCountResponse = (MailboxCountResponse) response; voicemailbox.setNewMessages(mailboxCountResponse.getNewMessages()); voicemailbox.setOldMessages(mailboxCountResponse.getOldMessages()); - } - else - { + } else { logger.error("Response to MailboxCountAction was not a MailboxCountResponse but " + response); } } @@ -688,87 +621,72 @@ public Collection getVoicemailboxes() throws ManagerCommunicationE return voicemailboxes; } - public List executeCliCommand(String command) throws ManagerCommunicationException - { + public List executeCliCommand(String command) throws ManagerCommunicationException { final ManagerResponse response; initializeIfNeeded(); response = sendAction(new CommandAction(command)); - if (!(response instanceof CommandResponse)) - { - throw new ManagerCommunicationException("Response to CommandAction(\"" + command - + "\") was not a CommandResponse but " + response, null); + if (!(response instanceof CommandResponse)) { + throw new ManagerCommunicationException( + "Response to CommandAction(\"" + command + "\") was not a CommandResponse but " + response, null); } return ((CommandResponse) response).getResult(); } - public boolean isModuleLoaded(String module) throws ManagerCommunicationException - { + public boolean isModuleLoaded(String module) throws ManagerCommunicationException { return sendAction(new ModuleCheckAction(module)) instanceof ModuleCheckResponse; } - public void loadModule(String module) throws ManagerCommunicationException - { + public void loadModule(String module) throws ManagerCommunicationException { sendModuleLoadAction(module, ModuleLoadAction.LOAD_TYPE_LOAD); } - public void unloadModule(String module) throws ManagerCommunicationException - { + public void unloadModule(String module) throws ManagerCommunicationException { sendModuleLoadAction(module, ModuleLoadAction.LOAD_TYPE_UNLOAD); } - public void reloadModule(String module) throws ManagerCommunicationException - { + public void reloadModule(String module) throws ManagerCommunicationException { sendModuleLoadAction(module, ModuleLoadAction.LOAD_TYPE_RELOAD); } - public void reloadAllModules() throws ManagerCommunicationException - { + public void reloadAllModules() throws ManagerCommunicationException { sendModuleLoadAction(null, ModuleLoadAction.LOAD_TYPE_RELOAD); } - protected void sendModuleLoadAction(String module, String loadType) throws ManagerCommunicationException - { + protected void sendModuleLoadAction(String module, String loadType) throws ManagerCommunicationException { final ManagerResponse response; response = sendAction(new ModuleLoadAction(module, loadType)); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { final ManagerError error = (ManagerError) response; throw new ManagerCommunicationException(error.getMessage(), null); } } - public ConfigFile getConfig(String filename) throws ManagerCommunicationException - { + public ConfigFile getConfig(String filename) throws ManagerCommunicationException { final ManagerResponse response; final GetConfigResponse getConfigResponse; initializeIfNeeded(); response = sendAction(new GetConfigAction(filename)); - if (!(response instanceof GetConfigResponse)) - { - throw new ManagerCommunicationException("Response to GetConfigAction(\"" + filename - + "\") was not a CommandResponse but " + response, null); + if (!(response instanceof GetConfigResponse)) { + throw new ManagerCommunicationException( + "Response to GetConfigAction(\"" + filename + "\") was not a CommandResponse but " + response, null); } getConfigResponse = (GetConfigResponse) response; - final Map> categories = new LinkedHashMap>(); final Map categoryMap = getConfigResponse.getCategories(); - for (Map.Entry categoryEntry : categoryMap.entrySet()) - { + final Map> categories = new LinkedHashMap<>(); + for (Map.Entry categoryEntry : categoryMap.entrySet()) { final List lines; final Map lineMap = getConfigResponse.getLines(categoryEntry.getKey()); - if (lineMap == null) - { - lines = new ArrayList(); - } - else - { - lines = new ArrayList(lineMap.values()); + if (lineMap == null) { + lines = new ArrayList<>(); + } else { + lines = new ArrayList<>(lineMap.values()); } categories.put(categoryEntry.getValue(), lines); @@ -777,115 +695,103 @@ public ConfigFile getConfig(String filename) throws ManagerCommunicationExceptio return new ConfigFileImpl(filename, categories); } - public void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException - { + @Override + public void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException { initializeIfNeeded(); - synchronized (listeners) - { - listeners.add(listener); + try (LockCloser closer = listeners.withLock()) { + if (!listeners.contains(listener)) { + listeners.add(listener); + } } } - public void removeAsteriskServerListener(AsteriskServerListener listener) - { - synchronized (listeners) - { + @Override + public void removeAsteriskServerListener(AsteriskServerListener listener) { + try (LockCloser closer = listeners.withLock()) { listeners.remove(listener); } } - void fireNewAsteriskChannel(AsteriskChannel channel) - { - synchronized (listeners) - { - for (AsteriskServerListener listener : listeners) - { - try - { + @Override + public boolean isAsteriskServerListening(AsteriskServerListener listener) { + return listeners.contains(listener); + } + + public void addChainListener(ManagerEventListener chainListener) { + try (LockCloser closer = this.chainListeners.withLock()) { + if (!this.chainListeners.contains(chainListener)) + this.chainListeners.add(chainListener); + } + + } + + public void removeChainListener(ManagerEventListener chainListener) { + this.chainListeners.remove(chainListener); + } + + void fireNewAsteriskChannel(AsteriskChannel channel) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskServerListener listener : listeners) { + try { listener.onNewAsteriskChannel(channel); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in onNewAsteriskChannel()", e); } } } } - void fireNewMeetMeUser(MeetMeUser user) - { - synchronized (listeners) - { - for (AsteriskServerListener listener : listeners) - { - try - { + void fireNewMeetMeUser(MeetMeUser user) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskServerListener listener : listeners) { + try { listener.onNewMeetMeUser(user); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in onNewMeetMeUser()", e); } } } } - ManagerResponse sendActionOnEventConnection(ManagerAction action) throws ManagerCommunicationException - { - try - { + ManagerResponse sendActionOnEventConnection(ManagerAction action) throws ManagerCommunicationException { + try { return eventConnection.sendAction(action); - } - catch (Exception e) - { + } catch (Exception e) { throw ManagerCommunicationExceptionMapper.mapSendActionException(action.getAction(), e); } } - ManagerResponse sendAction(ManagerAction action) throws ManagerCommunicationException - { + ManagerResponse sendAction(ManagerAction action) throws ManagerCommunicationException { // return connectionPool.sendAction(action); - try - { + try { return eventConnection.sendAction(action); - } - catch (Exception e) - { + } catch (Exception e) { throw ManagerCommunicationExceptionMapper.mapSendActionException(action.getAction(), e); } } - ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) throws ManagerCommunicationException - { + ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) throws ManagerCommunicationException { // return connectionPool.sendEventGeneratingAction(action); - try - { + try { return eventConnection.sendEventGeneratingAction(action); - } - catch (Exception e) - { + } catch (Exception e) { throw ManagerCommunicationExceptionMapper.mapSendActionException(action.getAction(), e); } } - ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, - long timeout) throws ManagerCommunicationException - { + ResponseEvents + + sendEventGeneratingAction(EventGeneratingAction action, long timeout) throws ManagerCommunicationException { // return connectionPool.sendEventGeneratingAction(action, timeout); - try - { + try { return eventConnection.sendEventGeneratingAction(action, timeout); - } - catch (Exception e) - { + } catch (Exception e) { throw ManagerCommunicationExceptionMapper.mapSendActionException(action.getAction(), e); } } - OriginateCallbackData getOriginateCallbackDataByTraceId(String traceId) - { - synchronized (originateCallbacks) - { + OriginateCallbackData getOriginateCallbackDataByTraceId(String traceId) { + try (LockCloser closer = originateCallbacks.withLock()) { return originateCallbacks.get(traceId); } } @@ -893,158 +799,116 @@ OriginateCallbackData getOriginateCallbackDataByTraceId(String traceId) /* Implementation of the ManagerEventListener interface */ /** - * Handles all events received from the Asterisk server. - *

      + * Handles all events received from the Asterisk server.
      * Events are queued until channels and queues are initialized and then * delegated to the dispatchEvent method. */ - public void onManagerEvent(ManagerEvent event) - { + public void onManagerEvent(ManagerEvent event) { // Handle Channel related events - if (event instanceof ConnectEvent) - { + if (event instanceof ConnectEvent) { handleConnectEvent((ConnectEvent) event); - } - else if (event instanceof DisconnectEvent) - { + } else if (event instanceof DisconnectEvent) { handleDisconnectEvent((DisconnectEvent) event); - } - else if (event instanceof NewChannelEvent) - { + } else if (event instanceof NewChannelEvent) { channelManager.handleNewChannelEvent((NewChannelEvent) event); - } - else if (event instanceof NewExtenEvent) - { + } else if (event instanceof NewExtenEvent) { channelManager.handleNewExtenEvent((NewExtenEvent) event); - } - else if (event instanceof NewStateEvent) - { + } else if (event instanceof NewStateEvent) { channelManager.handleNewStateEvent((NewStateEvent) event); - } - else if (event instanceof NewCallerIdEvent) - { + } else if (event instanceof NewCallerIdEvent) { channelManager.handleNewCallerIdEvent((NewCallerIdEvent) event); - } - else if (event instanceof DialEvent) - { + } else if (event instanceof DialEvent) { channelManager.handleDialEvent((DialEvent) event); - } - else if (event instanceof BridgeEvent) - { + } else if (event instanceof BridgeEvent) { channelManager.handleBridgeEvent((BridgeEvent) event); - } - else if (event instanceof RenameEvent) - { + } else if (event instanceof RenameEvent) { channelManager.handleRenameEvent((RenameEvent) event); - } - else if (event instanceof HangupEvent) - { + } else if (event instanceof HangupEvent) { channelManager.handleHangupEvent((HangupEvent) event); - } - else if (event instanceof CdrEvent) - { + } else if (event instanceof CdrEvent) { channelManager.handleCdrEvent((CdrEvent) event); - } - else if (event instanceof VarSetEvent) - { + } else if (event instanceof VarSetEvent) { channelManager.handleVarSetEvent((VarSetEvent) event); - } - else if (event instanceof DtmfEvent) - { + } else if (event instanceof DtmfEvent) { channelManager.handleDtmfEvent((DtmfEvent) event); + } else if (event instanceof MonitorStartEvent) { + channelManager.handleMonitorStartEvent((MonitorStartEvent) event); + } else if (event instanceof MonitorStopEvent) { + channelManager.handleMonitorStopEvent((MonitorStopEvent) event); } // End of channel related events // Handle parking related event - else if (event instanceof ParkedCallEvent) - { + else if (event instanceof ParkedCallEvent) { channelManager.handleParkedCallEvent((ParkedCallEvent) event); - } - else if (event instanceof ParkedCallGiveUpEvent) - { + } else if (event instanceof ParkedCallGiveUpEvent) { channelManager.handleParkedCallGiveUpEvent((ParkedCallGiveUpEvent) event); - } - else if (event instanceof ParkedCallTimeOutEvent) - { + } else if (event instanceof ParkedCallTimeOutEvent) { channelManager.handleParkedCallTimeOutEvent((ParkedCallTimeOutEvent) event); - } - else if (event instanceof UnparkedCallEvent) - { + } else if (event instanceof UnparkedCallEvent) { channelManager.handleUnparkedCallEvent((UnparkedCallEvent) event); } // End of parking related events // Handle queue related event - else if (event instanceof JoinEvent) - { + else if (event instanceof JoinEvent) { queueManager.handleJoinEvent((JoinEvent) event); - } - else if (event instanceof LeaveEvent) - { + } else if (event instanceof LeaveEvent) { queueManager.handleLeaveEvent((LeaveEvent) event); - } - else if (event instanceof QueueMemberStatusEvent) - { + } else if (event instanceof QueueMemberStatusEvent) { queueManager.handleQueueMemberStatusEvent((QueueMemberStatusEvent) event); - } - else if (event instanceof QueueMemberPenaltyEvent) - { + } else if (event instanceof QueueMemberPenaltyEvent) { queueManager.handleQueueMemberPenaltyEvent((QueueMemberPenaltyEvent) event); - } - else if (event instanceof QueueMemberAddedEvent) - { + } else if (event instanceof QueueMemberAddedEvent) { queueManager.handleQueueMemberAddedEvent((QueueMemberAddedEvent) event); - } - else if (event instanceof QueueMemberRemovedEvent) - { + } else if (event instanceof QueueMemberRemovedEvent) { queueManager.handleQueueMemberRemovedEvent((QueueMemberRemovedEvent) event); - } - else if (event instanceof QueueMemberPausedEvent) - { + } else if (event instanceof QueueMemberPausedEvent) { queueManager.handleQueueMemberPausedEvent((QueueMemberPausedEvent) event); + } else if (event instanceof QueueCallerJoinEvent) { + queueManager.handleJoinEvent((QueueCallerJoinEvent) event); + } else if (event instanceof QueueCallerLeaveEvent) { + queueManager.handleLeaveEvent((QueueCallerLeaveEvent) event); } // >>>>>> AJ 94 // Handle meetMeEvents - else if (event instanceof AbstractMeetMeEvent) - { + else if (event instanceof AbstractMeetMeEvent) { meetMeManager.handleMeetMeEvent((AbstractMeetMeEvent) event); - } - else if (event instanceof OriginateResponseEvent) - { + } else if (event instanceof OriginateResponseEvent) { handleOriginateEvent((OriginateResponseEvent) event); } // Handle agents-related events - else if (event instanceof AgentsEvent) - { + else if (event instanceof AgentsEvent) { agentManager.handleAgentsEvent((AgentsEvent) event); - } - else if (event instanceof AgentCalledEvent) - { + } else if (event instanceof AgentCalledEvent) { agentManager.handleAgentCalledEvent((AgentCalledEvent) event); - } - else if (event instanceof AgentConnectEvent) - { + } else if (event instanceof AgentConnectEvent) { agentManager.handleAgentConnectEvent((AgentConnectEvent) event); - } - else if (event instanceof AgentCompleteEvent) - { + } else if (event instanceof AgentCompleteEvent) { agentManager.handleAgentCompleteEvent((AgentCompleteEvent) event); - } - else if (event instanceof AgentCallbackLoginEvent) - { + } else if (event instanceof AgentCallbackLoginEvent) { agentManager.handleAgentCallbackLoginEvent((AgentCallbackLoginEvent) event); - } - else if (event instanceof AgentCallbackLogoffEvent) - { + } else if (event instanceof AgentCallbackLogoffEvent) { agentManager.handleAgentCallbackLogoffEvent((AgentCallbackLogoffEvent) event); - } - else if (event instanceof AgentLoginEvent) - { + } else if (event instanceof AgentLoginEvent) { agentManager.handleAgentLoginEvent((AgentLoginEvent) event); - } - else if (event instanceof AgentLogoffEvent) - { + } else if (event instanceof AgentLogoffEvent) { agentManager.handleAgentLogoffEvent((AgentLogoffEvent) event); } // End of agent-related events + + // dispatch the events to the chainListener if they exist. + fireChainListeners(event); + } + + /** + * dispatch the event to the chainListener if they exist. + * + * @param event + */ + private void fireChainListeners(ManagerEvent event) { + try (LockCloser closer = this.chainListeners.withLock()) { + for (ManagerEventListener listener : this.chainListeners) + listener.onManagerEvent(event); + } } /* @@ -1052,18 +916,20 @@ else if (event instanceof AgentLogoffEvent) * lost. */ - private void handleDisconnectEvent(DisconnectEvent disconnectEvent) - { - // reset version information as it might have changed while Asterisk restarted + private void handleDisconnectEvent(DisconnectEvent disconnectEvent) { + // reset version information as it might have changed while Asterisk + // restarted version = null; versions = null; - // same for channels, agents and queues rooms, they are reinitialized when reconnected + // same for channels, agents and queues rooms, they are reinitialized + // when reconnected channelManager.disconnected(); agentManager.disconnected(); meetMeManager.disconnected(); queueManager.disconnected(); initialized = false; + initializing = false; } /* @@ -1071,81 +937,85 @@ private void handleDisconnectEvent(DisconnectEvent disconnectEvent) * to the asterisk server is restored. */ - private void handleConnectEvent(ConnectEvent connectEvent) - { - try - { + private void handleConnectEvent(ConnectEvent connectEvent) { + try { initialize(); - } - catch (Exception e) - { + + channelManager.initialize(); + agentManager.initialize(); + meetMeManager.initialize(); + if (!skipQueues) { + queueManager.initialize(); + } + + logger.info("Initializing done"); + initialized = true; + initializing = false; + } catch (Exception e) { logger.error("Unable to reinitialize state after reconnection", e); } } - private void handleOriginateEvent(OriginateResponseEvent originateEvent) - { + private void handleOriginateEvent(OriginateResponseEvent originateEvent) { final String traceId; final OriginateCallbackData callbackData; final OriginateCallback cb; final AsteriskChannelImpl channel; - final AsteriskChannelImpl otherChannel; // the other side if local channel + final AsteriskChannelImpl otherChannel; // the other side if local + // channel traceId = originateEvent.getActionId(); - if (traceId == null) - { + if (traceId == null) { return; } - synchronized (originateCallbacks) - { + try (LockCloser closer = originateCallbacks.withLock()) { callbackData = originateCallbacks.get(traceId); - if (callbackData == null) - { + if (callbackData == null) { return; } originateCallbacks.remove(traceId); } cb = callbackData.getCallback(); - if (!AstUtil.isNull(originateEvent.getUniqueId())) - { + if (!AstUtil.isNull(originateEvent.getUniqueId())) { channel = channelManager.getChannelImplById(originateEvent.getUniqueId()); - } - else - { + } else { channel = callbackData.getChannel(); } - try - { - if (channel == null) - { + try { + if (channel == null) { final LiveException cause; - cause = new NoSuchChannelException("Channel '" + callbackData.getOriginateAction().getChannel() + "' is not available"); + cause = new NoSuchChannelException( + "Channel '" + callbackData.getOriginateAction().getChannel() + "' is not available"); cb.onFailure(cause); return; } - if (channel.wasBusy()) - { + if (channel.wasInState(ChannelState.UP)) { + cb.onSuccess(channel); + return; + } + + if (channel.wasBusy()) { cb.onBusy(channel); return; } otherChannel = channelManager.getOtherSideOfLocalChannel(channel); // special treatment of local channels: - // the interesting things happen to the other side so we have a look at that - if (otherChannel != null) - { + // the interesting things happen to the other side so we have a look + // at that + if (otherChannel != null) { final AsteriskChannel dialedChannel; dialedChannel = otherChannel.getDialedChannel(); - // on busy the other channel is in state busy when we receive the originate event - if (otherChannel.wasBusy()) - { + // on busy the other channel is in state busy when we receive + // the originate event + if (otherChannel.wasBusy()) { cb.onBusy(channel); return; } @@ -1157,124 +1027,122 @@ private void handleOriginateEvent(OriginateResponseEvent originateEvent) // this alternative has the drawback that there might by // multiple channels that have been dialed by the local channel // but we only look at the last one. - if (dialedChannel != null && dialedChannel.wasBusy()) - { + if (dialedChannel != null && dialedChannel.wasBusy()) { cb.onBusy(channel); return; } } - - if (channel.wasInState(ChannelState.DOWN)) - { - cb.onNoAnswer(channel); - return; - } - // if nothing else matched we asume success - cb.onSuccess(channel); - } - catch (Throwable t) - { + // if nothing else matched we asume no answer + cb.onNoAnswer(channel); + } catch (Throwable t) { logger.warn("Exception dispatching originate progress", t); } } - public void shutdown() - { - if (eventConnection != null && (eventConnection.getState() == ManagerConnectionState.CONNECTED || eventConnection.getState() == ManagerConnectionState.RECONNECTING)) - { - eventConnection.logoff(); + @Override + public void shutdown() { + if (eventConnection != null && (eventConnection.getState() == ManagerConnectionState.CONNECTED + || eventConnection.getState() == ManagerConnectionState.RECONNECTING)) { + try { + eventConnection.logoff(); + } catch (Exception ignore) { + } } - if (managerEventListenerProxy != null) - { + + if (managerEventListenerProxy != null) { + if (eventConnection != null) { + eventConnection.removeEventListener(managerEventListenerProxy); + } managerEventListenerProxy.shutdown(); } + + if (eventConnection != null && eventListener != null) { + eventConnection.removeEventListener(eventListener); + } + managerEventListenerProxy = null; eventListener = null; - } - public List getPeerEntries() throws ManagerCommunicationException - { + if (initialized) {// incredible, but it happened + handleDisconnectEvent(null); + } // i + + }// shutdown + + public List getPeerEntries() throws ManagerCommunicationException { ResponseEvents responseEvents = sendEventGeneratingAction(new SipPeersAction(), 2000); - List peerEntries = new ArrayList(30); - for (ResponseEvent re : responseEvents.getEvents()) - { - if (re instanceof PeerEntryEvent) - { + List peerEntries = new ArrayList<>(30); + for (ResponseEvent re : responseEvents.getEvents()) { + if (re instanceof PeerEntryEvent) { peerEntries.add((PeerEntryEvent) re); } } return peerEntries; } - public DbGetResponseEvent dbGet(String family, String key) throws ManagerCommunicationException - { + public DbGetResponseEvent dbGet(String family, String key) throws ManagerCommunicationException { ResponseEvents responseEvents = sendEventGeneratingAction(new DbGetAction(family, key), 2000); DbGetResponseEvent dbgre = null; - for (ResponseEvent re : responseEvents.getEvents()) - { + for (ResponseEvent re : responseEvents.getEvents()) { dbgre = (DbGetResponseEvent) re; } return dbgre; } - public void dbDel(String family, String key) throws ManagerCommunicationException - { - // The following only works with BRIStuffed asrterisk: sendAction(new DbDelAction(family,key)); + public void dbDel(String family, String key) throws ManagerCommunicationException { + // The following only works with BRIStuffed asrterisk: sendAction(new + // DbDelAction(family,key)); // Use cli command instead ... sendAction(new CommandAction("database del " + family + " " + key)); } - public void dbPut(String family, String key, String value) throws ManagerCommunicationException - { + public void dbPut(String family, String key, String value) throws ManagerCommunicationException { sendAction(new DbPutAction(family, key, value)); } - public AsteriskChannel getChannelByNameAndActive(String name) throws ManagerCommunicationException - { + public AsteriskChannel getChannelByNameAndActive(String name) throws ManagerCommunicationException { initializeIfNeeded(); return channelManager.getChannelImplByNameAndActive(name); } - public Collection getAgents() throws ManagerCommunicationException - { + public Collection getAgents() throws ManagerCommunicationException { initializeIfNeeded(); return agentManager.getAgents(); } - void fireNewAgent(AsteriskAgentImpl agent) - { - synchronized (listeners) - { - for (AsteriskServerListener listener : listeners) - { - try - { + void fireNewAgent(AsteriskAgentImpl agent) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskServerListener listener : listeners) { + try { listener.onNewAgent(agent); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in onNewAgent()", e); } } } } - void fireNewQueueEntry(AsteriskQueueEntry entry) - { - synchronized (listeners) - { - for (AsteriskServerListener listener : listeners) - { - try - { + void fireNewQueueEntry(AsteriskQueueEntry entry) { + try (LockCloser closer = listeners.withLock()) { + for (AsteriskServerListener listener : listeners) { + try { listener.onNewQueueEntry(entry); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception in onNewQueueEntry()", e); } } } } + + /* OCTAVIO LUNA */ + @Override + public void forceQueuesMonitor(boolean force) { + queueManager.forceQueuesMonitor(force); + } + + @Override + public boolean isQueuesMonitorForced() { + return queueManager.isQueuesMonitorForced(); + } } diff --git a/src/main/java/org/asteriskjava/live/internal/CallDetailRecordImpl.java b/src/main/java/org/asteriskjava/live/internal/CallDetailRecordImpl.java index eabdf59e7..141d0429f 100644 --- a/src/main/java/org/asteriskjava/live/internal/CallDetailRecordImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/CallDetailRecordImpl.java @@ -30,8 +30,7 @@ /** * Default implementation of the CallDetailRecord interface. */ -public class CallDetailRecordImpl implements CallDetailRecord -{ +public class CallDetailRecordImpl implements CallDetailRecord { private static final Map DISPOSITION_MAP; private static final Map AMA_FLAGS_MAP; private final AsteriskChannelImpl channel; @@ -51,24 +50,22 @@ public class CallDetailRecordImpl implements CallDetailRecord private final AmaFlags amaFlags; private final String userField; - static - { - DISPOSITION_MAP = new HashMap(); + static { + DISPOSITION_MAP = new HashMap<>(); DISPOSITION_MAP.put(CdrEvent.DISPOSITION_ANSWERED, Disposition.ANSWERED); DISPOSITION_MAP.put(CdrEvent.DISPOSITION_BUSY, Disposition.BUSY); DISPOSITION_MAP.put(CdrEvent.DISPOSITION_FAILED, Disposition.FAILED); DISPOSITION_MAP.put(CdrEvent.DISPOSITION_NO_ANSWER, Disposition.NO_ANSWER); DISPOSITION_MAP.put(CdrEvent.DISPOSITION_UNKNOWN, Disposition.UNKNOWN); - AMA_FLAGS_MAP = new HashMap(); + AMA_FLAGS_MAP = new HashMap<>(); AMA_FLAGS_MAP.put(CdrEvent.AMA_FLAG_BILLING, AmaFlags.BILLING); AMA_FLAGS_MAP.put(CdrEvent.AMA_FLAG_DOCUMENTATION, AmaFlags.DOCUMENTATION); AMA_FLAGS_MAP.put(CdrEvent.AMA_FLAG_OMIT, AmaFlags.OMIT); AMA_FLAGS_MAP.put(CdrEvent.AMA_FLAG_UNKNOWN, AmaFlags.UNKNOWN); } - CallDetailRecordImpl(AsteriskChannelImpl channel, AsteriskChannelImpl destinationChannel, CdrEvent cdrEvent) - { + CallDetailRecordImpl(AsteriskChannelImpl channel, AsteriskChannelImpl destinationChannel, CdrEvent cdrEvent) { //TODO add timezone to AsteriskServer TimeZone tz = TimeZone.getDefault(); this.channel = channel; @@ -84,97 +81,76 @@ public class CallDetailRecordImpl implements CallDetailRecord endDate = cdrEvent.getEndTimeAsDate(tz); duration = cdrEvent.getDuration(); billableSeconds = cdrEvent.getBillableSeconds(); - if (cdrEvent.getAmaFlags() != null) - { + if (cdrEvent.getAmaFlags() != null) { amaFlags = AMA_FLAGS_MAP.get(cdrEvent.getAmaFlags()); - } - else - { + } else { amaFlags = null; } - if (cdrEvent.getDisposition() != null) - { + if (cdrEvent.getDisposition() != null) { disposition = DISPOSITION_MAP.get(cdrEvent.getDisposition()); - } - else - { + } else { disposition = null; } userField = cdrEvent.getUserField(); } - public AsteriskChannel getChannel() - { + public AsteriskChannel getChannel() { return channel; } - public AsteriskChannel getDestinationChannel() - { + public AsteriskChannel getDestinationChannel() { return destinationChannel; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public AmaFlags getAmaFlags() - { + public AmaFlags getAmaFlags() { return amaFlags; } - public Date getAnswerDate() - { + public Date getAnswerDate() { return answerDate; } - public Integer getBillableSeconds() - { + public Integer getBillableSeconds() { return billableSeconds; } - public String getDestinationContext() - { + public String getDestinationContext() { return destinationContext; } - public String getDestinationExtension() - { + public String getDestinationExtension() { return destinationExtension; } - public Disposition getDisposition() - { + public Disposition getDisposition() { return disposition; } - public Integer getDuration() - { + public Integer getDuration() { return duration; } - public Date getEndDate() - { + public Date getEndDate() { return endDate; } - public String getLastApplication() - { + public String getLastApplication() { return lastApplication; } - public String getLastAppData() - { + public String getLastAppData() { return lastAppData; } - public Date getStartDate() - { + public Date getStartDate() { return startDate; } - public String getUserField() - { + public String getUserField() { return userField; } } diff --git a/src/main/java/org/asteriskjava/live/internal/ChannelManager.java b/src/main/java/org/asteriskjava/live/internal/ChannelManager.java index e3334ccb9..a7bf7e2f3 100644 --- a/src/main/java/org/asteriskjava/live/internal/ChannelManager.java +++ b/src/main/java/org/asteriskjava/live/internal/ChannelManager.java @@ -17,14 +17,20 @@ package org.asteriskjava.live.internal; import org.asteriskjava.live.*; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.ResponseEvents; import org.asteriskjava.manager.action.StatusAction; import org.asteriskjava.manager.event.*; +import org.asteriskjava.util.DaemonThreadFactory; import org.asteriskjava.util.DateUtil; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; /** * Manages channel events on behalf of an AsteriskServer. @@ -32,12 +38,12 @@ * @author srt * @version $Id$ */ -class ChannelManager -{ +class ChannelManager { private final Log logger = LogFactory.getLog(getClass()); /** - * How long we wait before we remove hung up channels from memory (in milliseconds). + * How long we wait before we remove hung up channels from memory (in + * milliseconds). */ private static final long REMOVAL_THRESHOLD = 15 * 60 * 1000L; // 15 minutes private static final long SLEEP_TIME_BEFORE_GET_VAR = 50L; @@ -47,47 +53,55 @@ class ChannelManager /** * A map of all active channel by their unique id. */ - private final Set channels; + final LockableMap channels = new LockableMap<>(new LinkedHashMap<>()); + + ScheduledThreadPoolExecutor traceScheduledExecutorService; /** * Creates a new instance. * * @param server the server this channel manager belongs to. */ - ChannelManager(AsteriskServerImpl server) - { + ChannelManager(AsteriskServerImpl server) { this.server = server; - this.channels = new HashSet(); } - void initialize() throws ManagerCommunicationException - { + void initialize() throws ManagerCommunicationException { initialize(null); } - void initialize(List variables) throws ManagerCommunicationException - { + void initialize(List variables) throws ManagerCommunicationException { ResponseEvents re; - disconnected(); + shutdown(); + + traceScheduledExecutorService = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory());// Executors.newSingleThreadScheduledExecutor + StatusAction sa = new StatusAction(); sa.setVariables(variables); re = server.sendEventGeneratingAction(sa); - for (ManagerEvent event : re.getEvents()) - { - if (event instanceof StatusEvent) - { + for (ManagerEvent event : re.getEvents()) { + if (event instanceof StatusEvent) { handleStatusEvent((StatusEvent) event); } } + logger.debug("ChannelManager has been initialised"); + } - void disconnected() - { - synchronized (channels) - { + void disconnected() { + shutdown(); + logger.debug("ChannelManager has been disconnected from Asterisk."); + } + + private void shutdown() { + if (traceScheduledExecutorService != null) { + traceScheduledExecutorService.shutdown(); + } + try (LockCloser closer = channels.withLock()) { channels.clear(); } + } /** @@ -95,17 +109,13 @@ void disconnected() * * @return a collection of all active AsteriskChannels. */ - Collection getChannels() - { + Collection getChannels() { Collection copy; - synchronized (channels) - { - copy = new ArrayList(channels.size() + 2); - for (AsteriskChannel channel : channels) - { - if (channel.getState() != ChannelState.HUNGUP) - { + try (LockCloser closer = channels.withLock()) { + copy = new ArrayList<>(channels.size() + 2); + for (AsteriskChannel channel : channels.values()) { + if (channel.getState() != ChannelState.HUNGUP) { copy.add(channel); } } @@ -113,33 +123,27 @@ Collection getChannels() return copy; } - private void addChannel(AsteriskChannelImpl channel) - { - synchronized (channels) - { - channels.add(channel); + private void addChannel(AsteriskChannelImpl channel) { + try (LockCloser closer = channels.withLock()) { + channels.put(channel.getId(), channel); } } /** - * Removes channels that have been hung more than {@link #REMOVAL_THRESHOLD} milliseconds. + * Removes channels that have been hung more than {@link #REMOVAL_THRESHOLD} + * milliseconds. */ - private void removeOldChannels() - { + private void removeOldChannels() { Iterator i; - synchronized (channels) - { - i = channels.iterator(); - while (i.hasNext()) - { + try (LockCloser closer = channels.withLock()) { + i = channels.values().iterator(); + while (i.hasNext()) { final AsteriskChannel channel = i.next(); final Date dateOfRemoval = channel.getDateOfRemoval(); - if (channel.getState() == ChannelState.HUNGUP && dateOfRemoval != null) - { + if (channel.getState() == ChannelState.HUNGUP && dateOfRemoval != null) { final long diff = DateUtil.getDate().getTime() - dateOfRemoval.getTime(); - if (diff >= REMOVAL_THRESHOLD) - { + if (diff >= REMOVAL_THRESHOLD) { i.remove(); } } @@ -147,125 +151,113 @@ private void removeOldChannels() } } - private AsteriskChannelImpl addNewChannel(String uniqueId, String name, - Date dateOfCreation, String callerIdNumber, String callerIdName, - ChannelState state, String account) - { - final AsteriskChannelImpl channel; - final String traceId; - - channel = new AsteriskChannelImpl(server, name, uniqueId, dateOfCreation); + private AsteriskChannelImpl addNewChannel(String uniqueId, final String name, Date dateOfCreation, String callerIdNumber, + String callerIdName, ChannelState state, String account) { + final AsteriskChannelImpl channel = new AsteriskChannelImpl(server, name, uniqueId, dateOfCreation); channel.setCallerId(new CallerId(callerIdName, callerIdNumber)); channel.setAccount(account); channel.stateChanged(dateOfCreation, state); logger.info("Adding channel " + channel.getName() + "(" + channel.getId() + ")"); - if (SLEEP_TIME_BEFORE_GET_VAR > 0) - { - try - { - Thread.sleep(SLEEP_TIME_BEFORE_GET_VAR); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); + if (SLEEP_TIME_BEFORE_GET_VAR > 0) { + long start = System.currentTimeMillis(); + long end = start + SLEEP_TIME_BEFORE_GET_VAR; + while (System.currentTimeMillis() < end) { + try { + channel.getVariable(Constants.VARIABLE_TRACE_ID); + } catch (NoSuchChannelException | ManagerCommunicationException e) { + try { + Thread.sleep(1L); + } catch (InterruptedException intEx) { + Thread.currentThread().interrupt(); + } + } } } - traceId = getTraceId(channel); + String traceId = getTraceId(channel); channel.setTraceId(traceId); addChannel(channel); - if (traceId != null && (!name.toLowerCase(Locale.ENGLISH).startsWith("local/") || (name.endsWith(",1") || name.endsWith(";1")))) - { - final OriginateCallbackData callbackData; - callbackData = server.getOriginateCallbackDataByTraceId(traceId); - if (callbackData != null && callbackData.getChannel() == null) - { - callbackData.setChannel(channel); - try - { - callbackData.getCallback().onDialing(channel); - } - catch (Throwable t) - { - logger.warn("Exception dispatching originate progress.", t); - } - } - } + // todo getChannelImplById -> LinkedHashMap, callbacks order + traceScheduledExecutorService.schedule(new Runnable() { + @Override + public void run() { + final String traceId = getTraceId(channel); + channel.setTraceId(traceId); + + if (traceId != null && (!name.toLowerCase(Locale.ENGLISH).startsWith("local/") || name.endsWith(",1") + || name.endsWith(";1"))) { + final OriginateCallbackData callbackData = server.getOriginateCallbackDataByTraceId(traceId); + + if (callbackData != null && callbackData.getChannel() == null) { + callbackData.setChannel(channel); + try { + callbackData.getCallback().onDialing(channel); + } catch (Throwable t) { + logger.warn("Exception dispatching originate progress. " + channel, t); + } // t + } // i + } // i + } + }, SLEEP_TIME_BEFORE_GET_VAR, TimeUnit.MILLISECONDS); + server.fireNewAsteriskChannel(channel); return channel; - } + }// addNewChannel - void handleStatusEvent(StatusEvent event) - { + void handleStatusEvent(StatusEvent event) { AsteriskChannelImpl channel; final Extension extension; boolean isNew = false; Map variables = event.getVariables(); channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { + if (channel == null) { Date dateOfCreation; - if (event.getSeconds() != null) - { + if (event.getSeconds() != null) { dateOfCreation = new Date(DateUtil.getDate().getTime() - (event.getSeconds() * 1000L)); - } - else - { + } else { dateOfCreation = DateUtil.getDate(); } channel = new AsteriskChannelImpl(server, event.getChannel(), event.getUniqueId(), dateOfCreation); isNew = true; - if (variables != null) - { - for (String variable : variables.keySet()) - { - channel.updateVariable(variable, variables.get(variable)); + if (variables != null) { + for (Entry variable : variables.entrySet()) { + channel.updateVariable(variable.getKey(), variable.getValue()); } } } - if (event.getContext() == null && event.getExtension() == null - && event.getPriority() == null) - { + if (event.getContext() == null && event.getExtension() == null && event.getPriority() == null) { extension = null; - } - else - { + } else { extension = new Extension(event.getContext(), event.getExtension(), event.getPriority()); } - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum())); channel.setAccount(event.getAccountCode()); - if (event.getChannelState() != null) - { + if (event.getChannelState() != null) { channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState())); } channel.extensionVisited(event.getDateReceived(), extension); - if (event.getBridgedChannel() != null) - { + if (event.getBridgedChannel() != null) { final AsteriskChannelImpl linkedChannel = getChannelImplByName(event.getBridgedChannel()); - if (linkedChannel != null) - { + if (linkedChannel != null) { // the date used here is not correct! channel.channelLinked(event.getDateReceived(), linkedChannel); - synchronized (linkedChannel) - { + try (LockCloser closer2 = linkedChannel.withLock()) { linkedChannel.channelLinked(event.getDateReceived(), channel); } } } } - if (isNew) - { + if (isNew) { logger.info("Adding new channel " + channel.getName()); addChannel(channel); server.fireNewAsteriskChannel(channel); @@ -273,34 +265,29 @@ void handleStatusEvent(StatusEvent event) } /** - * Returns a channel from the ChannelManager's cache with the given name - * If multiple channels are found, returns the most recently CREATED one. - * If two channels with the very same date exist, avoid HUNGUP ones. + * Returns a channel from the ChannelManager's cache with the given name If + * multiple channels are found, returns the most recently CREATED one. If + * two channels with the very same date exist, avoid HUNGUP ones. * * @param name the name of the requested channel. - * @return the (most recent) channel if found, in any state, or null if none found. + * @return the (most recent) channel if found, in any state, or null if none + * found. */ - AsteriskChannelImpl getChannelImplByName(String name) - { + AsteriskChannelImpl getChannelImplByName(String name) { Date dateOfCreation = null; AsteriskChannelImpl channel = null; - if (name == null) - { + if (name == null) { return null; } - synchronized (channels) - { - for (AsteriskChannelImpl tmp : channels) - { - if (tmp.getName() != null && tmp.getName().equals(name)) - { - // return the most recent channel or when dates are similar, the active one - if (dateOfCreation == null || - tmp.getDateOfCreation().after(dateOfCreation) || - (tmp.getDateOfCreation().equals(dateOfCreation) && tmp.getState() != ChannelState.HUNGUP)) - { + try (LockCloser closer = channels.withLock()) { + for (AsteriskChannelImpl tmp : channels.values()) { + if (name.equals(tmp.getName())) { + // return the most recent channel or when dates are similar, + // the active one + if (dateOfCreation == null || tmp.getDateOfCreation().after(dateOfCreation) + || (tmp.getDateOfCreation().equals(dateOfCreation) && tmp.getState() != ChannelState.HUNGUP)) { channel = tmp; dateOfCreation = channel.getDateOfCreation(); } @@ -311,33 +298,30 @@ AsteriskChannelImpl getChannelImplByName(String name) } /** - * Returns a NON-HUNGUP channel from the ChannelManager's cache with the given name. + * Returns a NON-HUNGUP channel from the ChannelManager's cache with the + * given name. * * @param name the name of the requested channel. * @return the NON-HUNGUP channel if found, or null if none is found. */ - AsteriskChannelImpl getChannelImplByNameAndActive(String name) - { + AsteriskChannelImpl getChannelImplByNameAndActive(String name) { - // In non bristuffed AST 1.2, we don't have uniqueid header to match the channel + // In non bristuffed AST 1.2, we don't have uniqueid header to match the + // channel // So we must use the channel name - // Channel name is unique at any give moment in the * server + // Channel name is unique at any give moment in the * server // But asterisk-java keeps Hungup channels for a while. // We don't want to retrieve hungup channels. AsteriskChannelImpl channel = null; - if (name == null) - { + if (name == null) { return null; } - synchronized (channels) - { - for (AsteriskChannelImpl tmp : channels) - { - if (tmp.getName() != null && tmp.getName().equals(name) && tmp.getState() != ChannelState.HUNGUP) - { + try (LockCloser closer = channels.withLock()) { + for (AsteriskChannelImpl tmp : channels.values()) { + if (name.equals(tmp.getName()) && tmp.getState() != ChannelState.HUNGUP) { channel = tmp; } } @@ -345,93 +329,65 @@ AsteriskChannelImpl getChannelImplByNameAndActive(String name) return channel; } - AsteriskChannelImpl getChannelImplById(String id) - { - if (id == null) - { + AsteriskChannelImpl getChannelImplById(String uniqueId) { + if (uniqueId == null) { return null; } - synchronized (channels) - { - for (AsteriskChannelImpl channel : channels) - { - if (id.equals(channel.getId())) - { - return channel; - } - } + try (LockCloser closer = channels.withLock()) { + return channels.get(uniqueId); } - return null; - } + }// getChannelImplById /** - * Returns the other side of a local channel. - *

      - * Local channels consist of two sides, like - * "Local/1234@from-local-60b5,1" and "Local/1234@from-local-60b5,2" (for Asterisk 1.4) or - * "Local/1234@from-local-60b5;1" and "Local/1234@from-local-60b5;2" (for Asterisk 1.6) - * this method returns the other side. + * Returns the other side of a local channel.
      + * Local channels consist of two sides, like "Local/1234@from-local-60b5,1" + * and "Local/1234@from-local-60b5,2" (for Asterisk 1.4) or + * "Local/1234@from-local-60b5;1" and "Local/1234@from-local-60b5;2" (for + * Asterisk 1.6) this method returns the other side. * * @param localChannel one side - * @return the other side, or null if not available or if the given channel - * is not a local channel. + * @return the other side, or null if not available or if the + * given channel is not a local channel. */ - AsteriskChannelImpl getOtherSideOfLocalChannel(AsteriskChannel localChannel) - { + AsteriskChannelImpl getOtherSideOfLocalChannel(AsteriskChannel localChannel) { final String name; final char num; - if (localChannel == null) - { + if (localChannel == null) { return null; } name = localChannel.getName(); - if (name == null || !name.startsWith("Local/") || (name.charAt(name.length() - 2) != ',' && name.charAt(name.length() - 2) != ';')) - { + if (name == null || !name.startsWith("Local/") + || (name.charAt(name.length() - 2) != ',' && name.charAt(name.length() - 2) != ';')) { return null; } num = name.charAt(name.length() - 1); - if (num == '1') - { + if (num == '1') { return getChannelImplByName(name.substring(0, name.length() - 1) + "2"); - } - else if (num == '2') - { + } else if (num == '2') { return getChannelImplByName(name.substring(0, name.length() - 1) + "1"); - } - else - { + } else { return null; } } - void handleNewChannelEvent(NewChannelEvent event) - { + void handleNewChannelEvent(NewChannelEvent event) { final AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { - if (event.getChannel() == null) - { + if (channel == null) { + if (event.getChannel() == null) { logger.info("Ignored NewChannelEvent with empty channel name (uniqueId=" + event.getUniqueId() + ")"); + } else { + addNewChannel(event.getUniqueId(), event.getChannel(), event.getDateReceived(), event.getCallerIdNum(), + event.getCallerIdName(), ChannelState.valueOf(event.getChannelState()), event.getAccountCode()); } - else - { - addNewChannel( - event.getUniqueId(), event.getChannel(), event.getDateReceived(), - event.getCallerIdNum(), event.getCallerIdName(), - ChannelState.valueOf(event.getChannelState()), event.getAccountCode()); - } - } - else - { + } else { // channel had already been created probably by a NewCallerIdEvent - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { channel.nameChanged(event.getDateReceived(), event.getChannel()); channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum())); channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState())); @@ -439,74 +395,80 @@ void handleNewChannelEvent(NewChannelEvent event) } } - void handleNewExtenEvent(NewExtenEvent event) - { + void handleNewExtenEvent(NewExtenEvent event) { AsteriskChannelImpl channel; final Extension extension; channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { - logger.error("Ignored NewExtenEvent for unknown channel " + event.getChannel()); + if (channel == null) { + logger.warn("handleNewExtenEvent: Ignored NewExtenEvent for unknown channel " + event.getChannel()); return; } - extension = new Extension( - event.getContext(), event.getExtension(), event.getPriority(), - event.getApplication(), event.getAppData()); + extension = new Extension(event.getContext(), event.getExtension(), event.getPriority(), event.getApplication(), + event.getAppData()); - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { channel.extensionVisited(event.getDateReceived(), extension); } } - void handleNewStateEvent(NewStateEvent event) - { + private void idChanged(AsteriskChannelImpl channel, AbstractChannelEvent event) { + if (channel != null) { + final String oldId = channel.getId(); + final String newId = event.getUniqueId(); + + if (oldId != null && oldId.equals(newId)) { + return; + } + + logger.info("Changing unique_id for '" + channel.getName() + "' from " + oldId + " to " + newId + " < " + event); + try (LockCloser closer = channels.withLock()) { + channels.remove(oldId); + channels.put(newId, channel); + channel.idChanged(event.getDateReceived(), newId); + } + } + }// idChanged + + void handleNewStateEvent(NewStateEvent event) { AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { - // NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/) + if (channel == null) { + // NewStateEvent can occur for an existing channel that now has a + // different unique id (originate with Local/) channel = getChannelImplByNameAndActive(event.getChannel()); - if (channel != null) - { - logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId()); - channel.idChanged(event.getDateReceived(), event.getUniqueId()); - } + idChanged(channel, event); - if (channel == null) - { - logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId()); + if (channel == null) { + logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + + event.getUniqueId()); // NewStateEvent can occur instead of a NewChannelEvent - channel = addNewChannel( - event.getUniqueId(), event.getChannel(), event.getDateReceived(), - event.getCallerIdNum(), event.getCallerIdName(), - ChannelState.valueOf(event.getChannelState()), null /* account code not available */); + channel = addNewChannel(event.getUniqueId(), event.getChannel(), event.getDateReceived(), + event.getCallerIdNum(), event.getCallerIdName(), ChannelState.valueOf(event.getChannelState()), + null /* account code not available */); } } - // NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a - // NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents. - if (event.getCallerIdNum() != null || event.getCallerIdName() != null) - { + // NewStateEvent can provide a new CallerIdNum or CallerIdName not + // previously received through a + // NewCallerIdEvent. This happens at least on outgoing legs from the + // queue application to agents. + if (event.getCallerIdNum() != null || event.getCallerIdName() != null) { String cidnum = ""; String cidname = ""; CallerId currentCallerId = channel.getCallerId(); - if (currentCallerId != null) - { + if (currentCallerId != null) { cidnum = currentCallerId.getNumber(); cidname = currentCallerId.getName(); } - if (event.getCallerIdNum() != null) - { + if (event.getCallerIdNum() != null) { cidnum = event.getCallerIdNum(); } - if (event.getCallerIdName() != null) - { + if (event.getCallerIdName() != null) { cidname = event.getCallerIdName(); } @@ -514,76 +476,62 @@ void handleNewStateEvent(NewStateEvent event) logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString()); channel.setCallerId(newCallerId); - // Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been + // Also, NewStateEvent can return a new channel name for the same + // channel uniqueid, indicating the channel has been // renamed but no related RenameEvent has been received. // This happens with mISDN channels (see AJ-153) - if (event.getChannel() != null && !event.getChannel().equals(channel.getName())) - { - logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'"); - synchronized (channel) - { + if (event.getChannel() != null && !event.getChannel().equals(channel.getName())) { + logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + + event.getChannel() + "'"); + try (LockCloser closer = channel.withLock()) { channel.nameChanged(event.getDateReceived(), event.getChannel()); } } } - if (event.getChannelState() != null) - { - synchronized (channel) - { + if (event.getChannelState() != null) { + try (LockCloser closer = channel.withLock()) { channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState())); } } } - void handleNewCallerIdEvent(NewCallerIdEvent event) - { + void handleNewCallerIdEvent(NewCallerIdEvent event) { AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { - // NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/) + if (channel == null) { + // NewCallerIdEvent can occur for an existing channel that now has a + // different unique id (originate with Local/) channel = getChannelImplByNameAndActive(event.getChannel()); - if (channel != null) - { - logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId()); - channel.idChanged(event.getDateReceived(), event.getUniqueId()); - } + idChanged(channel, event); - if (channel == null) - { + if (channel == null) { // NewCallerIdEvent can occur before NewChannelEvent - channel = addNewChannel( - event.getUniqueId(), event.getChannel(), event.getDateReceived(), - event.getCallerIdNum(), event.getCallerIdName(), - ChannelState.DOWN, null /* account code not available */); + channel = addNewChannel(event.getUniqueId(), event.getChannel(), event.getDateReceived(), + event.getCallerIdNum(), event.getCallerIdName(), ChannelState.DOWN, + null /* account code not available */); } } - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum())); } } - void handleHangupEvent(HangupEvent event) - { + void handleHangupEvent(HangupEvent event) { HangupCause cause = null; AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { - logger.error("Ignored HangupEvent for unknown channel " + event.getChannel()); + if (channel == null) { + logger.warn("handleHangupEvent: Ignored HangupEvent for unknown channel " + event.getChannel()); return; } - if (event.getCause() != null) - { + if (event.getCause() != null) { cause = HangupCause.getByCode(event.getCause()); } - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { channel.hungup(event.getDateReceived(), cause, event.getCauseTxt()); } @@ -591,294 +539,297 @@ void handleHangupEvent(HangupEvent event) removeOldChannels(); } - void handleDialEvent(DialEvent event) - { + void handleDialEvent(DialEvent event) { final AsteriskChannelImpl sourceChannel = getChannelImplById(event.getUniqueId()); final AsteriskChannelImpl destinationChannel = getChannelImplById(event.getDestUniqueId()); - if (sourceChannel == null) - { - logger.error("Ignored DialEvent for unknown source channel " + event.getChannel() + " with unique id " + event.getUniqueId()); + if (sourceChannel == null) { + logger.warn("handleDialEvent: Ignored DialEvent for unknown source channel " + event.getChannel() + + " with unique id " + event.getUniqueId()); return; } - if (destinationChannel == null) - { - logger.error("Ignored DialEvent for unknown destination channel " + event.getDestination() + " with unique id " + event.getDestUniqueId()); + if (destinationChannel == null) { + if (DialEvent.SUBEVENT_END.equalsIgnoreCase(event.getSubEvent())) { + sourceChannel.updateVariable(AsteriskChannel.VAR_AJ_DIAL_STATUS, event.getDialStatus()); + logger.info("handleDialEvent: Ignored DialEvent for unknown dst channel " + event.getDestination() + + " with unique_id " + event.getDestUniqueId()); + } else { + logger.warn("handleDialEvent: Ignored DialEvent for unknown dst channel " + event.getDestination() + + " with unique_id " + event.getDestUniqueId()); + } return; - } + } // i logger.info(sourceChannel.getName() + " dialed " + destinationChannel.getName()); getTraceId(sourceChannel); getTraceId(destinationChannel); - synchronized (sourceChannel) - { + try (LockCloser closer = sourceChannel.withLock()) { sourceChannel.channelDialed(event.getDateReceived(), destinationChannel); } - synchronized (destinationChannel) - { + try (LockCloser closer = destinationChannel.withLock()) { destinationChannel.channelDialing(event.getDateReceived(), sourceChannel); } } - void handleBridgeEvent(BridgeEvent event) - { + void handleBridgeEvent(BridgeEvent event) { final AsteriskChannelImpl channel1 = getChannelImplById(event.getUniqueId1()); final AsteriskChannelImpl channel2 = getChannelImplById(event.getUniqueId2()); - if (channel1 == null) - { - logger.error("Ignored BridgeEvent for unknown channel " + event.getChannel1()); + if (channel1 == null) { + logger.warn("handleBridgeEvent: Ignored BridgeEvent for unknown channel " + event.getChannel1()); return; } - if (channel2 == null) - { - logger.error("Ignored BridgeEvent for unknown channel " + event.getChannel2()); + if (channel2 == null) { + logger.warn("handleBridgeEvent: Ignored BridgeEvent for unknown channel " + event.getChannel2()); return; } - if (event.isLink()) - { + if (event.isLink()) { logger.info("Linking channels " + channel1.getName() + " and " + channel2.getName()); - synchronized (channel1) - { + try (LockCloser closer = channel1.withLock()) { channel1.channelLinked(event.getDateReceived(), channel2); } - synchronized (channel2) - { + try (LockCloser closer = channel2.withLock()) { channel2.channelLinked(event.getDateReceived(), channel1); } } - if (event.isUnlink()) - { + if (event.isUnlink()) { logger.info("Unlinking channels " + channel1.getName() + " and " + channel2.getName()); - synchronized (channel1) - { + try (LockCloser closer = channel1.withLock()) { channel1.channelUnlinked(event.getDateReceived()); } - synchronized (channel2) - { + try (LockCloser closer = channel2.withLock()) { channel2.channelUnlinked(event.getDateReceived()); } } } - void handleRenameEvent(RenameEvent event) - { + void handleRenameEvent(RenameEvent event) { AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { - logger.error("Ignored RenameEvent for unknown channel with uniqueId " + event.getUniqueId()); + if (channel == null) { + logger.warn("handleRenameEvent: Ignored RenameEvent for unknown channel with uniqueId " + event.getUniqueId()); return; } - logger.info("Renaming channel '" + channel.getName() + "' to '" + event.getNewname() + "', uniqueId is " + event.getUniqueId()); - synchronized (channel) - { + logger.info("Renaming channel '" + channel.getName() + "' to '" + event.getNewname() + "', uniqueId is " + + event.getUniqueId()); + try (LockCloser closer = channel.withLock()) { channel.nameChanged(event.getDateReceived(), event.getNewname()); } } - void handleCdrEvent(CdrEvent event) - { + void handleCdrEvent(CdrEvent event) { final AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); final AsteriskChannelImpl destinationChannel = getChannelImplByName(event.getDestinationChannel()); final CallDetailRecordImpl cdr; - if (channel == null) - { + if (channel == null) { logger.info("Ignored CdrEvent for unknown channel with uniqueId " + event.getUniqueId()); return; } cdr = new CallDetailRecordImpl(channel, destinationChannel, event); - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { channel.callDetailRecordReceived(event.getDateReceived(), cdr); } } - private String getTraceId(AsteriskChannel channel) - { + private String getTraceId(AsteriskChannel channel) { String traceId; - try - { + try { traceId = channel.getVariable(Constants.VARIABLE_TRACE_ID); - } - catch (Exception e) - { + } catch (Exception e) { traceId = null; } - //logger.info("TraceId for channel " + channel.getName() + " is " + traceId); + // logger.info("TraceId for channel " + channel.getName() + " is " + + // traceId); return traceId; } - void handleParkedCallEvent(ParkedCallEvent event) - { - // Only bristuffed versions: AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getChannel()); + void handleParkedCallEvent(ParkedCallEvent event) { + logger.info("Trace - ChannelManager.java - handleParkedCallEvent: " + event); + // Only bristuffed versions: AsteriskChannelImpl channel = + // getChannelImplById(event.getUniqueId()); + AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getParkeeChannel()); - if (channel == null) - { - logger.info("Ignored ParkedCallEvent for unknown channel " - + event.getChannel()); + if (channel == null) { + logger.info("Ignored ParkedCallEvent for unknown channel " + event.getParkeeChannel()); return; } - synchronized (channel) - { - // todo The context should be "parkedcalls" or whatever has been configured in features.conf - // unfortunately we don't get the context in the ParkedCallEvent so for now we'll set it to null. - Extension ext = new Extension(null, event.getExten(), 1); - channel.setParkedAt(ext); + try (LockCloser closer = channel.withLock()) { + Extension ext = new Extension(null, + (event.getParkingSpace() != null) ? event.getParkingSpace() : event.getExten(), 1); + String parkinglot = event.getParkingLot(); + channel.setParkedAt(ext, parkinglot); logger.info("Channel " + channel.getName() + " is parked at " + channel.getParkedAt().getExtension()); } } - void handleParkedCallGiveUpEvent(ParkedCallGiveUpEvent event) - { - // Only bristuffed versions: AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getChannel()); + void handleParkedCallGiveUpEvent(ParkedCallGiveUpEvent event) { + // Only bristuffed versions: AsteriskChannelImpl channel = + // getChannelImplById(event.getUniqueId()); + AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getParkeeChannel()); - if (channel == null) - { - logger.info("Ignored ParkedCallGiveUpEvent for unknown channel " - + event.getChannel()); + if (channel == null) { + logger.info("Ignored ParkedCallGiveUpEvent for unknown channel " + event.getParkeeChannel()); return; } Extension wasParkedAt = channel.getParkedAt(); - if (wasParkedAt == null) - { + if (wasParkedAt == null) { logger.info("Ignored ParkedCallGiveUpEvent as the channel was not parked"); return; } - synchronized (channel) - { - channel.setParkedAt(null); + try (LockCloser closer = channel.withLock()) { + channel.setParkedAt(null, null); } logger.info("Channel " + channel.getName() + " is unparked (GiveUp) from " + wasParkedAt.getExtension()); } - void handleParkedCallTimeOutEvent(ParkedCallTimeOutEvent event) - { - // Only bristuffed versions: AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getChannel()); + void handleParkedCallTimeOutEvent(ParkedCallTimeOutEvent event) { + // Only bristuffed versions: AsteriskChannelImpl channel = + // getChannelImplById(event.getUniqueId()); + final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getParkeeChannel()); - if (channel == null) - { - logger.info("Ignored ParkedCallTimeOutEvent for unknown channel " + event.getChannel()); + if (channel == null) { + logger.info("Ignored ParkedCallTimeOutEvent for unknown channel " + event.getParkeeChannel()); return; } Extension wasParkedAt = channel.getParkedAt(); - if (wasParkedAt == null) - { + if (wasParkedAt == null) { logger.info("Ignored ParkedCallTimeOutEvent as the channel was not parked"); return; } - synchronized (channel) - { - channel.setParkedAt(null); + try (LockCloser closer = channel.withLock()) { + channel.setParkedAt(null, null); } logger.info("Channel " + channel.getName() + " is unparked (Timeout) from " + wasParkedAt.getExtension()); } - void handleUnparkedCallEvent(UnparkedCallEvent event) - { - // Only bristuffed versions: AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getChannel()); + void handleUnparkedCallEvent(UnparkedCallEvent event) { + // Only bristuffed versions: AsteriskChannelImpl channel = + // getChannelImplById(event.getUniqueId()); + final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getParkeeChannel()); - if (channel == null) - { - logger.info("Ignored UnparkedCallEvent for unknown channel " + event.getChannel()); + if (channel == null) { + logger.info("Ignored UnparkedCallEvent for unknown channel " + event.getParkeeChannel()); return; } Extension wasParkedAt = channel.getParkedAt(); - if (wasParkedAt == null) - { + if (wasParkedAt == null) { logger.info("Ignored UnparkedCallEvent as the channel was not parked"); return; } - synchronized (channel) - { - channel.setParkedAt(null); + try (LockCloser closer = channel.withLock()) { + channel.setParkedAt(null, null); } logger.info("Channel " + channel.getName() + " is unparked (moved away) from " + wasParkedAt.getExtension()); } - void handleVarSetEvent(VarSetEvent event) - { - if (event.getUniqueId() == null) - { + void handleVarSetEvent(VarSetEvent event) { + if (event.getUniqueId() == null) { return; } final AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { + if (channel == null) { logger.info("Ignored VarSetEvent for unknown channel with uniqueId " + event.getUniqueId()); return; } - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { channel.updateVariable(event.getVariable(), event.getValue()); } } - void handleDtmfEvent(DtmfEvent event) - { + void handleDtmfEvent(DtmfEvent event) { // we are only intrested in END events - if (event.isBegin()) - { + if (event.isBegin()) { return; } - if (event.getUniqueId() == null) - { + if (event.getUniqueId() == null) { return; } final AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { + if (channel == null) { logger.info("Ignored DtmfEvent for unknown channel with uniqueId " + event.getUniqueId()); return; } final Character dtmfDigit; - if (event.getDigit() == null || event.getDigit().length() < 1) - { + if (event.getDigit() == null || event.getDigit().length() < 1) { dtmfDigit = null; - } - else - { + } else { dtmfDigit = event.getDigit().charAt(0); } - synchronized (channel) - { - if (event.isReceived()) - { + try (LockCloser closer = channel.withLock()) { + if (event.isReceived()) { channel.dtmfReceived(dtmfDigit); } - if (event.isSent()) - { + if (event.isSent()) { channel.dtmfSent(dtmfDigit); } } } + + void handleMonitorStartEvent(MonitorStartEvent event) { + final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getChannel()); + + if (channel == null) { + logger.info("Ignored MonitorStartEvent for unknown channel " + event.getChannel()); + return; + } + + boolean isMonitored = channel.isMonitored(); + + if (isMonitored) { + logger.info("Ignored MonitorStartEvent as the channel was already monitored"); + return; + } + + try (LockCloser closer = channel.withLock()) { + channel.setMonitored(true); + } + logger.info("Channel " + channel.getName() + " is monitored"); + } + + void handleMonitorStopEvent(MonitorStopEvent event) { + final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getChannel()); + + if (channel == null) { + logger.info("Ignored MonitorStopEvent for unknown channel " + event.getChannel()); + return; + } + + boolean isMonitored = channel.isMonitored(); + + if (!isMonitored) { + logger.info("Ignored MonitorStopEvent as the channel was not monitored"); + return; + } + + try (LockCloser closer = channel.withLock()) { + channel.setMonitored(false); + } + logger.info("Channel " + channel.getName() + " is not monitored"); + } + } diff --git a/src/main/java/org/asteriskjava/live/internal/ConfigFileImpl.java b/src/main/java/org/asteriskjava/live/internal/ConfigFileImpl.java index e3e40ccd2..105bc6f22 100644 --- a/src/main/java/org/asteriskjava/live/internal/ConfigFileImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/ConfigFileImpl.java @@ -18,8 +18,8 @@ import org.asteriskjava.config.ConfigFile; -import java.util.Map; import java.util.List; +import java.util.Map; /** * ConfigFile implementation based on the config actions of the Manager API. @@ -28,34 +28,28 @@ * @version $Id$ * @since 1.0.0 */ -public class ConfigFileImpl implements ConfigFile -{ +public class ConfigFileImpl implements ConfigFile { private final String filename; private final Map> categories; - public ConfigFileImpl(String filename, Map> categories) - { + public ConfigFileImpl(String filename, Map> categories) { this.filename = filename; this.categories = categories; } - public String getFilename() - { + public String getFilename() { return filename; } - public Map> getCategories() - { + public Map> getCategories() { return categories; } - public String getValue(String category, String key) - { + public String getValue(String category, String key) { throw new UnsupportedOperationException("Not yet inmplemented"); } - public List getValues(String category, String key) - { + public List getValues(String category, String key) { throw new UnsupportedOperationException("Not yet inmplemented"); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/live/internal/Constants.java b/src/main/java/org/asteriskjava/live/internal/Constants.java index 230c98a64..2ffa3bd45 100644 --- a/src/main/java/org/asteriskjava/live/internal/Constants.java +++ b/src/main/java/org/asteriskjava/live/internal/Constants.java @@ -2,15 +2,13 @@ /** * Defines constants used internally in the live package in multiple classes. - * + * * @author srt * @version $Id$ */ -class Constants -{ +class Constants { // hide constructor - private Constants() - { + private Constants() { } diff --git a/src/main/java/org/asteriskjava/live/internal/ManagerCommunicationExceptionMapper.java b/src/main/java/org/asteriskjava/live/internal/ManagerCommunicationExceptionMapper.java index 61d0cdc49..2ed537a59 100644 --- a/src/main/java/org/asteriskjava/live/internal/ManagerCommunicationExceptionMapper.java +++ b/src/main/java/org/asteriskjava/live/internal/ManagerCommunicationExceptionMapper.java @@ -23,15 +23,13 @@ * Maps exceptions received from * {@link org.asteriskjava.manager.ManagerConnection} to the corresponding * {@link org.asteriskjava.live.ManagerCommunicationException}. - * + * * @author srt * @version $Id$ */ -class ManagerCommunicationExceptionMapper -{ +class ManagerCommunicationExceptionMapper { // hide constructor - private ManagerCommunicationExceptionMapper() - { + private ManagerCommunicationExceptionMapper() { } @@ -40,23 +38,17 @@ private ManagerCommunicationExceptionMapper() * {@link org.asteriskjava.manager.ManagerConnection} when sending a * {@link org.asteriskjava.manager.action.ManagerAction} to the corresponding * {@link org.asteriskjava.live.ManagerCommunicationException}. - * + * * @param actionName name of the action that has been tried to send - * @param exception exception received + * @param exception exception received * @return the corresponding ManagerCommunicationException */ - static ManagerCommunicationException mapSendActionException(String actionName, Exception exception) - { - if (exception instanceof IllegalStateException) - { + static ManagerCommunicationException mapSendActionException(String actionName, Exception exception) { + if (exception instanceof IllegalStateException) { return new ManagerCommunicationException("Not connected to Asterisk Server", exception); - } - else if (exception instanceof EventTimeoutException) - { + } else if (exception instanceof EventTimeoutException) { return new ManagerCommunicationException("Timeout waiting for events from " + actionName + "Action", exception); - } - else - { + } else { return new ManagerCommunicationException("Unable to send " + actionName + "Action", exception); } } diff --git a/src/main/java/org/asteriskjava/live/internal/ManagerConnectionPool.java b/src/main/java/org/asteriskjava/live/internal/ManagerConnectionPool.java deleted file mode 100644 index 21612197e..000000000 --- a/src/main/java/org/asteriskjava/live/internal/ManagerConnectionPool.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 2005-2006 Stefan Reuter - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.asteriskjava.live.internal; - -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; - -import org.asteriskjava.live.ManagerCommunicationException; -import org.asteriskjava.manager.ManagerConnection; -import org.asteriskjava.manager.ResponseEvents; -import org.asteriskjava.manager.action.EventGeneratingAction; -import org.asteriskjava.manager.action.ManagerAction; -import org.asteriskjava.manager.response.ManagerResponse; -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; - -class ManagerConnectionPool -{ - private final Log logger = LogFactory.getLog(getClass()); - private final BlockingQueue connections; - - ManagerConnectionPool(int size) - { - this.connections = new ArrayBlockingQueue(size); - } - - void clear() - { - connections.clear(); - } - - void add(ManagerConnection connection) - { - put(connection); - } - - ManagerResponse sendAction(ManagerAction action) throws ManagerCommunicationException - { - ManagerConnection connection; - ManagerResponse response; - - connection = get(); - try - { - response = connection.sendAction(action); - } - catch (Exception e) - { - throw ManagerCommunicationExceptionMapper.mapSendActionException(action.getAction(), e); - } - finally - { - put(connection); - } - - return response; - } - - ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) throws ManagerCommunicationException - { - return sendEventGeneratingAction(action, -1); - } - - ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) - throws ManagerCommunicationException - { - ManagerConnection connection; - ResponseEvents responseEvents; - - connection = get(); - try - { - if (timeout > 0) - { - responseEvents = connection.sendEventGeneratingAction(action, timeout); - } - else - { - responseEvents = connection.sendEventGeneratingAction(action); - } - } - catch (Exception e) - { - throw ManagerCommunicationExceptionMapper.mapSendActionException(action.getAction(), e); - } - finally - { - put(connection); - } - - return responseEvents; - } - - /** - * Retrieves a connection from the pool. - * - * @return the retrieved connection, or null if interrupted - * while waiting for a connection to become available. - */ - private ManagerConnection get() - { - try - { - return connections.take(); - } - catch (InterruptedException e) - { - logger.error("Interrupted while waiting for ManagerConnection to become available", e); - Thread.currentThread().interrupt(); - return null; - } - } - - private void put(ManagerConnection connection) - { - try - { - connections.put(connection); - } - catch (InterruptedException e) - { - Thread.currentThread().interrupt(); - throw new RuntimeException("Interrupted while trying to add connection to pool"); - } - } -} diff --git a/src/main/java/org/asteriskjava/live/internal/MeetMeManager.java b/src/main/java/org/asteriskjava/live/internal/MeetMeManager.java index 872f7e98a..42f2230cc 100644 --- a/src/main/java/org/asteriskjava/live/internal/MeetMeManager.java +++ b/src/main/java/org/asteriskjava/live/internal/MeetMeManager.java @@ -18,6 +18,8 @@ import org.asteriskjava.live.ManagerCommunicationException; import org.asteriskjava.live.MeetMeRoom; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.action.CommandAction; import org.asteriskjava.manager.event.AbstractMeetMeEvent; import org.asteriskjava.manager.event.MeetMeLeaveEvent; @@ -30,7 +32,10 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -39,8 +44,7 @@ * * @author srt */ -class MeetMeManager -{ +class MeetMeManager { private static final String MEETME_LIST_COMMAND = "meetme list"; private static final Pattern MEETME_LIST_PATTERN = Pattern.compile("^User #: ([0-9]+).*Channel: (\\S+).*$"); @@ -51,47 +55,35 @@ class MeetMeManager /** * Maps room number to MeetMe room. */ - private final Map rooms; + private final LockableMap rooms; - MeetMeManager(AsteriskServerImpl server, ChannelManager channelManager) - { + MeetMeManager(AsteriskServerImpl server, ChannelManager channelManager) { this.server = server; this.channelManager = channelManager; - this.rooms = new HashMap(); + this.rooms = new LockableMap<>(new HashMap<>()); } - void initialize() - { - synchronized (rooms) - { - for (MeetMeRoomImpl room : rooms.values()) - { + void initialize() { + try (LockCloser closer = rooms.withLock()) { + for (MeetMeRoomImpl room : rooms.values()) { populateRoom(room); } } } - void disconnected() - { + void disconnected() { /* - synchronized (rooms) - { - rooms.clear(); - } - */ + * try (LockCloser closer = Locker2.lock(rooms) { rooms.clear(); } + */ } - Collection getMeetMeRooms() - { + Collection getMeetMeRooms() { final Collection result; - result = new ArrayList(); - synchronized (rooms) - { - for (MeetMeRoom room : rooms.values()) - { - if (!room.isEmpty()) - { + result = new ArrayList<>(); + try (LockCloser closer = rooms.withLock()) { + for (MeetMeRoom room : rooms.values()) { + if (!room.isEmpty()) { result.add(room); } } @@ -99,8 +91,7 @@ Collection getMeetMeRooms() return result; } - void handleMeetMeEvent(AbstractMeetMeEvent event) - { + void handleMeetMeEvent(AbstractMeetMeEvent event) { String roomNumber; Integer userNumber; AsteriskChannelImpl channel; @@ -108,108 +99,92 @@ void handleMeetMeEvent(AbstractMeetMeEvent event) MeetMeUserImpl user; roomNumber = event.getMeetMe(); - if (roomNumber == null) - { + if (roomNumber == null) { logger.warn("RoomNumber (meetMe property) is null. Ignoring " + event.getClass().getName()); return; } - userNumber = event.getUserNum(); - if (userNumber == null) - { + userNumber = event.getUser(); + if (userNumber == null) { logger.warn("UserNumber (userNum property) is null. Ignoring " + event.getClass().getName()); return; } user = getOrCreateUserImpl(event); - if (user == null) - { + if (user == null) { return; } channel = user.getChannel(); room = user.getRoom(); - if (event instanceof MeetMeLeaveEvent) - { + if (event instanceof MeetMeLeaveEvent) { logger.info("Removing channel " + channel.getName() + " from room " + roomNumber); - if (room != user.getRoom()) - { - if (user.getRoom() != null) - { + if (room != user.getRoom()) { + if (user.getRoom() != null) { logger.error("Channel " + channel.getName() + " should be removed from room " + roomNumber + " but is user of room " + user.getRoom().getRoomNumber()); user.getRoom().removeUser(user); - } - else - { + } else { logger.error("Channel " + channel.getName() + " should be removed from room " + roomNumber + " but is user of no room"); } } - // Mmmm should remove from the room before firing PropertyChangeEvents ? + // Mmmm should remove from the room before firing + // PropertyChangeEvents ? user.left(event.getDateReceived()); room.removeUser(user); channel.setMeetMeUserImpl(null); - } - else if (event instanceof MeetMeTalkingEvent) - { + } else if (event instanceof MeetMeTalkingEvent) { Boolean status; status = ((MeetMeTalkingEvent) event).getStatus(); - if (status != null) - { + if (status != null) { user.setTalking(status); - } - else - { + } else { user.setTalking(true); } - } - else if (event instanceof MeetMeMuteEvent) - { + } else if (event instanceof MeetMeMuteEvent) { Boolean status; status = ((MeetMeMuteEvent) event).getStatus(); - if (status != null) - { + if (status != null) { user.setMuted(status); } } } - private void populateRoom(MeetMeRoomImpl room) - { + private void populateRoom(MeetMeRoomImpl room) { final CommandAction meetMeListAction; final ManagerResponse response; final List lines; - final Collection userNumbers = new ArrayList(); // list of user numbers in the room + final Collection userNumbers = new ArrayList<>(); // list + // of + // user + // numbers + // in + // the + // room meetMeListAction = new CommandAction(MEETME_LIST_COMMAND + " " + room.getRoomNumber()); - try - { + try { response = server.sendAction(meetMeListAction); - } - catch (ManagerCommunicationException e) - { + } catch (ManagerCommunicationException e) { logger.error("Unable to send \"" + MEETME_LIST_COMMAND + "\" command", e); return; } - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { logger.error("Unable to send \"" + MEETME_LIST_COMMAND + "\" command: " + response.getMessage()); return; } - if (!(response instanceof CommandResponse)) - { + if (!(response instanceof CommandResponse)) { logger.error("Response to \"" + MEETME_LIST_COMMAND + "\" command is not a CommandResponse but " + response.getClass()); return; } lines = ((CommandResponse) response).getResult(); - for (String line : lines) - { + for (String line : lines) { final Matcher matcher; final Integer userNumber; final AsteriskChannelImpl channel; @@ -219,42 +194,41 @@ private void populateRoom(MeetMeRoomImpl room) MeetMeUserImpl roomUser; matcher = MEETME_LIST_PATTERN.matcher(line); - if (!matcher.matches()) - { + if (!matcher.matches()) { continue; } userNumber = Integer.valueOf(matcher.group(1)); channel = channelManager.getChannelImplByName(matcher.group(2)); + if (channel == null) // User has left the room already in the + // meanwhile + { + continue; + } userNumbers.add(userNumber); - if (line.contains("(Admin Muted)") || line.contains("(Muted)")) - { + if (line.contains("(Admin Muted)") || line.contains("(Muted)")) { muted = true; } - if (line.contains("(talking)")) - { + if (line.contains("(talking)")) { talking = true; } channelUser = channel.getMeetMeUser(); - if (channelUser != null && channelUser.getRoom() != room) - { + if (channelUser != null && channelUser.getRoom() != room) { channelUser.left(DateUtil.getDate()); channelUser = null; } roomUser = room.getUser(userNumber); - if (roomUser != null && roomUser.getChannel() != channel) - { + if (roomUser != null && roomUser.getChannel() != channel) { room.removeUser(roomUser); roomUser = null; } - if (channelUser == null && roomUser == null) - { + if (channelUser == null && roomUser == null) { final MeetMeUserImpl user; // using the current date as dateJoined is not correct but we // don't have anything that is better @@ -264,21 +238,14 @@ private void populateRoom(MeetMeRoomImpl room) room.addUser(user); channel.setMeetMeUserImpl(user); server.fireNewMeetMeUser(user); - } - else if (channelUser != null && roomUser == null) - { + } else if (channelUser != null && roomUser == null) { channelUser.setMuted(muted); room.addUser(channelUser); - } - else if (channelUser == null) - { + } else if (channelUser == null && roomUser != null) { roomUser.setMuted(muted); channel.setMeetMeUserImpl(roomUser); - } - else - { - if (channelUser != roomUser) - { + } else { + if (channelUser != roomUser) { logger.error("Inconsistent state: channelUser != roomUser, channelUser=" + channelUser + ", roomUser=" + roomUser); } @@ -286,25 +253,21 @@ else if (channelUser == null) } Collection users = room.getUserImpls(); - Collection usersToRemove = new ArrayList(); - for (MeetMeUserImpl user : users) - { - if (!userNumbers.contains(user.getUserNumber())) - { + Collection usersToRemove = new ArrayList<>(); + for (MeetMeUserImpl user : users) { + if (!userNumbers.contains(user.getUserNumber())) { // remove user as he is no longer in the room usersToRemove.add(user); } } - for (MeetMeUserImpl user : usersToRemove) - { + for (MeetMeUserImpl user : usersToRemove) { user.left(DateUtil.getDate()); room.removeUser(user); user.getChannel().setMeetMeUserImpl(null); } } - private MeetMeUserImpl getOrCreateUserImpl(AbstractMeetMeEvent event) - { + private MeetMeUserImpl getOrCreateUserImpl(AbstractMeetMeEvent event) { final String roomNumber; final MeetMeRoomImpl room; final String uniqueId; @@ -313,41 +276,36 @@ private MeetMeUserImpl getOrCreateUserImpl(AbstractMeetMeEvent event) roomNumber = event.getMeetMe(); room = getOrCreateRoomImpl(roomNumber); - user = room.getUser(event.getUserNum()); - if (user != null) - { + user = room.getUser(event.getUser()); + if (user != null) { return user; } // ok create a new one uniqueId = event.getUniqueId(); - if (uniqueId == null) - { + if (uniqueId == null) { logger.warn("UniqueId is null. Ignoring MeetMeEvent"); return null; } channel = channelManager.getChannelImplById(uniqueId); - if (channel == null) - { + if (channel == null) { logger.warn("No channel with unique id " + uniqueId + ". Ignoring MeetMeEvent"); return null; } user = channel.getMeetMeUser(); - if (user != null) - { + if (user != null) { logger.error("Got MeetMeEvent for channel " + channel.getName() + " that is already user of a room"); user.left(event.getDateReceived()); - if (user.getRoom() != null) - { + if (user.getRoom() != null) { user.getRoom().removeUser(user); } channel.setMeetMeUserImpl(null); } - logger.info("Adding channel " + channel.getName() + " as user " + event.getUserNum() + " to room " + roomNumber); - user = new MeetMeUserImpl(server, room, event.getUserNum(), channel, event.getDateReceived()); + logger.info("Adding channel " + channel.getName() + " as user " + event.getUser() + " to room " + roomNumber); + user = new MeetMeUserImpl(server, room, event.getUser(), channel, event.getDateReceived()); room.addUser(user); channel.setMeetMeUserImpl(user); server.fireNewMeetMeUser(user); @@ -362,16 +320,13 @@ private MeetMeUserImpl getOrCreateUserImpl(AbstractMeetMeEvent event) * @param roomNumber number of the room to get or create. * @return the room with the given number. */ - MeetMeRoomImpl getOrCreateRoomImpl(String roomNumber) - { + MeetMeRoomImpl getOrCreateRoomImpl(String roomNumber) { MeetMeRoomImpl room; boolean created = false; - synchronized (rooms) - { + try (LockCloser closer = rooms.withLock()) { room = rooms.get(roomNumber); - if (room == null) - { + if (room == null) { room = new MeetMeRoomImpl(server, roomNumber); populateRoom(room); rooms.put(roomNumber, room); @@ -379,8 +334,7 @@ MeetMeRoomImpl getOrCreateRoomImpl(String roomNumber) } } - if (created) - { + if (created) { logger.debug("Created MeetMeRoom " + roomNumber); } diff --git a/src/main/java/org/asteriskjava/live/internal/MeetMeRoomImpl.java b/src/main/java/org/asteriskjava/live/internal/MeetMeRoomImpl.java index adb2ea91d..59da00312 100644 --- a/src/main/java/org/asteriskjava/live/internal/MeetMeRoomImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/MeetMeRoomImpl.java @@ -16,107 +16,90 @@ */ package org.asteriskjava.live.internal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - import org.asteriskjava.live.ManagerCommunicationException; import org.asteriskjava.live.MeetMeRoom; import org.asteriskjava.live.MeetMeUser; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.action.CommandAction; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; + /** * Default implementation of the MeetMeRoom interface. */ -class MeetMeRoomImpl extends AbstractLiveObject implements MeetMeRoom -{ +class MeetMeRoomImpl extends AbstractLiveObject implements MeetMeRoom { private static final String COMMAND_PREFIX = "meetme"; private static final String LOCK_COMMAND = "lock"; private static final String UNLOCK_COMMAND = "unlock"; private final String roomNumber; - + /** * Maps userNumber to user. */ - private final Map users; + private final LockableMap users; - MeetMeRoomImpl(AsteriskServerImpl server, String roomNumber) - { + MeetMeRoomImpl(AsteriskServerImpl server, String roomNumber) { super(server); this.roomNumber = roomNumber; - this.users = new HashMap(20); + this.users = new LockableMap<>(new HashMap<>(20)); } - public String getRoomNumber() - { + public String getRoomNumber() { return roomNumber; } - public Collection getUsers() - { - synchronized (users) - { + public Collection getUsers() { + try (LockCloser closer = users.withLock()) { return new ArrayList(users.values()); } } - public boolean isEmpty() - { - synchronized (users) - { + public boolean isEmpty() { + try (LockCloser closer = users.withLock()) { return users.isEmpty(); } } - Collection getUserImpls() - { - synchronized (users) - { - return new ArrayList(users.values()); + Collection getUserImpls() { + try (LockCloser closer = users.withLock()) { + return new ArrayList<>(users.values()); } } - - void addUser(MeetMeUserImpl user) - { - synchronized (users) - { + + void addUser(MeetMeUserImpl user) { + try (LockCloser closer = users.withLock()) { users.put(user.getUserNumber(), user); } } - MeetMeUserImpl getUser(Integer userNumber) - { - synchronized (users) - { + MeetMeUserImpl getUser(Integer userNumber) { + try (LockCloser closer = users.withLock()) { return users.get(userNumber); } } - void removeUser(MeetMeUserImpl user) - { - synchronized (users) - { + void removeUser(MeetMeUserImpl user) { + try (LockCloser closer = users.withLock()) { users.remove(user.getUserNumber()); } } // action methods - public void lock() throws ManagerCommunicationException - { + public void lock() throws ManagerCommunicationException { sendMeetMeCommand(LOCK_COMMAND); } - public void unlock() throws ManagerCommunicationException - { + public void unlock() throws ManagerCommunicationException { sendMeetMeCommand(UNLOCK_COMMAND); } - private void sendMeetMeCommand(String command) throws ManagerCommunicationException - { - final StringBuffer sb = new StringBuffer(); + private void sendMeetMeCommand(String command) throws ManagerCommunicationException { + final StringBuilder sb = new StringBuilder(); sb.append(COMMAND_PREFIX); sb.append(" "); sb.append(command); @@ -127,15 +110,13 @@ private void sendMeetMeCommand(String command) throws ManagerCommunicationExcept } @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; int systemHashcode; - sb = new StringBuffer("MeetMeRoom["); + sb = new StringBuilder("MeetMeRoom["); - synchronized (this) - { + try (LockCloser closer = this.withLock()) { sb.append("roomNumber='").append(getRoomNumber()).append("',"); systemHashcode = System.identityHashCode(this); } diff --git a/src/main/java/org/asteriskjava/live/internal/MeetMeUserImpl.java b/src/main/java/org/asteriskjava/live/internal/MeetMeUserImpl.java index f2a25e14d..099afe65a 100644 --- a/src/main/java/org/asteriskjava/live/internal/MeetMeUserImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/MeetMeUserImpl.java @@ -16,15 +16,15 @@ */ package org.asteriskjava.live.internal; -import java.util.Date; - import org.asteriskjava.live.ManagerCommunicationException; import org.asteriskjava.live.MeetMeUser; import org.asteriskjava.live.MeetMeUserState; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.action.CommandAction; -class MeetMeUserImpl extends AbstractLiveObject implements MeetMeUser -{ +import java.util.Date; + +class MeetMeUserImpl extends AbstractLiveObject implements MeetMeUser { private static final String COMMAND_PREFIX = "meetme"; private static final String MUTE_COMMAND = "mute"; private static final String UNMUTE_COMMAND = "unmute"; @@ -40,9 +40,8 @@ class MeetMeUserImpl extends AbstractLiveObject implements MeetMeUser private boolean talking; private boolean muted; - MeetMeUserImpl(AsteriskServerImpl server, MeetMeRoomImpl room, Integer userNumber, - AsteriskChannelImpl channel, Date dateJoined) - { + MeetMeUserImpl(AsteriskServerImpl server, MeetMeRoomImpl room, Integer userNumber, AsteriskChannelImpl channel, + Date dateJoined) { super(server); this.room = room; this.userNumber = userNumber; @@ -51,41 +50,35 @@ class MeetMeUserImpl extends AbstractLiveObject implements MeetMeUser this.state = MeetMeUserState.JOINED; } - public MeetMeRoomImpl getRoom() - { + public MeetMeRoomImpl getRoom() { return room; } - public Integer getUserNumber() - { + public Integer getUserNumber() { return userNumber; } - public AsteriskChannelImpl getChannel() - { + public AsteriskChannelImpl getChannel() { return channel; } - public Date getDateJoined() - { + public Date getDateJoined() { return dateJoined; } - public Date getDateLeft() - { + public Date getDateLeft() { return dateLeft; } /** - * Sets the status to {@link MeetMeUserState#LEFT} and dateLeft to the given date. - * + * Sets the status to {@link MeetMeUserState#LEFT} and dateLeft to the given + * date. + * * @param dateLeft the date this user left the room. */ - void left(Date dateLeft) - { + void left(Date dateLeft) { MeetMeUserState oldState; - synchronized (this) - { + try (LockCloser closer = this.withLock()) { oldState = this.state; this.dateLeft = dateLeft; this.state = MeetMeUserState.LEFT; @@ -93,30 +86,25 @@ void left(Date dateLeft) firePropertyChange(PROPERTY_STATE, oldState, state); } - public MeetMeUserState getState() - { + public MeetMeUserState getState() { return state; } - public boolean isTalking() - { + public boolean isTalking() { return talking; } - void setTalking(boolean talking) - { + void setTalking(boolean talking) { boolean oldTalking = this.talking; this.talking = talking; firePropertyChange(PROPERTY_TALKING, oldTalking, talking); } - public boolean isMuted() - { + public boolean isMuted() { return muted; } - void setMuted(boolean muted) - { + void setMuted(boolean muted) { boolean oldMuted = this.muted; this.muted = muted; firePropertyChange(PROPERTY_MUTED, oldMuted, muted); @@ -124,24 +112,20 @@ void setMuted(boolean muted) // action methods - public void kick() throws ManagerCommunicationException - { + public void kick() throws ManagerCommunicationException { sendMeetMeUserCommand(KICK_COMMAND); } - public void mute() throws ManagerCommunicationException - { + public void mute() throws ManagerCommunicationException { sendMeetMeUserCommand(MUTE_COMMAND); } - public void unmute() throws ManagerCommunicationException - { + public void unmute() throws ManagerCommunicationException { sendMeetMeUserCommand(UNMUTE_COMMAND); } - private void sendMeetMeUserCommand(String command) throws ManagerCommunicationException - { - StringBuffer sb = new StringBuffer(); + private void sendMeetMeUserCommand(String command) throws ManagerCommunicationException { + StringBuilder sb = new StringBuilder(); sb.append(COMMAND_PREFIX); sb.append(" "); sb.append(command); @@ -152,17 +136,15 @@ private void sendMeetMeUserCommand(String command) throws ManagerCommunicationEx server.sendAction(new CommandAction(sb.toString())); } - + @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; int systemHashcode; - sb = new StringBuffer("MeetMeUser["); + sb = new StringBuilder("MeetMeUser["); - synchronized (this) - { + try (LockCloser closer = this.withLock()) { sb.append("dateJoined='").append(getDateJoined()).append("',"); sb.append("dateLeft='").append(getDateLeft()).append("',"); sb.append("talking=").append(isTalking()).append(","); @@ -171,8 +153,7 @@ public String toString() systemHashcode = System.identityHashCode(this); } sb.append("channel=AsteriskChannel["); - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { sb.append("id='").append(channel.getId()).append("',"); sb.append("name='").append(channel.getName()).append("'],"); } diff --git a/src/main/java/org/asteriskjava/live/internal/OriginateCallbackData.java b/src/main/java/org/asteriskjava/live/internal/OriginateCallbackData.java index bc7236190..246690b1c 100644 --- a/src/main/java/org/asteriskjava/live/internal/OriginateCallbackData.java +++ b/src/main/java/org/asteriskjava/live/internal/OriginateCallbackData.java @@ -1,21 +1,20 @@ /** - * + * */ package org.asteriskjava.live.internal; -import java.util.Date; - import org.asteriskjava.live.OriginateCallback; import org.asteriskjava.manager.action.OriginateAction; +import java.util.Date; + /** * Wrapper class for OriginateCallbacks. - * + * * @author srt * @version $Id$ */ -class OriginateCallbackData -{ +class OriginateCallbackData { private OriginateAction originateAction; private Date dateSent; private OriginateCallback callback; @@ -23,42 +22,36 @@ class OriginateCallbackData /** * Creates a new instance. - * + * * @param originateAction the action that has been sent to the Asterisk - * server - * @param dateSent date when the the action has been sent - * @param callback callback to notify about result + * server + * @param dateSent date when the the action has been sent + * @param callback callback to notify about result */ - OriginateCallbackData(OriginateAction originateAction, Date dateSent, OriginateCallback callback) - { + OriginateCallbackData(OriginateAction originateAction, Date dateSent, OriginateCallback callback) { super(); this.originateAction = originateAction; this.dateSent = dateSent; this.callback = callback; } - OriginateAction getOriginateAction() - { + OriginateAction getOriginateAction() { return originateAction; } - Date getDateSent() - { + Date getDateSent() { return dateSent; } - OriginateCallback getCallback() - { + OriginateCallback getCallback() { return callback; } - AsteriskChannelImpl getChannel() - { + AsteriskChannelImpl getChannel() { return channel; } - void setChannel(AsteriskChannelImpl channel) - { + void setChannel(AsteriskChannelImpl channel) { this.channel = channel; } } diff --git a/src/main/java/org/asteriskjava/live/internal/QueueManager.java b/src/main/java/org/asteriskjava/live/internal/QueueManager.java index 62e5ad5bf..2194fd78c 100644 --- a/src/main/java/org/asteriskjava/live/internal/QueueManager.java +++ b/src/main/java/org/asteriskjava/live/internal/QueueManager.java @@ -16,14 +16,11 @@ */ package org.asteriskjava.live.internal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - import org.asteriskjava.live.AsteriskQueue; import org.asteriskjava.live.ManagerCommunicationException; import org.asteriskjava.live.QueueMemberState; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.EventTimeoutException; import org.asteriskjava.manager.ResponseEvents; import org.asteriskjava.manager.action.QueueStatusAction; @@ -31,81 +28,109 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +import java.util.*; +import java.util.Map.Entry; + /** * Manages queue events on behalf of an AsteriskServer. * * @author srt * @version $Id$ */ -class QueueManager -{ +class QueueManager { private final Log logger = LogFactory.getLog(this.getClass()); private final AsteriskServerImpl server; private final ChannelManager channelManager; + private boolean queuesMonitorForced = false; + private long queueMonitorLastTimeReloaded; + private long queuesMonitorLeaseTime = 1000; /** - * A map of ACD queues by there name. + * A map of ACD queues by there name. 101119 OLB: Modified to act as a LRU + * Cache to optimize updates */ - private final Map queues; + private final LockableMap queuesLRU = new LockableMap<>(new LinkedHashMap<>()); - QueueManager(AsteriskServerImpl server, ChannelManager channelManager) - { + QueueManager(AsteriskServerImpl server, ChannelManager channelManager) { this.server = server; this.channelManager = channelManager; - this.queues = new HashMap(); } - void initialize() throws ManagerCommunicationException - { + void initialize() throws ManagerCommunicationException { ResponseEvents re; - try - { + try { re = server.sendEventGeneratingAction(new QueueStatusAction()); - } - catch (ManagerCommunicationException e) - { + } catch (ManagerCommunicationException e) { final Throwable cause = e.getCause(); - if (cause instanceof EventTimeoutException) - { + if (cause instanceof EventTimeoutException) { // this happens with Asterisk 1.0.x as it doesn't send a // QueueStatusCompleteEvent re = ((EventTimeoutException) cause).getPartialResult(); - } - else - { + } else { throw e; } } - for (ManagerEvent event : re.getEvents()) - { - if (event instanceof QueueParamsEvent) - { + for (ManagerEvent event : re.getEvents()) { + if (event instanceof QueueParamsEvent) { handleQueueParamsEvent((QueueParamsEvent) event); - } - else if (event instanceof QueueMemberEvent) - { + } else if (event instanceof QueueMemberEvent) { handleQueueMemberEvent((QueueMemberEvent) event); + } else if (event instanceof QueueEntryEvent) { + handleQueueEntryEvent((QueueEntryEvent) event); } - else if (event instanceof QueueEntryEvent) - { + } + + } + + /** + * Method to ask for a Queue data update + * + * @param queue + * @throws ManagerCommunicationException + * @author Octavio Luna + */ + void updateQueue(String queue) throws ManagerCommunicationException { + ResponseEvents re; + + try { + QueueStatusAction queueStatusAction = new QueueStatusAction(); + queueStatusAction.setQueue(queue); + re = server.sendEventGeneratingAction(queueStatusAction); + } catch (ManagerCommunicationException e) { + final Throwable cause = e.getCause(); + + if (cause instanceof EventTimeoutException) { + // this happens with Asterisk 1.0.x as it doesn't send a + // QueueStatusCompleteEvent + re = ((EventTimeoutException) cause).getPartialResult(); + } else { + throw e; + } + } + + for (ManagerEvent event : re.getEvents()) { + // 101119 OLB: solo actualizamos el QUEUE por ahora + if (event instanceof QueueParamsEvent) { + handleQueueParamsEvent((QueueParamsEvent) event); + } else if (event instanceof QueueMemberEvent) { + handleQueueMemberEvent((QueueMemberEvent) event); + } else if (event instanceof QueueEntryEvent) { handleQueueEntryEvent((QueueEntryEvent) event); } + } } - void disconnected() - { - synchronized (queues) - { - for(AsteriskQueueImpl queue : queues.values()) - { + void disconnected() { + try (LockCloser closer = queuesLRU.withLock()) { + for (AsteriskQueueImpl queue : queuesLRU.values()) { queue.cancelServiceLevelTimer(); } - queues.clear(); + queuesLRU.clear(); } } @@ -114,14 +139,37 @@ void disconnected() * * @return a copy of the list of the queues. */ - Collection getQueues() - { + Collection getQueues() { + refreshQueuesIfForced(); + Collection copy; - synchronized (queues) - { - copy = new ArrayList(queues.values()); + try (LockCloser closer = queuesLRU.withLock()) { + copy = new ArrayList(queuesLRU.values()); + } + return copy; + } + + public List getQueuesUpdatedAfter(Date date) { + refreshQueuesIfForced(); + + List copy = new ArrayList<>(); + try (LockCloser closer = queuesLRU.withLock()) { + List> list = new ArrayList<>(queuesLRU.entrySet()); + ListIterator> iter = list.listIterator(list.size()); + + Entry entry; + while (iter.hasPrevious()) { + entry = iter.previous(); + AsteriskQueueImpl astQueue = entry.getValue(); + if (astQueue.getLastUpdateMillis() <= date.getTime()) { + break; + } + copy.add(astQueue); + } + } + return copy; } @@ -130,11 +178,9 @@ Collection getQueues() * * @param queue the AsteriskQueueImpl to be added */ - private void addQueue(AsteriskQueueImpl queue) - { - synchronized (queues) - { - queues.put(queue.getName(), queue); + private void addQueue(AsteriskQueueImpl queue) { + try (LockCloser closer = queuesLRU.withLock()) { + queuesLRU.put(queue.getName(), queue); } } @@ -143,38 +189,44 @@ private void addQueue(AsteriskQueueImpl queue) * * @param event the event received */ - private void handleQueueParamsEvent(QueueParamsEvent event) - { + private void handleQueueParamsEvent(QueueParamsEvent event) { AsteriskQueueImpl queue; - final String name; - final Integer max; - final String strategy; - final Integer serviceLevel; - final Integer weight; - - name = event.getQueue(); - max = event.getMax(); - strategy = event.getStrategy(); - serviceLevel = event.getServiceLevel(); - weight = event.getWeight(); - - queue = queues.get(name); - - if (queue == null) - { - queue = new AsteriskQueueImpl(server, name, max, strategy, serviceLevel, weight); + + final String name = event.getQueue(); + final Integer max = event.getMax(); + final String strategy = event.getStrategy(); + final Integer serviceLevel = event.getServiceLevel(); + final Integer weight = event.getWeight(); + final Integer calls = event.getCalls(); + final Integer holdTime = event.getHoldTime(); + final Integer talkTime = event.getTalkTime(); + final Integer completed = event.getCompleted(); + final Integer abandoned = event.getAbandoned(); + final Double serviceLevelPerf = event.getServiceLevelPerf(); + + queue = getInternalQueueByName(name); + + if (queue == null) { + queue = new AsteriskQueueImpl(server, name, max, strategy, serviceLevel, weight, calls, holdTime, talkTime, + completed, abandoned, serviceLevelPerf); logger.info("Adding new queue " + queue); addQueue(queue); - } - else - { - // We should never reach that code as this method is only called for initialization + } else { + // We should never reach that code as this method is only called for + // initialization // So the queue should never be in the queues list - synchronized (queue) - { - queue.setMax(max); - queue.setServiceLevel(serviceLevel); - queue.setWeight(weight); + try (LockCloser closer = queue.withLock()) { + try (LockCloser closer2 = queuesLRU.withLock()) { + + if (queue.setMax(max) | queue.setServiceLevel(serviceLevel) | queue.setWeight(weight) + | queue.setCalls(calls) | queue.setHoldTime(holdTime) | queue.setTalkTime(talkTime) + | queue.setCompleted(completed) | queue.setAbandoned(abandoned) + | queue.setServiceLevelPerf(serviceLevelPerf)) { + + queuesLRU.remove(queue.getName()); + queuesLRU.put(queue.getName(), queue); + } + } } } } @@ -184,58 +236,88 @@ private void handleQueueParamsEvent(QueueParamsEvent event) * * @param event the QueueMemberEvent received */ - private void handleQueueMemberEvent(QueueMemberEvent event) - { - final AsteriskQueueImpl queue = queues.get(event.getQueue()); - if (queue == null) - { + private void handleQueueMemberEvent(QueueMemberEvent event) { + final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); + if (queue == null) { logger.error("Ignored QueueEntryEvent for unknown queue " + event.getQueue()); return; } - AsteriskQueueMemberImpl member = queue.getMember(event.getLocation()); - if (member == null) - { - member = new AsteriskQueueMemberImpl(server, queue, event.getLocation(), - QueueMemberState.valueOf(event.getStatus()), event.getPaused(), - event.getPenalty(), event.getMembership()); + AsteriskQueueMemberImpl member = queue.getMember(event.getInterface()); + if (member == null) { + member = new AsteriskQueueMemberImpl(server, queue, event.getInterface(), + QueueMemberState.valueOf(event.getStatus()), event.getPaused(), event.getPenalty(), + event.getMembership(), event.getCallsTaken(), event.getLastCall()); + + queue.addMember(member); + } else { + manageQueueMemberChange(queue, member, event); + } + + } + + private void manageQueueMemberChange(AsteriskQueueImpl queue, AsteriskQueueMemberImpl member, QueueMemberEvent event) { + if (member.stateChanged(QueueMemberState.valueOf(event.getStatus())) | member.pausedChanged(event.getPaused()) + | member.penaltyChanged(event.getPenalty()) | member.callsTakenChanged(event.getCallsTaken()) + | member.lastCallChanged(event.getLastCall())) { + queue.stampLastUpdate(); } - queue.addMember(member); } /** - * Called during initialization to populate entries of the queues. - * Currently does the same as handleJoinEvent() + * Called during initialization to populate entries of the queues. Currently + * does the same as handleJoinEvent() * * @param event - the QueueEntryEvent received */ - private void handleQueueEntryEvent(QueueEntryEvent event) - { - final AsteriskQueueImpl queue = getQueueByName(event.getQueue()); - final AsteriskChannelImpl channel = channelManager - .getChannelImplByName(event.getChannel()); - - if (queue == null) - { + private void handleQueueEntryEvent(QueueEntryEvent event) { + final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); + final AsteriskChannelImpl channel = channelManager.getChannelImplByName(event.getChannel()); + + if (queue == null) { logger.error("Ignored QueueEntryEvent for unknown queue " + event.getQueue()); return; } - if (channel == null) - { + if (channel == null) { logger.error("Ignored QueueEntryEvent for unknown channel " + event.getChannel()); return; } - if (queue.getEntry(event.getChannel()) != null) - { - logger.error("Ignored duplicate queue entry during population in queue " - + event.getQueue() + " for channel " + event.getChannel()); + // Asterisk gives us an initial position but doesn't tell us when he + // shifts the others + // We won't use this data for ordering until there is a appropriate + // event in AMI. + // (and refreshing the whole queue is too intensive and suffers + // incoherencies + // due to asynchronous shift that leaves holes if requested too fast) + int reportedPosition = event.getPosition(); + + queue.createNewEntry(channel, reportedPosition, event.getDateReceived()); + } + + /** + * + * Called from AsteriskServerImpl whenever a new entry appears in a + * queue. + * + * @param event the JoinEvent received + + */ + void handleJoinEvent(QueueCallerJoinEvent event) { + final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); + final AsteriskChannelImpl channel = channelManager.getChannelImplByName(event.getChannel()); + + if (queue == null) { + logger.error("Ignored JoinEvent for unknown queue " + event.getQueue()); + return; + } + if (channel == null) { + logger.error("Ignored JoinEvent for unknown channel " + event.getChannel()); return; } - // Asterisk gives us an initial position but doesn't tell us when he shifts the others - // We won't use this data for ordering until there is a appropriate event in AMI. - // (and refreshing the whole queue is too intensive and suffers incoherencies + // Asterisk gives us an initial position but doesn't tell us when he + // shifts the others + // We won't use this data for ordering until there is a appropriate + // event in AMI. + // (and refreshing the whole queue is too intensive and suffers + // incoherencies // due to asynchronous shift that leaves holes if requested too fast) int reportedPosition = event.getPosition(); @@ -247,32 +329,25 @@ private void handleQueueEntryEvent(QueueEntryEvent event) * * @param event the JoinEvent received */ - void handleJoinEvent(JoinEvent event) - { - final AsteriskQueueImpl queue = getQueueByName(event.getQueue()); + void handleJoinEvent(JoinEvent event) { + final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); final AsteriskChannelImpl channel = channelManager.getChannelImplByName(event.getChannel()); - if (queue == null) - { + if (queue == null) { logger.error("Ignored JoinEvent for unknown queue " + event.getQueue()); return; } - if (channel == null) - { + if (channel == null) { logger.error("Ignored JoinEvent for unknown channel " + event.getChannel()); return; } - if (queue.getEntry(event.getChannel()) != null) - { - logger.error("Ignored duplicate queue entry in queue " - + event.getQueue() + " for channel " + event.getChannel()); - return; - } - - // Asterisk gives us an initial position but doesn't tell us when he shifts the others - // We won't use this data for ordering until there is a appropriate event in AMI. - // (and refreshing the whole queue is too intensive and suffers incoherencies + // Asterisk gives us an initial position but doesn't tell us when he + // shifts the others + // We won't use this data for ordering until there is a appropriate + // event in AMI. + // (and refreshing the whole queue is too intensive and suffers + // incoherencies // due to asynchronous shift that leaves holes if requested too fast) int reportedPosition = event.getPosition(); @@ -284,27 +359,23 @@ void handleJoinEvent(JoinEvent event) * * @param event - the LeaveEvent received */ - void handleLeaveEvent(LeaveEvent event) - { - final AsteriskQueueImpl queue = getQueueByName(event.getQueue()); + void handleLeaveEvent(QueueCallerLeaveEvent event) { + final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); final AsteriskChannelImpl channel = channelManager.getChannelImplByName(event.getChannel()); - if (queue == null) - { + if (queue == null) { logger.error("Ignored LeaveEvent for unknown queue " + event.getQueue()); return; } - if (channel == null) - { + if (channel == null) { logger.error("Ignored LeaveEvent for unknown channel " + event.getChannel()); return; } final AsteriskQueueEntryImpl existingQueueEntry = queue.getEntry(event.getChannel()); - if (existingQueueEntry == null) - { - logger.error("Ignored leave event for non existing queue entry in queue " - + event.getQueue() + " for channel " + event.getChannel()); + if (existingQueueEntry == null) { + logger.error("Ignored leave event for non existing queue entry in queue " + event.getQueue() + " for channel " + + event.getChannel()); return; } @@ -312,65 +383,84 @@ void handleLeaveEvent(LeaveEvent event) } /** - * Challange a QueueMemberStatusEvent. - * Called from AsteriskServerImpl whenever a member state changes. + * Called from AsteriskServerImpl whenever an enty leaves a queue. + * + * @param event - the LeaveEvent received + */ + void handleLeaveEvent(LeaveEvent event) { + final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); + final AsteriskChannelImpl channel = channelManager.getChannelImplByName(event.getChannel()); + + if (queue == null) { + logger.error("Ignored LeaveEvent for unknown queue " + event.getQueue()); + return; + } + if (channel == null) { + logger.error("Ignored LeaveEvent for unknown channel " + event.getChannel()); + return; + } + + final AsteriskQueueEntryImpl existingQueueEntry = queue.getEntry(event.getChannel()); + if (existingQueueEntry == null) { + logger.error("Ignored leave event for non existing queue entry in queue " + event.getQueue() + " for channel " + + event.getChannel()); + return; + } + + queue.removeEntry(existingQueueEntry, event.getDateReceived()); + } + + /** + * Challange a QueueMemberStatusEvent. Called from AsteriskServerImpl + * whenever a member state changes. * * @param event that was triggered by Asterisk server. */ - void handleQueueMemberStatusEvent(QueueMemberStatusEvent event) - { - AsteriskQueueImpl queue = getQueueByName(event.getQueue()); + void handleQueueMemberStatusEvent(QueueMemberStatusEvent event) { + AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); - if (queue == null) - { + if (queue == null) { logger.error("Ignored QueueMemberStatusEvent for unknown queue " + event.getQueue()); return; } - AsteriskQueueMemberImpl member = queue.getMemberByLocation(event.getLocation()); - if (member == null) - { - logger.error("Ignored QueueMemberStatusEvent for unknown member " + event.getLocation()); + AsteriskQueueMemberImpl member = queue.getMemberByLocation(event.getInterface()); + if (member == null) { + logger.error("Ignored QueueMemberStatusEvent for unknown member " + event.getInterface()); return; } - member.stateChanged(QueueMemberState.valueOf(event.getStatus())); - member.penaltyChanged(event.getPenalty()); + manageQueueMemberChange(queue, member, event); queue.fireMemberStateChanged(member); } void handleQueueMemberPausedEvent(QueueMemberPausedEvent event) { - AsteriskQueueImpl queue = getQueueByName(event.getQueue()); + AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); - if (queue == null) - { + if (queue == null) { logger.error("Ignored QueueMemberPausedEvent for unknown queue " + event.getQueue()); return; } - AsteriskQueueMemberImpl member = queue.getMemberByLocation(event.getLocation()); - if (member == null) - { - logger.error("Ignored QueueMemberPausedEvent for unknown member " + event.getLocation()); + AsteriskQueueMemberImpl member = queue.getMemberByLocation(event.getInterface()); + if (member == null) { + logger.error("Ignored QueueMemberPausedEvent for unknown member " + event.getInterface()); return; } member.pausedChanged(event.getPaused()); } - - void handleQueueMemberPenaltyEvent(QueueMemberPenaltyEvent event) - { - AsteriskQueueImpl queue = getQueueByName(event.getQueue()); - if (queue == null) - { + void handleQueueMemberPenaltyEvent(QueueMemberPenaltyEvent event) { + AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); + + if (queue == null) { logger.error("Ignored QueueMemberStatusEvent for unknown queue " + event.getQueue()); return; } AsteriskQueueMemberImpl member = queue.getMemberByLocation(event.getLocation()); - if (member == null) - { + if (member == null) { logger.error("Ignored QueueMemberStatusEvent for unknown member " + event.getLocation()); return; } @@ -382,43 +472,59 @@ void handleQueueMemberPenaltyEvent(QueueMemberPenaltyEvent event) * Retrieves a queue by its name. * * @param queueName name of the queue. - * @return the requested queue or null if there is no queue with the given name. + * @return the requested queue or null if there is no queue + * with the given name. */ - private AsteriskQueueImpl getQueueByName(String queueName) - { - AsteriskQueueImpl queue; + AsteriskQueueImpl getQueueByName(String queueName) { + refreshQueueIfForced(queueName); - synchronized (queues) - { - queue = queues.get(queueName); - } - if (queue == null) - { + AsteriskQueueImpl queue = getInternalQueueByName(queueName); + if (queue == null) { logger.error("Requested queue '" + queueName + "' not found!"); } + + return queue; + } + + private AsteriskQueueImpl getInternalQueueByName(String queueName) { + AsteriskQueueImpl queue; + + try (LockCloser closer = queuesLRU.withLock()) { + queue = queuesLRU.get(queueName); + } return queue; } + private void refreshQueueIfForced(String queueName) { + if (queuesMonitorForced) { + updateQueue(queueName); + } + } + + private void refreshQueuesIfForced() { + if (queuesMonitorForced && (System.currentTimeMillis() - queueMonitorLastTimeReloaded) > queuesMonitorLeaseTime) { + initialize(); + queueMonitorLastTimeReloaded = System.currentTimeMillis(); + } + } + /** * Challange a QueueMemberAddedEvent. * * @param event - the generated QueueMemberAddedEvent. */ - public void handleQueueMemberAddedEvent(QueueMemberAddedEvent event) - { - final AsteriskQueueImpl queue = queues.get(event.getQueue()); - if (queue == null) - { + public void handleQueueMemberAddedEvent(QueueMemberAddedEvent event) { + final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); + if (queue == null) { logger.error("Ignored QueueMemberAddedEvent for unknown queue " + event.getQueue()); return; } - AsteriskQueueMemberImpl member = queue.getMember(event.getLocation()); - if (member == null) - { - member = new AsteriskQueueMemberImpl(server, queue, event.getLocation(), - QueueMemberState.valueOf(event.getStatus()), event.getPaused(), - event.getPenalty(), event.getMembership()); + AsteriskQueueMemberImpl member = queue.getMember(event.getInterface()); + if (member == null) { + member = new AsteriskQueueMemberImpl(server, queue, event.getInterface(), + QueueMemberState.valueOf(event.getStatus()), event.getPaused(), event.getPenalty(), + event.getMembership(), event.getCallsTaken(), event.getLastCall()); } queue.addMember(member); @@ -429,24 +535,28 @@ public void handleQueueMemberAddedEvent(QueueMemberAddedEvent event) * * @param event - the generated QueueMemberRemovedEvent. */ - public void handleQueueMemberRemovedEvent(QueueMemberRemovedEvent event) - { - final AsteriskQueueImpl queue = queues.get(event.getQueue()); - if (queue == null) - { + public void handleQueueMemberRemovedEvent(QueueMemberRemovedEvent event) { + final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); + if (queue == null) { logger.error("Ignored QueueMemberRemovedEvent for unknown queue " + event.getQueue()); return; } - final AsteriskQueueMemberImpl member = queue.getMember(event.getLocation()); - if (member == null) - { - logger.error("Ignored QueueMemberRemovedEvent for unknown agent name: " - + event.getMemberName() + " location: " + event.getLocation() - + " queue: " + event.getQueue()); + final AsteriskQueueMemberImpl member = queue.getMember(event.getInterface()); + if (member == null) { + logger.error("Ignored QueueMemberRemovedEvent for unknown agent name: " + event.getMemberName() + " location: " + + event.getInterface() + " queue: " + event.getQueue()); return; } queue.removeMember(member); } + + public void forceQueuesMonitor(boolean force) { + queuesMonitorForced = force; + } + + public boolean isQueuesMonitorForced() { + return queuesMonitorForced; + } } diff --git a/src/main/java/org/asteriskjava/live/internal/package.html b/src/main/java/org/asteriskjava/live/internal/package.html index 90995dfa5..5f3ca4a84 100644 --- a/src/main/java/org/asteriskjava/live/internal/package.html +++ b/src/main/java/org/asteriskjava/live/internal/package.html @@ -1,28 +1,28 @@ - + -

      Provides private implementations and helper classes for interfaces +

      Provides private implementations and helper classes for interfaces defined in the org.asteriskjava.live package.

      - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/live/package.html b/src/main/java/org/asteriskjava/live/package.html index 1560b214b..d33273ce2 100644 --- a/src/main/java/org/asteriskjava/live/package.html +++ b/src/main/java/org/asteriskjava/live/package.html @@ -1,27 +1,27 @@ - +

      Provides a higher level API on top of Asterisk's Manager API.

      - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/lock/Lockable.java b/src/main/java/org/asteriskjava/lock/Lockable.java new file mode 100644 index 000000000..e1e7b06c4 --- /dev/null +++ b/src/main/java/org/asteriskjava/lock/Lockable.java @@ -0,0 +1,132 @@ +package org.asteriskjava.lock; + +import com.google.common.util.concurrent.RateLimiter; +import org.asteriskjava.lock.Locker.LockCloser; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; + +public class Lockable { + private final ReentrantLock internalLock = new ReentrantLock(false); + final private String lockName; + final AtomicReference threadHoldingLock = new AtomicReference<>(); + private final AtomicInteger totalWaitTime = new AtomicInteger(); + private final AtomicInteger totalHoldTime = new AtomicInteger(); + private final AtomicInteger requested = new AtomicInteger(); + private final AtomicInteger waited = new AtomicInteger(); + private final AtomicInteger acquired = new AtomicInteger(); + private volatile boolean dumped = false; + private volatile boolean blocked = false; + + private final RateLimiter rateLimiter = RateLimiter.create(4); + + private final static AtomicLong seed = new AtomicLong(); + private final long lockableId = seed.incrementAndGet(); + + public Lockable() { + this.lockName = getLockCaller(); + } + + private String getLockCaller() { + StackTraceElement[] trace = new Exception().getStackTrace(); + String name = this.getClass().getCanonicalName(); + for (StackTraceElement element : trace) { + if (element.getFileName() != null && !element.getFileName().contains(Lockable.class.getSimpleName())) { + name = element.getFileName() + " " + element.getMethodName() + " " + element.getLineNumber() + " " + + element.getClassName(); + break; + } + } + + return name; + } + + String asLockString() { + return "Lockable [waited=" + waited + ", waitTime=" + totalWaitTime + ", totalHoldTime=" + totalHoldTime + + ", acquired=" + acquired + ", object=" + lockName + ", id=" + lockableId + "]"; + } + + long getLockAverageHoldTime() { + long hold = totalHoldTime.get(); + long count = acquired.get(); + if (count < 10) { + return 250; + } + return Math.max(hold / count, 50); + } + + public LockCloser withLock() { + return Locker.doWithLock(this); + } + + ReentrantLock getInternalLock() { + return internalLock; + } + + void addLockTotalWaitTime(int time) { + totalWaitTime.addAndGet(time); + } + + void addLockTotalHoldTime(int time) { + totalHoldTime.addAndGet(time); + } + + int addLockRequested() { + return requested.incrementAndGet(); + } + + void addLockWaited(int time) { + waited.addAndGet(time); + } + + void addLockAcquired(int count) { + acquired.addAndGet(count); + } + + boolean isLockDumped() { + return dumped; + } + + void setLockDumped(boolean dumped) { + this.dumped = dumped; + } + + int getLockTotalWaitTime() { + return totalWaitTime.intValue(); + } + + int getLockWaited() { + return waited.intValue(); + } + + int getLockRequested() { + return requested.intValue(); + } + + Long getLockableId() { + return lockableId; + } + + int getLockTotalHoldTime() { + return totalHoldTime.intValue(); + } + + int getLockAcquired() { + return acquired.intValue(); + } + + boolean wasLockBlocked() { + return blocked; + } + + void setLockBlocked(boolean blocked) { + this.blocked = blocked; + } + + public RateLimiter getDumpRateLimit() { + return rateLimiter; + } + +} diff --git a/src/main/java/org/asteriskjava/lock/LockableList.java b/src/main/java/org/asteriskjava/lock/LockableList.java new file mode 100644 index 000000000..78c87b68a --- /dev/null +++ b/src/main/java/org/asteriskjava/lock/LockableList.java @@ -0,0 +1,147 @@ +package org.asteriskjava.lock; + +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; +import java.util.stream.Stream; + +public class LockableList extends Lockable implements List { + final List list; + + public LockableList(List list) { + if (list instanceof Lockable) { + throw new RuntimeException("list is already lockable"); + } + this.list = list; + } + + public void forEach(Consumer action) { + list.forEach(action); + } + + public int size() { + return list.size(); + } + + public boolean isEmpty() { + return list.isEmpty(); + } + + public boolean contains(Object o) { + return list.contains(o); + } + + public Iterator iterator() { + return list.iterator(); + } + + public Object[] toArray() { + return list.toArray(); + } + + public T[] toArray(T[] a) { + return list.toArray(a); + } + + public boolean add(S e) { + return list.add(e); + } + + public boolean remove(Object o) { + return list.remove(o); + } + + public boolean containsAll(Collection c) { + return list.containsAll(c); + } + + public boolean addAll(Collection c) { + return list.addAll(c); + } + + public boolean addAll(int index, Collection c) { + return list.addAll(index, c); + } + + public boolean removeAll(Collection c) { + return list.removeAll(c); + } + + public boolean retainAll(Collection c) { + return list.retainAll(c); + } + + public void replaceAll(UnaryOperator operator) { + list.replaceAll(operator); + } + + public boolean removeIf(Predicate filter) { + return list.removeIf(filter); + } + + public void sort(Comparator c) { + list.sort(c); + } + + public void clear() { + list.clear(); + } + + public boolean equals(Object o) { + return list.equals(o); + } + + public int hashCode() { + return list.hashCode(); + } + + public S get(int index) { + return list.get(index); + } + + public S set(int index, S element) { + return list.set(index, element); + } + + public void add(int index, S element) { + list.add(index, element); + } + + public Stream stream() { + return list.stream(); + } + + public S remove(int index) { + return list.remove(index); + } + + public Stream parallelStream() { + return list.parallelStream(); + } + + public int indexOf(Object o) { + return list.indexOf(o); + } + + public int lastIndexOf(Object o) { + return list.lastIndexOf(o); + } + + public ListIterator listIterator() { + return list.listIterator(); + } + + public ListIterator listIterator(int index) { + return list.listIterator(index); + } + + public List subList(int fromIndex, int toIndex) { + return list.subList(fromIndex, toIndex); + } + + public Spliterator spliterator() { + return list.spliterator(); + } + +} diff --git a/src/main/java/org/asteriskjava/lock/LockableMap.java b/src/main/java/org/asteriskjava/lock/LockableMap.java new file mode 100644 index 000000000..ca919bc0d --- /dev/null +++ b/src/main/java/org/asteriskjava/lock/LockableMap.java @@ -0,0 +1,120 @@ +package org.asteriskjava.lock; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +public class LockableMap extends Lockable implements Map { + final Map map; + + public LockableMap(Map map) { + if (map instanceof Lockable) { + throw new RuntimeException("map is already lockable"); + } + this.map = map; + } + + public int size() { + return map.size(); + } + + public boolean isEmpty() { + return map.isEmpty(); + } + + public boolean containsKey(Object key) { + return map.containsKey(key); + } + + public boolean containsValue(Object value) { + return map.containsValue(value); + } + + public P get(Object key) { + return map.get(key); + } + + public P put(S key, P value) { + return map.put(key, value); + } + + public P remove(Object key) { + return map.remove(key); + } + + public void putAll(Map m) { + map.putAll(m); + } + + public void clear() { + map.clear(); + } + + public Set keySet() { + return map.keySet(); + } + + public Collection

      values() { + return map.values(); + } + + public Set> entrySet() { + return map.entrySet(); + } + + public boolean equals(Object o) { + return map.equals(o); + } + + public int hashCode() { + return map.hashCode(); + } + + public P getOrDefault(Object key, P defaultValue) { + return map.getOrDefault(key, defaultValue); + } + + public void forEach(BiConsumer action) { + map.forEach(action); + } + + public void replaceAll(BiFunction function) { + map.replaceAll(function); + } + + public P putIfAbsent(S key, P value) { + return map.putIfAbsent(key, value); + } + + public boolean remove(Object key, Object value) { + return map.remove(key, value); + } + + public boolean replace(S key, P oldValue, P newValue) { + return map.replace(key, oldValue, newValue); + } + + public P replace(S key, P value) { + return map.replace(key, value); + } + + public P computeIfAbsent(S key, Function mappingFunction) { + return map.computeIfAbsent(key, mappingFunction); + } + + public P computeIfPresent(S key, BiFunction remappingFunction) { + return map.computeIfPresent(key, remappingFunction); + } + + public P compute(S key, BiFunction remappingFunction) { + return map.compute(key, remappingFunction); + } + + public P merge(S key, P value, BiFunction remappingFunction) { + return map.merge(key, value, remappingFunction); + } + +} diff --git a/src/main/java/org/asteriskjava/lock/LockableSet.java b/src/main/java/org/asteriskjava/lock/LockableSet.java new file mode 100644 index 000000000..f88bd5de6 --- /dev/null +++ b/src/main/java/org/asteriskjava/lock/LockableSet.java @@ -0,0 +1,101 @@ +package org.asteriskjava.lock; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Set; +import java.util.Spliterator; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.Stream; + +public class LockableSet extends Lockable implements Set { + final Set set; + + public LockableSet(Set set) { + if (set instanceof Lockable) { + throw new RuntimeException("set is already lockable"); + } + this.set = set; + } + + public void forEach(Consumer action) { + set.forEach(action); + } + + public int size() { + return set.size(); + } + + public boolean isEmpty() { + return set.isEmpty(); + } + + public boolean contains(Object o) { + return set.contains(o); + } + + public Iterator iterator() { + return set.iterator(); + } + + public Object[] toArray() { + return set.toArray(); + } + + public T[] toArray(T[] a) { + return set.toArray(a); + } + + public boolean add(S e) { + return set.add(e); + } + + public boolean remove(Object o) { + return set.remove(o); + } + + public boolean containsAll(Collection c) { + return set.containsAll(c); + } + + public boolean addAll(Collection c) { + return set.addAll(c); + } + + public boolean retainAll(Collection c) { + return set.retainAll(c); + } + + public boolean removeAll(Collection c) { + return set.removeAll(c); + } + + public void clear() { + set.clear(); + } + + public boolean equals(Object o) { + return set.equals(o); + } + + public int hashCode() { + return set.hashCode(); + } + + public Spliterator spliterator() { + return set.spliterator(); + } + + public boolean removeIf(Predicate filter) { + return set.removeIf(filter); + } + + public Stream stream() { + return set.stream(); + } + + public Stream parallelStream() { + return set.parallelStream(); + } + +} diff --git a/src/main/java/org/asteriskjava/lock/Locker.java b/src/main/java/org/asteriskjava/lock/Locker.java new file mode 100644 index 000000000..d8edcab28 --- /dev/null +++ b/src/main/java/org/asteriskjava/lock/Locker.java @@ -0,0 +1,266 @@ +package org.asteriskjava.lock; + +import com.google.common.util.concurrent.RateLimiter; +import org.asteriskjava.pbx.util.LogTime; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +public class Locker { + + private static final Log logger = LogFactory.getLog(Locker.class); + + private static volatile boolean diags = false; + + private static ScheduledFuture future; + private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); + + private static final Object sync = new Object(); + + // keep references to Lockables so they can't be garbage collected between + // reporting intervals + private static final Map keepList = new HashMap<>(); + + private static final RateLimiter waitRateLimiter = RateLimiter.create(4); + + public static LockCloser doWithLock(final Lockable lockable) { + try { + if (diags) { + synchronized (sync) { + keepList.put(lockable.getLockableId(), lockable); + } + return lockWithDiags(lockable); + } + return simpleLock(lockable); + } catch (Exception e) { + throw new RuntimeException(e); + } + + } + + /** + * determine the caller to Locker + * + * @param lockable + * @return + */ + static String getCaller(Lockable lockable) { + StackTraceElement[] trace = new Exception().getStackTrace(); + String name = lockable.getClass().getCanonicalName(); + for (StackTraceElement element : trace) { + if (element.getFileName() != null && !element.getFileName().contains(Locker.class.getSimpleName())) { + name = element.getFileName() + " " + element.getMethodName() + " " + element.getLineNumber() + " " + + element.getClassName(); + break; + } + } + + return name; + } + + public interface LockCloser extends AutoCloseable { + public void close(); + } + + // Once every ten seconds max + private static RateLimiter warnRateLimiter = RateLimiter.create(0.1); + + private static final LogTime startTime = new LogTime(); + + private static LockCloser simpleLock(Lockable lockable) throws InterruptedException { + LogTime acquireTimer = new LogTime(); + ReentrantLock lock = lockable.getInternalLock(); + lock.lock(); + // lock acquired! + if (acquireTimer.timeTaken() > 1_000 && warnRateLimiter.tryAcquire()) { + logger.warn("Locks are being held for to long, waited " + acquireTimer.timeTaken() + + "ms, you can enable lock diagnostics by calling Locker.enable()"); + } + + LogTime holdTimer = new LogTime(); + return () -> { + lock.unlock(); + + if (holdTimer.timeTaken() > 500 && warnRateLimiter.tryAcquire()) { + // don't start warning for the first 10 seconds + if (startTime.timeTaken() > 10_000) { + logger.warn("Locks are being held for to long (" + holdTimer.timeTaken() + + "ms), you can enable lock diagnostics by calling Locker.enable()"); + } + } + }; + } + + private static LockCloser lockWithDiags(Lockable lockable) throws InterruptedException { + + int offset = lockable.addLockRequested(); + long waitStart = System.currentTimeMillis(); + + ReentrantLock lock = lockable.getInternalLock(); + while (!lock.tryLock(100, TimeUnit.MILLISECONDS)) { + if (!lockable.isLockDumped() && lockable.getDumpRateLimit().tryAcquire()) { + lockable.setLockDumped(true); + dumpThread(lockable.threadHoldingLock.get(), + "Waiting on lock... blocked by... id:" + lockable.getLockableId()); + } else { + if (waitRateLimiter.tryAcquire()) { + long elapsed = System.currentTimeMillis() - waitStart; + logger.warn("waiting " + elapsed + "(MS) id:" + lockable.getLockableId()); + } + } + lockable.setLockBlocked(true); + } + lockable.setLockDumped(false); + lockable.addLockAcquired(1); + + long acquiredAt = System.currentTimeMillis(); + lockable.threadHoldingLock.set(Thread.currentThread()); + return new LockCloser() { + + @Override + public void close() { + // ignore any wait that may have been caused by Locker code, so + // count the waiters before we release the lock + long waiters = lockable.getLockRequested() - offset; + lockable.addLockWaited((int) waiters); + + boolean dumped = lockable.isLockDumped(); + // release the lock + lock.unlock(); + + // count the time waiting and holding the lock + int holdTime = (int) (System.currentTimeMillis() - acquiredAt); + int waitTime = (int) (acquiredAt - waitStart); + lockable.addLockTotalWaitTime(waitTime); + lockable.addLockTotalHoldTime(holdTime); + + long averageHoldTime = lockable.getLockAverageHoldTime(); + if ((waiters > 0 && holdTime > averageHoldTime * 2) || dumped) { + // some threads waited + String message = "Lock held for (" + holdTime + "MS), " + waiters + + " threads waited for some of that time! " + getCaller(lockable) + " id:" + + lockable.getLockableId(); + logger.warn(message); + if (holdTime > averageHoldTime * 10.0 || dumped) { + Exception trace = new Exception(message); + logger.error(trace, trace); + } + } + + if (holdTime > averageHoldTime * 5.0) { + // long hold! + String message = "Lock hold of lock (" + holdTime + "MS), average is " + + lockable.getLockAverageHoldTime() + " " + getCaller(lockable) + " id:" + + lockable.getLockableId(); + + logger.warn(message); + if (holdTime > averageHoldTime * 10.0) { + Exception trace = new Exception(message); + logger.error(trace, trace); + } + } + } + }; + + } + + public static void dumpThread(Thread thread, String message) { + + if (thread != null) { + StackTraceElement[] trace = thread.getStackTrace(); + + String dump = ""; + + int i = 0; + for (; i < trace.length; i++) { + StackTraceElement ste = trace[i]; + dump += "\tat " + ste.toString(); + dump += '\n'; + } + logger.error(message); + if (dump.length() > 0) { + logger.error(dump); + } else { + logger.error("Unable to create dump, thread seems to have exited."); + } + } else { + logger.error("Thread hasn't been set: " + message); + } + + } + + /** + * start dumping lock stats once per minute, can't be stopped once started. + */ + public static void enable() { + synchronized (sync) { + if (!diags) { + diags = true; + future = executor.scheduleWithFixedDelay(() -> { + dumpStats(); + }, 1, 1, TimeUnit.MINUTES); + logger.warn("Lock checking enabled"); + } else { + logger.warn("Already enabled"); + } + } + } + + public static void disable() { + synchronized (sync) { + if (diags) { + diags = false; + future.cancel(false); + dumpStats(); + logger.warn("Lock checking disabled"); + } else { + logger.warn("Lock checking is already disabled"); + } + } + } + + private static volatile boolean first = true; + + static void dumpStats() { + List lockables = new LinkedList<>(); + + synchronized (sync) { + lockables.addAll(keepList.values()); + keepList.clear(); + } + + boolean activity = false; + for (Lockable lockable : lockables) { + if (lockable.wasLockBlocked()) { + int waited = lockable.getLockWaited(); + int waitTime = lockable.getLockTotalWaitTime(); + int acquired = lockable.getLockAcquired(); + int holdTime = lockable.getLockTotalHoldTime(); + lockable.setLockBlocked(false); + activity = true; + logger.warn(lockable.asLockString()); + lockable.addLockWaited(-waited); + lockable.addLockTotalWaitTime(-waitTime); + + lockable.addLockAcquired(-acquired); + lockable.addLockTotalHoldTime(-holdTime); + + } + } + + if (first || activity) { + logger.warn("Will dump Lock stats each minute when there is contention..."); + first = false; + } + } + +} diff --git a/src/main/java/org/asteriskjava/manager/AbstractManagerEventListener.java b/src/main/java/org/asteriskjava/manager/AbstractManagerEventListener.java index 95fcac14b..51930ad72 100644 --- a/src/main/java/org/asteriskjava/manager/AbstractManagerEventListener.java +++ b/src/main/java/org/asteriskjava/manager/AbstractManagerEventListener.java @@ -1,50 +1,55 @@ package org.asteriskjava.manager; import org.asteriskjava.manager.event.*; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.lang.reflect.Method; /** - * Utility class that provides a protected handler method for each concrete manager event. - * Makes life easier by removing the need to code endless if-then-else constructs with instanceof - * checking for the events you are interested in. + * Utility class that provides a protected handler method for each concrete + * manager event. Makes life easier by removing the need to code endless + * if-then-else constructs with instanceof checking for the events you are + * interested in. *

      * Kindly donated by Steve Prior. *

      * Example based on HelloEvents from the tutorial: - * + * *

        * public class HelloEvents extends AbstractManagerEventListener
        * {
        *     private ManagerConnection managerConnection;
      - * 
      + *
        *     public HelloEvents(String machine, String userid, String password) throws IOException
        *     {
        *         ManagerConnectionFactory factory = new ManagerConnectionFactory(machine, userid, password);
        *         this.managerConnection = factory.createManagerConnection();
        *     }
      - * 
      + *
        *     public void run() throws Exception
        *     {
        *         // register for events
        *         managerConnection.addEventListener(this);
      - * 
      + *
        *         // connect to Asterisk and log in
        *         managerConnection.login();
      - * 
      + *
        *         // request channel state
        *         managerConnection.sendAction(new StatusAction());
      - * 
      + *
        *         // wait 10 seconds for events to come in
        *         Thread.sleep(10000);
      - * 
      + *
        *         // and finally log off and disconnect
        *         managerConnection.logoff();
        *     }
      - * 
      - *     protected void handleEvent(StatusEvent event)
      + *
      + *     public void handleEvent(StatusEvent event)
        *     {
        *         System.out.println(event.getChannel() + ":" + event.getState());
        *     }
      - * 
      + *
        *     public static void main(String[] args) throws Exception
        *     {
        *         HelloEvents helloEvents;
      @@ -53,562 +58,604 @@
        *     }
        * }
        * 
      - * + * * @author srt * @since 0.3 */ -public abstract class AbstractManagerEventListener implements ManagerEventListener -{ - protected void handleEvent(AgentCallbackLoginEvent event) - { +public abstract class AbstractManagerEventListener implements ManagerEventListener { + + private static final Log LOGGER = LogFactory.getLog(AbstractManagerEventListener.class); + + public void handleEvent(AgentCompleteEvent event) { + } + + public void handleEvent(AgentConnectEvent event) { + } + + public void handleEvent(AgentDumpEvent event) { + } + + public void handleEvent(AgentRingNoAnswerEvent event) { + } + + public void handleEvent(AttendedTransferEvent event) { + } + + public void handleEvent(BlindTransferEvent event) { + } + + public void handleEvent(BridgeCreateEvent event) { + } + + public void handleEvent(BridgeDestroyEvent event) { + } + + public void handleEvent(BridgeEnterEvent event) { + } + + public void handleEvent(BridgeLeaveEvent event) { + } + + public void handleEvent(HangupEvent event) { + } + + public void handleEvent(NewChannelEvent event) { + } + + public void handleEvent(NewStateEvent event) { + } + + public void handleEvent(ConfbridgeEndEvent event) { + } + + public void handleEvent(ConfbridgeJoinEvent event) { + } + + public void handleEvent(ConfbridgeLeaveEvent event) { + } + + public void handleEvent(ConfbridgeStartEvent event) { + } + + public void handleEvent(ConfbridgeTalkingEvent event) { + } + + public void handleEvent(AntennaLevelEvent event) { + } + + public void handleEvent(HangupRequestEvent event) { + } + + public void handleEvent(NewCallerIdEvent event) { + } + + public void handleEvent(SoftHangupRequestEvent event) { + } + + public void handleEvent(FaxDocumentStatusEvent event) { + } + + public void handleEvent(FaxReceivedEvent event) { + } + + public void handleEvent(FaxStatusEvent event) { + } + + public void handleEvent(SendFaxEvent event) { + } + + public void handleEvent(SendFaxStatusEvent event) { + } + + public void handleEvent(T38FaxStatusEvent event) { + } + + public void handleEvent(HoldEvent event) { + } + + public void handleEvent(UnholdEvent event) { + } + + public void handleEvent(MeetMeJoinEvent event) { + } + + public void handleEvent(MeetMeLeaveEvent event) { + } + + public void handleEvent(MeetMeMuteEvent event) { + } + + public void handleEvent(MeetMeTalkingEvent event) { + } + + public void handleEvent(MeetMeTalkingRequestEvent event) { + } + + public void handleEvent(MonitorStartEvent event) { + } + + public void handleEvent(MonitorStopEvent event) { + } + + public void handleEvent(ParkedCallEvent event) { + } + + public void handleEvent(QueueMemberAddedEvent event) { + } + + public void handleEvent(QueueMemberPausedEvent event) { + } + + public void handleEvent(QueueMemberRemovedEvent event) { + } + + public void handleEvent(QueueMemberRingInUseEvent event) { + } + + public void handleEvent(RtcpReceivedEvent event) { + } + + public void handleEvent(RtcpSentEvent event) { + } + + public void handleEvent(RtpReceiverStatEvent event) { + } + + public void handleEvent(RtpSenderStatEvent event) { + } + + public void handleEvent(AgentCallbackLoginEvent event) { + } + + public void handleEvent(AgentCallbackLogoffEvent event) { + } + + public void handleEvent(AgentCalledEvent event) { + } + + public void handleEvent(AgentLoginEvent event) { + } + + public void handleEvent(AgentLogoffEvent event) { + } + + public void handleEvent(AgiExecEvent event) { + } + + public void handleEvent(AgiExecEndEvent event) { + } + + public void handleEvent(AgiExecStartEvent event) { + } + + public void handleEvent(AlarmClearEvent event) { + } + + public void handleEvent(AlarmEvent event) { + } + + public void handleEvent(BridgeEvent event) { + } + + @SuppressWarnings("deprecation") + public void handleEvent(LinkEvent event) { + } + + @SuppressWarnings("deprecation") + public void handleEvent(UnlinkEvent event) { + } + + public void handleEvent(BridgeExecEvent event) { + } + + public void handleEvent(BridgeMergeEvent event) { + } + + public void handleEvent(CdrEvent event) { + } + + public void handleEvent(CelEvent event) { + } + + public void handleEvent(ChallengeResponseFailedEvent event) { + } + + public void handleEvent(ChallengeSentEvent event) { + } + + public void handleEvent(ChannelReloadEvent event) { + } + + public void handleEvent(ChannelUpdateEvent event) { + } + + public void handleEvent(ChanSpyStartEvent event) { + } + + public void handleEvent(ChanSpyStopEvent event) { + } + + public void handleEvent(ConnectEvent event) { + } + + public void handleEvent(ContactStatusEvent event) { + } + + public void handleEvent(DAHDIChannelEvent event) { + } + + public void handleEvent(DeviceStateChangeEvent event) { + } + + public void handleEvent(DialEvent event) { + } + + public void handleEvent(DialBeginEvent event) { + } + + public void handleEvent(DialEndEvent event) { + } + + public void handleEvent(DialStateEvent event) { + } + + public void handleEvent(DisconnectEvent event) { } - protected void handleEvent(AgentCallbackLogoffEvent event) - { + public void handleEvent(DndStateEvent event) { } - protected void handleEvent(AgentCalledEvent event) - { + public void handleEvent(DongleCallStateChangeEvent event) { } - protected void handleEvent(AgentLoginEvent event) - { + public void handleEvent(DongleCENDEvent event) { } - protected void handleEvent(AgentLogoffEvent event) - { + public void handleEvent(DongleNewCMGREvent event) { } - protected void handleEvent(AlarmClearEvent event) - { + public void handleEvent(DongleNewSMSBase64Event event) { } - protected void handleEvent(AlarmEvent event) - { + public void handleEvent(DongleNewSMSEvent event) { } - protected void handleEvent(CdrEvent event) - { + public void handleEvent(DongleStatusEvent event) { } - protected void handleEvent(ConnectEvent event) - { + public void handleEvent(DtmfEvent event) { } - protected void handleEvent(DialEvent event) - { + public void handleEvent(DtmfBeginEvent event) { } - protected void handleEvent(DisconnectEvent event) - { + public void handleEvent(DtmfEndEvent event) { } - protected void handleEvent(DndStateEvent event) - { + public void handleEvent(ExtensionStatusEvent event) { } - protected void handleEvent(ExtensionStatusEvent event) - { + public void handleEvent(FullyBootedEvent event) { } - protected void handleEvent(HoldedCallEvent event) - { + public void handleEvent(HoldedCallEvent event) { } - protected void handleEvent(HoldEvent event) - { + public void handleEvent(InvalidPasswordEvent event) { } - protected void handleEvent(LogChannelEvent event) - { + public void handleEvent(JabberEventEvent event) { } - protected void handleEvent(MessageWaitingEvent event) - { + public void handleEvent(JitterBufStatsEvent event) { } - protected void handleEvent(NewExtenEvent event) - { + public void handleEvent(LocalBridgeEvent event) { } - protected void handleEvent(PeerStatusEvent event) - { + public void handleEvent(LocalOptimizationBeginEvent event) { } - protected void handleEvent(ProtocolIdentifierReceivedEvent event) - { + public void handleEvent(LocalOptimizationEndEvent event) { } - protected void handleEvent(QueueEvent event) - { + public void handleEvent(LogChannelEvent event) { } - protected void handleEvent(RegistryEntryEvent event) - { + public void handleEvent(MasqueradeEvent event) { } - protected void handleEvent(RegistryEvent event) - { + public void handleEvent(MeetMeEndEvent event) { } - protected void handleEvent(ReloadEvent event) - { + public void handleEvent(MessageWaitingEvent event) { } - protected void handleEvent(RenameEvent event) - { + public void handleEvent(ModuleLoadReportEvent event) { } - protected void handleEvent(ShutdownEvent event) - { + public void handleEvent(MusicOnHoldEvent event) { } - protected void handleEvent(UserEvent event) - { + public void handleEvent(MusicOnHoldStartEvent event) { } - protected void handleEvent(AgentCompleteEvent event) - { + public void handleEvent(MusicOnHoldStopEvent event) { } - protected void handleEvent(AgentConnectEvent event) - { + public void handleEvent(NewAccountCodeEvent event) { } - protected void handleEvent(AgentDumpEvent event) - { + public void handleEvent(NewConnectedLineEvent event) { } - protected void handleEvent(FaxReceivedEvent event) - { + public void handleEvent(NewExtenEvent event) { } - protected void handleEvent(NewCallerIdEvent event) - { + public void handleEvent(PeerStatusEvent event) { } - protected void handleEvent(HangupEvent event) - { + public void handleEvent(PickupEvent event) { } - protected void handleEvent(NewChannelEvent event) - { + public void handleEvent(PriEventEvent event) { } - protected void handleEvent(NewStateEvent event) - { + public void handleEvent(ProtocolIdentifierReceivedEvent event) { } - protected void handleEvent(MeetMeJoinEvent event) - { + public void handleEvent(QueueEvent event) { } - protected void handleEvent(MeetMeLeaveEvent event) - { + public void handleEvent(JoinEvent event) { } - protected void handleEvent(MeetMeMuteEvent event) - { + public void handleEvent(LeaveEvent event) { } - protected void handleEvent(MeetMeTalkingEvent event) - { + public void handleEvent(QueueCallerAbandonEvent event) { } - protected void handleEvent(ParkedCallGiveUpEvent event) - { + public void handleEvent(QueueCallerJoinEvent event) { } - protected void handleEvent(ParkedCallTimeOutEvent event) - { + public void handleEvent(QueueCallerLeaveEvent event) { } - protected void handleEvent(UnparkedCallEvent event) - { + public void handleEvent(QueueMemberPenaltyEvent event) { } - protected void handleEvent(QueueMemberAddedEvent event) - { + public void handleEvent(ReceiveFaxEvent event) { } - protected void handleEvent(QueueMemberPausedEvent event) - { + public void handleEvent(RegistryEvent event) { } - protected void handleEvent(QueueMemberRemovedEvent event) - { + public void handleEvent(ReloadEvent event) { } - protected void handleEvent(AgentsCompleteEvent event) - { + public void handleEvent(RenameEvent event) { } - protected void handleEvent(AgentsEvent event) - { + public void handleEvent(ResponseEvent event) { } - protected void handleEvent(DbGetResponseEvent event) - { + public void handleEvent(AgentsCompleteEvent event) { } - protected void handleEvent(JoinEvent event) - { + public void handleEvent(AgentsEvent event) { } - protected void handleEvent(LeaveEvent event) - { + public void handleEvent(AsyncAgiEvent event) { } - protected void handleEvent(BridgeEvent event) - { + public void handleEvent(ConfbridgeListCompleteEvent event) { } - protected void handleEvent(OriginateResponseEvent event) - { + public void handleEvent(ConfbridgeListEvent event) { } - protected void handleEvent(ParkedCallEvent event) - { + public void handleEvent(ConfbridgeListRoomsCompleteEvent event) { } - protected void handleEvent(ParkedCallsCompleteEvent event) - { + public void handleEvent(ConfbridgeListRoomsEvent event) { } - protected void handleEvent(PeerEntryEvent event) - { + public void handleEvent(CoreShowChannelEvent event) { } - protected void handleEvent(PeerlistCompleteEvent event) - { + public void handleEvent(CoreShowChannelsCompleteEvent event) { } - protected void handleEvent(QueueEntryEvent event) - { + public void handleEvent(DahdiShowChannelsCompleteEvent event) { } - protected void handleEvent(QueueMemberEvent event) - { + public void handleEvent(DahdiShowChannelsEvent event) { } - protected void handleEvent(QueueMemberStatusEvent event) - { + public void handleEvent(DbGetResponseEvent event) { } - protected void handleEvent(QueueParamsEvent event) - { + public void handleEvent(DongleDeviceEntryEvent event) { } - protected void handleEvent(QueueStatusCompleteEvent event) - { + public void handleEvent(DongleShowDevicesCompleteEvent event) { } - protected void handleEvent(RegistrationsCompleteEvent event) - { + public void handleEvent(EndpointList event) { } - protected void handleEvent(StatusCompleteEvent event) - { + public void handleEvent(EndpointListComplete event) { } - protected void handleEvent(StatusEvent event) - { + public void handleEvent(ListDialplanEvent event) { } - protected void handleEvent(ZapShowChannelsCompleteEvent event) - { + public void handleEvent(OriginateResponseEvent event) { } - protected void handleEvent(ZapShowChannelsEvent event) - { + public void handleEvent(ParkedCallsCompleteEvent event) { } - protected void handleEvent(CoreShowChannelEvent event) - { + public void handleEvent(PeerEntryEvent event) { } - protected void handleEvent(CoreShowChannelsCompleteEvent event) - { + public void handleEvent(PeerlistCompleteEvent event) { + } + + public void handleEvent(PeersEvent event) { + } + + public void handleEvent(QueueEntryEvent event) { + } + + public void handleEvent(QueueMemberEvent event) { + } + + public void handleEvent(QueueParamsEvent event) { + } + + public void handleEvent(QueueStatusCompleteEvent event) { + } + + public void handleEvent(QueueSummaryCompleteEvent event) { + } + + public void handleEvent(QueueSummaryEvent event) { + } + + public void handleEvent(RegistrationsCompleteEvent event) { + } + + public void handleEvent(RegistryEntryEvent event) { + } + + public void handleEvent(ShowDialplanCompleteEvent event) { + } + + public void handleEvent(SkypeBuddyEntryEvent event) { + } + + public void handleEvent(SkypeBuddyListCompleteEvent event) { + } + + public void handleEvent(SkypeLicenseEvent event) { + } + + public void handleEvent(SkypeLicenseListCompleteEvent event) { + } + + public void handleEvent(StatusCompleteEvent event) { + } + + public void handleEvent(StatusEvent event) { + } + + public void handleEvent(VoicemailUserEntryCompleteEvent event) { + } + + public void handleEvent(VoicemailUserEntryEvent event) { + } + + public void handleEvent(ZapShowChannelsCompleteEvent event) { + } + + public void handleEvent(ZapShowChannelsEvent event) { + } + + public void handleEvent(ShutdownEvent event) { + } + + public void handleEvent(SkypeAccountStatusEvent event) { + } + + public void handleEvent(SkypeBuddyStatusEvent event) { + } + + public void handleEvent(SkypeChatMessageEvent event) { + } + + public void handleEvent(SuccessfulAuthEvent event) { + } + + public void handleEvent(AuthMethodNotAllowedEvent event) { + } + + public void handleEvent(FailedACLEvent event) { + } + + public void handleEvent(InvalidTransportEvent event) { + } + + public void handleEvent(LoadAverageLimitEvent event) { + } + + public void handleEvent(MemoryLimitEvent event) { + } + + public void handleEvent(RequestNotAllowedEvent event) { + } + + public void handleEvent(RequestNotSupportedEvent event) { + } + + public void handleEvent(SessionLimitEvent event) { + } + + public void handleEvent(UnexpectedAddressEvent event) { + } + + public void handleEvent(TransferEvent event) { + } + + public void handleEvent(UserEvent event) { + } + + public void handleEvent(PausedEvent event) { + } + + public void handleEvent(UnpausedEvent event) { + } + + public void handleEvent(VarSetEvent event) { + } + + public void handleEvent(EndpointDetail event) { + } + + public void handleEvent(AorDetail event) { + } + + public void handleEvent(ContactStatusDetail event) { + } + + public void handleEvent(EndpointDetailComplete event) { + } + + public void handleEvent(InvalidAccountId event) { } /** * Dispatches to the appropriate handleEvent(...) method. - * + * * @param event the event to handle */ - public void onManagerEvent(ManagerEvent event) - { - if (event instanceof AgentCallbackLoginEvent) - { - handleEvent((AgentCallbackLoginEvent) event); - } - else if (event instanceof AgentCallbackLogoffEvent) - { - handleEvent((AgentCallbackLogoffEvent) event); - } - else if (event instanceof AgentCalledEvent) - { - handleEvent((AgentCalledEvent) event); - } - else if (event instanceof AgentLoginEvent) - { - handleEvent((AgentLoginEvent) event); - } - else if (event instanceof AgentLogoffEvent) - { - handleEvent((AgentLogoffEvent) event); - } - else if (event instanceof AlarmClearEvent) - { - handleEvent((AlarmClearEvent) event); - } - else if (event instanceof AlarmEvent) - { - handleEvent((AlarmEvent) event); - } - else if (event instanceof CdrEvent) - { - handleEvent((CdrEvent) event); - } - else if (event instanceof ConnectEvent) - { - handleEvent((ConnectEvent) event); - } - else if (event instanceof DialEvent) - { - handleEvent((DialEvent) event); - } - else if (event instanceof DisconnectEvent) - { - handleEvent((DisconnectEvent) event); - } - else if (event instanceof DndStateEvent) - { - handleEvent((DndStateEvent) event); - } - else if (event instanceof ExtensionStatusEvent) - { - handleEvent((ExtensionStatusEvent) event); - } - else if (event instanceof HoldedCallEvent) - { - handleEvent((HoldedCallEvent) event); - } - else if (event instanceof HoldEvent) - { - handleEvent((HoldEvent) event); - } - else if (event instanceof LogChannelEvent) - { - handleEvent((LogChannelEvent) event); - } - else if (event instanceof MessageWaitingEvent) - { - handleEvent((MessageWaitingEvent) event); - } - else if (event instanceof NewExtenEvent) - { - handleEvent((NewExtenEvent) event); - } - else if (event instanceof PeerStatusEvent) - { - handleEvent((PeerStatusEvent) event); - } - else if (event instanceof ProtocolIdentifierReceivedEvent) - { - handleEvent((ProtocolIdentifierReceivedEvent) event); - } - else if (event instanceof QueueEvent) - { - handleEvent((QueueEvent) event); - } - else if (event instanceof RegistrationsCompleteEvent) - { - handleEvent((RegistrationsCompleteEvent) event); - } - else if (event instanceof RegistryEntryEvent) - { - handleEvent((RegistryEntryEvent) event); - } - else if (event instanceof RegistryEvent) - { - handleEvent((RegistryEvent) event); - } - else if (event instanceof ReloadEvent) - { - handleEvent((ReloadEvent) event); - } - else if (event instanceof RenameEvent) - { - handleEvent((RenameEvent) event); - } - else if (event instanceof ShutdownEvent) - { - handleEvent((ShutdownEvent) event); - } - else if (event instanceof UserEvent) - { - handleEvent((UserEvent) event); - } - else if (event instanceof AgentCompleteEvent) - { - handleEvent((AgentCompleteEvent) event); - } - else if (event instanceof AgentConnectEvent) - { - handleEvent((AgentConnectEvent) event); - } - else if (event instanceof AgentDumpEvent) - { - handleEvent((AgentDumpEvent) event); - } - else if (event instanceof FaxReceivedEvent) - { - handleEvent((FaxReceivedEvent) event); - } - else if (event instanceof NewCallerIdEvent) - { - handleEvent((NewCallerIdEvent) event); - } - else if (event instanceof HangupEvent) - { - handleEvent((HangupEvent) event); - } - else if (event instanceof NewChannelEvent) - { - handleEvent((NewChannelEvent) event); - } - else if (event instanceof NewStateEvent) - { - handleEvent((NewStateEvent) event); - } - else if (event instanceof MeetMeJoinEvent) - { - handleEvent((MeetMeJoinEvent) event); - } - else if (event instanceof MeetMeLeaveEvent) - { - handleEvent((MeetMeLeaveEvent) event); - } - else if (event instanceof MeetMeMuteEvent) - { - handleEvent((MeetMeMuteEvent) event); - } - else if (event instanceof MeetMeTalkingEvent) - { - handleEvent((MeetMeTalkingEvent) event); - } - else if (event instanceof ParkedCallGiveUpEvent) - { - handleEvent((ParkedCallGiveUpEvent) event); - } - else if (event instanceof ParkedCallTimeOutEvent) - { - handleEvent((ParkedCallTimeOutEvent) event); - } - else if (event instanceof UnparkedCallEvent) - { - handleEvent((UnparkedCallEvent) event); - } - else if (event instanceof QueueMemberAddedEvent) - { - handleEvent((QueueMemberAddedEvent) event); - } - else if (event instanceof QueueMemberPausedEvent) - { - handleEvent((QueueMemberPausedEvent) event); - } - else if (event instanceof QueueMemberRemovedEvent) - { - handleEvent((QueueMemberRemovedEvent) event); - } - else if (event instanceof AgentsCompleteEvent) - { - handleEvent((AgentsCompleteEvent) event); - } - else if (event instanceof AgentsEvent) - { - handleEvent((AgentsEvent) event); - } - else if (event instanceof DbGetResponseEvent) - { - handleEvent((DbGetResponseEvent) event); - } - else if (event instanceof JoinEvent) - { - handleEvent((JoinEvent) event); - } - else if (event instanceof LeaveEvent) - { - handleEvent((LeaveEvent) event); - } - else if (event instanceof BridgeEvent) - { - handleEvent((BridgeEvent) event); - } - else if (event instanceof OriginateResponseEvent) - { - handleEvent((OriginateResponseEvent) event); - } - else if (event instanceof ParkedCallEvent) - { - handleEvent((ParkedCallEvent) event); - } - else if (event instanceof ParkedCallsCompleteEvent) - { - handleEvent((ParkedCallsCompleteEvent) event); - } - else if (event instanceof PeerEntryEvent) - { - handleEvent((PeerEntryEvent) event); - } - else if (event instanceof PeerlistCompleteEvent) - { - handleEvent((PeerlistCompleteEvent) event); - } - else if (event instanceof QueueEntryEvent) - { - handleEvent((QueueEntryEvent) event); - } - else if (event instanceof QueueMemberEvent) - { - handleEvent((QueueMemberEvent) event); - } - else if (event instanceof QueueMemberStatusEvent) - { - handleEvent((QueueMemberStatusEvent) event); - } - else if (event instanceof QueueParamsEvent) - { - handleEvent((QueueParamsEvent) event); - } - else if (event instanceof QueueStatusCompleteEvent) - { - handleEvent((QueueStatusCompleteEvent) event); - } - else if (event instanceof StatusCompleteEvent) - { - handleEvent((StatusCompleteEvent) event); - } - else if (event instanceof StatusEvent) - { - handleEvent((StatusEvent) event); - } - else if (event instanceof ZapShowChannelsCompleteEvent) - { - handleEvent((ZapShowChannelsCompleteEvent) event); - } - else if (event instanceof ZapShowChannelsEvent) - { - handleEvent((ZapShowChannelsEvent) event); - } - else if (event instanceof CoreShowChannelEvent) - { - handleEvent((CoreShowChannelEvent) event); - } - else if (event instanceof CoreShowChannelsCompleteEvent) - { - handleEvent((CoreShowChannelsCompleteEvent) event); - } + @Override + public void onManagerEvent(ManagerEvent event) { + + // if this turns out to be slow, we could consider caching the + // reflection lookup + try { + Method method = this.getClass().getMethod("handleEvent", event.getClass()); + if (method != null) { + method.invoke(this, event); + return; + } + } catch (Exception e) { + LOGGER.error(e, e); + } + + LOGGER.error("The event " + event.getClass() + + " couldn't be mapped to a method in AbstractManagerEventListener.java, someone should add it!"); } } diff --git a/src/main/java/org/asteriskjava/manager/AsteriskMapping.java b/src/main/java/org/asteriskjava/manager/AsteriskMapping.java index 6a93eb393..a1ac701b9 100644 --- a/src/main/java/org/asteriskjava/manager/AsteriskMapping.java +++ b/src/main/java/org/asteriskjava/manager/AsteriskMapping.java @@ -1,22 +1,26 @@ package org.asteriskjava.manager; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; -import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + /** - * Customized the mapping to Asterisk. In general the mapping is done implicitly based - * on reflection but there are certain action that are using headers with specical - * characters that can not be represented in Java. In those cases you can annotate - * the property (getter, setter or field) and provide the header name that Asterisk expects. + * Customize the mapping to Asterisk. In general the mapping is done implicitly + * based on reflection but there are certain actions that use headers with + * characters that are not valid in Java identifiers. In those cases you can + * annotate the property (getter, setter or field) and provide the header name + * that Asterisk sends or expects. + *

      + * Similarly, if an AMI event name contains characters that are not valid Java + * identifiers, the class itself can be decorated with this annotation to + * affect the mapping. * * @since 1.0.0 */ -@Target({METHOD, FIELD}) +@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) -public @interface AsteriskMapping -{ - public abstract String value(); -} \ No newline at end of file +public @interface AsteriskMapping { + String value(); +} diff --git a/src/main/java/org/asteriskjava/manager/AuthenticationFailedException.java b/src/main/java/org/asteriskjava/manager/AuthenticationFailedException.java index f74a5481d..06c71a4f3 100644 --- a/src/main/java/org/asteriskjava/manager/AuthenticationFailedException.java +++ b/src/main/java/org/asteriskjava/manager/AuthenticationFailedException.java @@ -19,12 +19,11 @@ /** * An AuthenticationFailedException is thrown when a login fails due to an incorrect username and/or * password. - * + * * @author srt * @version $Id$ */ -public class AuthenticationFailedException extends Exception -{ +public class AuthenticationFailedException extends Exception { /** * Serializable version identifier */ @@ -32,22 +31,20 @@ public class AuthenticationFailedException extends Exception /** * Creates a new AuthenticationFailedException with the given message. - * + * * @param message message describing the authentication failure */ - public AuthenticationFailedException(final String message) - { + public AuthenticationFailedException(final String message) { super(message); } /** * Creates a new AuthenticationFailedException with the given message and cause. - * + * * @param message message describing the authentication failure - * @param cause exception that caused the authentication failure + * @param cause exception that caused the authentication failure */ - public AuthenticationFailedException(final String message, final Throwable cause) - { + public AuthenticationFailedException(final String message, final Throwable cause) { super(message, cause); } } diff --git a/src/main/java/org/asteriskjava/manager/DefaultManagerConnection.java b/src/main/java/org/asteriskjava/manager/DefaultManagerConnection.java index 5ce6aa949..e7c10501e 100644 --- a/src/main/java/org/asteriskjava/manager/DefaultManagerConnection.java +++ b/src/main/java/org/asteriskjava/manager/DefaultManagerConnection.java @@ -16,15 +16,16 @@ */ package org.asteriskjava.manager; -import java.io.IOException; -import java.net.InetAddress; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.manager.action.EventGeneratingAction; import org.asteriskjava.manager.action.ManagerAction; +import org.asteriskjava.manager.event.ManagerEvent; import org.asteriskjava.manager.internal.ManagerConnectionImpl; import org.asteriskjava.manager.response.ManagerResponse; -import org.asteriskjava.manager.event.ManagerEvent; + +import java.io.IOException; +import java.net.InetAddress; +import java.nio.charset.Charset; /** * Default implemention of the @@ -42,19 +43,17 @@ * data from Asterisk once it is * {@link org.asteriskjava.manager.ManagerConnectionState#CONNECTING}. * - * @see org.asteriskjava.manager.ManagerConnectionFactory * @author srt * @version $Id$ + * @see org.asteriskjava.manager.ManagerConnectionFactory */ -public class DefaultManagerConnection implements ManagerConnection -{ +public class DefaultManagerConnection implements ManagerConnection { private ManagerConnectionImpl impl; /** * Creates a new instance. */ - public DefaultManagerConnection() - { + public DefaultManagerConnection() { this.impl = new ManagerConnectionImpl(); } @@ -66,8 +65,7 @@ public DefaultManagerConnection() * @param username the username to use for login * @param password the password to use for login */ - public DefaultManagerConnection(String hostname, String username, String password) - { + public DefaultManagerConnection(String hostname, String username, String password) { this(); impl.setHostname(hostname); impl.setUsername(username); @@ -78,13 +76,12 @@ public DefaultManagerConnection(String hostname, String username, String passwor * Creates a new instance with the given connection parameters. * * @param hostname the hostname of the Asterisk server to connect to. - * @param port the port where Asterisk listens for incoming Manager API - * connections, usually 5038. + * @param port the port where Asterisk listens for incoming Manager API + * connections, usually 5038. * @param username the username to use for login * @param password the password to use for login */ - public DefaultManagerConnection(String hostname, int port, String username, String password) - { + public DefaultManagerConnection(String hostname, int port, String username, String password) { this(); impl.setHostname(hostname); impl.setPort(port); @@ -99,8 +96,7 @@ public DefaultManagerConnection(String hostname, int port, String username, Stri * * @param hostname the hostname to connect to */ - public void setHostname(String hostname) - { + public void setHostname(String hostname) { impl.setHostname(hostname); } @@ -112,8 +108,7 @@ public void setHostname(String hostname) * * @param port the port to connect to */ - public void setPort(int port) - { + public void setPort(int port) { impl.setPort(port); } @@ -126,8 +121,7 @@ public void setPort(int port) * false for a plain text connection. * @since 0.3 */ - public void setSsl(boolean ssl) - { + public void setSsl(boolean ssl) { impl.setSsl(ssl); } @@ -137,8 +131,7 @@ public void setSsl(boolean ssl) * * @param username the username to use for login */ - public void setUsername(String username) - { + public void setUsername(String username) { impl.setUsername(username); } @@ -148,11 +141,15 @@ public void setUsername(String username) * * @param password the password to use for login */ - public void setPassword(String password) - { + public void setPassword(String password) { impl.setPassword(password); } + @Override + public void setEncoding(Charset encoding) { + impl.setEncoding(encoding); + } + /** * Sets the time in milliseconds the synchronous sendAction methods * {@link #sendAction(ManagerAction)} will wait for a response before @@ -163,8 +160,8 @@ public void setPassword(String password) * @param defaultTimeout default timeout in milliseconds * @deprecated use {@link #setDefaultResponseTimeout(long)} instead */ - @Deprecated public void setDefaultTimeout(long defaultTimeout) - { + @Deprecated + public void setDefaultTimeout(long defaultTimeout) { impl.setDefaultResponseTimeout(defaultTimeout); } @@ -178,8 +175,7 @@ public void setPassword(String password) * @param defaultResponseTimeout default response timeout in milliseconds * @since 0.2 */ - public void setDefaultResponseTimeout(long defaultResponseTimeout) - { + public void setDefaultResponseTimeout(long defaultResponseTimeout) { impl.setDefaultResponseTimeout(defaultResponseTimeout); } @@ -193,8 +189,7 @@ public void setDefaultResponseTimeout(long defaultResponseTimeout) * @param defaultEventTimeout default event timeout in milliseconds * @since 0.2 */ - public void setDefaultEventTimeout(long defaultEventTimeout) - { + public void setDefaultEventTimeout(long defaultEventTimeout) { impl.setDefaultEventTimeout(defaultEventTimeout); } @@ -204,163 +199,154 @@ public void setDefaultEventTimeout(long defaultEventTimeout) * It does nothing. * * @deprecated no longer needed as we now use an interrupt based response - * checking approach. + * checking approach. */ - @Deprecated public void setSleepTime(long sleepTime) - { + @Deprecated + public void setSleepTime(long sleepTime) { } /** - * Set to true to try reconnecting to ther asterisk serve - * even if the reconnection attempt threw an AuthenticationFailedException. + * Set to true to try reconnecting to ther asterisk serve even + * if the reconnection attempt threw an AuthenticationFailedException. *

      * Default is true. */ - public void setKeepAliveAfterAuthenticationFailure(boolean keepAliveAfterAuthenticationFailure) - { + public void setKeepAliveAfterAuthenticationFailure(boolean keepAliveAfterAuthenticationFailure) { impl.setKeepAliveAfterAuthenticationFailure(keepAliveAfterAuthenticationFailure); } /* Implementation of ManagerConnection interface */ - public String getHostname() - { + public String getHostname() { return impl.getHostname(); } - public int getPort() - { + public int getPort() { return impl.getPort(); } - public String getUsername() - { + public String getUsername() { return impl.getUsername(); } - public String getPassword() - { + public String getPassword() { return impl.getPassword(); } - public AsteriskVersion getVersion() - { + @Override + public Charset getEncoding() { + return impl.getEncoding(); + } + + public AsteriskVersion getVersion() { return impl.getVersion(); } - public boolean isSsl() - { + public boolean isSsl() { return impl.isSsl(); } - public InetAddress getLocalAddress() - { + public InetAddress getLocalAddress() { return impl.getLocalAddress(); } - public int getLocalPort() - { + public int getLocalPort() { return impl.getLocalPort(); } - public InetAddress getRemoteAddress() - { + public InetAddress getRemoteAddress() { return impl.getRemoteAddress(); } - public int getRemotePort() - { + public int getRemotePort() { return impl.getRemotePort(); } - public void registerUserEventClass(Class userEventClass) - { + public void registerUserEventClass(Class userEventClass) { impl.registerUserEventClass(userEventClass); } - public void setSocketTimeout(int socketTimeout) - { + public void setSocketTimeout(int socketTimeout) { impl.setSocketTimeout(socketTimeout); } - public void setSocketReadTimeout(int socketReadTimeout) - { + public void setSocketReadTimeout(int socketReadTimeout) { impl.setSocketReadTimeout(socketReadTimeout); } - public void login() throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException - { + public void login() throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException { impl.login(); } - public void login(String events) throws IllegalStateException, IOException, AuthenticationFailedException, - TimeoutException - { + public void login(String events) + throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException { impl.login(events); } - public void logoff() throws IllegalStateException - { + public void logoff() throws IllegalStateException { impl.logoff(); } - public ManagerResponse sendAction(ManagerAction action) throws IOException, TimeoutException, IllegalArgumentException, - IllegalStateException - { + public ManagerResponse sendAction(ManagerAction action) + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { return impl.sendAction(action); } - public ManagerResponse sendAction(ManagerAction action, long timeout) throws IOException, TimeoutException, - IllegalArgumentException, IllegalStateException - { + public ManagerResponse sendAction(ManagerAction action, long timeout) + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { return impl.sendAction(action, timeout); } - public void sendAction(ManagerAction action, SendActionCallback callbackHandler) throws IOException, - IllegalArgumentException, IllegalStateException - { + public void sendAction(ManagerAction action, SendActionCallback callbackHandler) + throws IOException, IllegalArgumentException, IllegalStateException { impl.sendAction(action, callbackHandler); } - public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) throws IOException, EventTimeoutException, - IllegalArgumentException, IllegalStateException - { + public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) + throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException { return impl.sendEventGeneratingAction(action); } - public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) throws IOException, - EventTimeoutException, IllegalArgumentException, IllegalStateException - { + public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) + throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException { return impl.sendEventGeneratingAction(action, timeout); } - public void addEventListener(final ManagerEventListener listener) - { + @Override + public void sendEventGeneratingAction(EventGeneratingAction action, + SendEventGeneratingActionCallback callback) + throws IOException, IllegalArgumentException, IllegalStateException { + impl.sendEventGeneratingAction(action, callback); + } + + public void addEventListener(final ManagerEventListener listener) { impl.addEventListener(listener); } - public void removeEventListener(final ManagerEventListener listener) - { + public void removeEventListener(final ManagerEventListener listener) { impl.removeEventListener(listener); } - public String getProtocolIdentifier() - { + public String getProtocolIdentifier() { return impl.getProtocolIdentifier(); } - public ManagerConnectionState getState() - { + public ManagerConnectionState getState() { return impl.getState(); } @Override - public String toString() - { + public String toString() { final StringBuilder sb = new StringBuilder("DefaultManagerConnection["); sb.append("hostname='").append(getHostname()).append("',"); sb.append("port=").append(getPort()).append("]"); return sb.toString(); } + + @Override + public void deregisterEventClass(Class eventClass) { + impl.deregisterEventClass(eventClass); + + } } diff --git a/src/main/java/org/asteriskjava/manager/EventTimeoutException.java b/src/main/java/org/asteriskjava/manager/EventTimeoutException.java index 8da0c19e7..5142b9cc2 100644 --- a/src/main/java/org/asteriskjava/manager/EventTimeoutException.java +++ b/src/main/java/org/asteriskjava/manager/EventTimeoutException.java @@ -21,13 +21,12 @@ * ResponseEvents are not completely received within the expected time period.

      * This exception allows you to retrieve the partial result, that is the events * that have been successfully received before the timeout occured. - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class EventTimeoutException extends TimeoutException -{ +public class EventTimeoutException extends TimeoutException { /** * Serial version identifier. */ @@ -37,13 +36,12 @@ public class EventTimeoutException extends TimeoutException /** * Creates a new EventTimeoutException with the given message and partial * result. - * - * @param message message with details about the timeout. + * + * @param message message with details about the timeout. * @param partialResult the ResponseEvents object filled with the parts that - * have been received before the timeout occured. + * have been received before the timeout occured. */ - public EventTimeoutException(String message, ResponseEvents partialResult) - { + public EventTimeoutException(String message, ResponseEvents partialResult) { super(message); this.partialResult = partialResult; } @@ -55,13 +53,12 @@ public EventTimeoutException(String message, ResponseEvents partialResult) * wherever possible. This is only a hack to handle those versions of * Asterisk that don't follow the Manager API conventions, for example by * not sending the correct ActionCompleteEvent. - * + * * @return the ResponseEvents object filled with the parts that have been - * received before the timeout occured. Note: The response attribute - * may be null when no response has been received. + * received before the timeout occured. Note: The response attribute + * may be null when no response has been received. */ - public ResponseEvents getPartialResult() - { + public ResponseEvents getPartialResult() { return partialResult; } } diff --git a/src/main/java/org/asteriskjava/manager/ExpectedResponse.java b/src/main/java/org/asteriskjava/manager/ExpectedResponse.java index ae6302bda..da5c836c6 100644 --- a/src/main/java/org/asteriskjava/manager/ExpectedResponse.java +++ b/src/main/java/org/asteriskjava/manager/ExpectedResponse.java @@ -2,11 +2,12 @@ import org.asteriskjava.manager.response.ManagerResponse; -import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; -import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + /** * Indicates that an annotated {@link org.asteriskjava.manager.action.ManagerAction} expects * a specific subclass of {@link org.asteriskjava.manager.response.ManagerResponse} when executed @@ -16,7 +17,6 @@ */ @Target(TYPE) @Retention(RUNTIME) -public @interface ExpectedResponse -{ +public @interface ExpectedResponse { Class value(); } diff --git a/src/main/java/org/asteriskjava/manager/ManagerConnection.java b/src/main/java/org/asteriskjava/manager/ManagerConnection.java index f69471f3a..1fdbc8e42 100644 --- a/src/main/java/org/asteriskjava/manager/ManagerConnection.java +++ b/src/main/java/org/asteriskjava/manager/ManagerConnection.java @@ -16,22 +16,23 @@ */ package org.asteriskjava.manager; -import java.io.IOException; -import java.net.InetAddress; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.manager.action.EventGeneratingAction; import org.asteriskjava.manager.action.ManagerAction; import org.asteriskjava.manager.event.ManagerEvent; import org.asteriskjava.manager.response.ManagerResponse; +import java.io.IOException; +import java.net.InetAddress; +import java.nio.charset.Charset; + /** * The main interface to talk to an Asterisk server via the Asterisk Manager * API. *

      * The ManagerConnection repesents a connection to an Asterisk server and is - * capable of sending {@link org.asteriskjava.manager.action.ManagerAction}s - * and receiving {@link org.asteriskjava.manager.response.ManagerResponse}s and + * capable of sending {@link org.asteriskjava.manager.action.ManagerAction}s and + * receiving {@link org.asteriskjava.manager.response.ManagerResponse}s and * {@link org.asteriskjava.manager.event.ManagerEvent}s. It does not add any * further functionality but rather provides a Java view to Asterisk's Manager * API (freeing you from TCP/IP connection and parsing stuff). @@ -42,12 +43,11 @@ * A concrete implementation of this interface can be obtained from a * {@link org.asteriskjava.manager.ManagerConnectionFactory}. * - * @see org.asteriskjava.manager.ManagerConnectionFactory * @author srt * @version $Id$ + * @see org.asteriskjava.manager.ManagerConnectionFactory */ -public interface ManagerConnection -{ +public interface ManagerConnection { /** * Returns the hostname of the connected Asterisk server. * @@ -90,13 +90,31 @@ public interface ManagerConnection */ AsteriskVersion getVersion(); + /** + * Sets the encoding to use to connect to the Asterisk server (eg. important + * for manager/user events). All connections should use the same encoding. + * The default is UTF-8. + * + * @param encoding the encoding to use for manager/user events etc. + */ + void setEncoding(Charset encoding); + + /** + * Returns the encoding to use to connect to the Asterisk server (eg. + * important for manager/user events). All connections should use the same + * encoding. The default is UTF-8. + * + * @return the encoding to use for manager/user events etc. + */ + Charset getEncoding(); + /** * Returns whether to use SSL. *

      * Default is false. * * @return true if SSL is used for the connection, - * false for a plain text connection. + * false for a plain text connection. * @since 0.3 */ boolean isSsl(); @@ -144,16 +162,16 @@ public interface ManagerConnection * registered event handlers. *

      * Note: If you write your own Asterisk applications that use Asterisk's - * manager_event() function directly and don't use the - * channel and uniqueid attributes provided by UserEvent you can also - * register events that directly subclass {@link ManagerEvent}. + * manager_event() function directly and don't use the channel + * and uniqueid attributes provided by UserEvent you can also register + * events that directly subclass {@link ManagerEvent}. *

      * The event class must be a concrete class with a default constructor (one * that takes no arguments). - * + * * @param userEventClass the class representing the user event to register. * @throws IllegalArgumentException if userEventClass is not a valid event - * class. + * class. * @see org.asteriskjava.manager.event.UserEvent * @see ManagerEvent */ @@ -163,12 +181,12 @@ public interface ManagerConnection * The timeout to use when connecting the the Asterisk server. *

      * Default is 0, that is using Java's built-in default. - * + * * @param socketTimeout the timeout value to be used in milliseconds. * @see java.net.Socket#connect(java.net.SocketAddress, int) * @since 0.2 */ - public void setSocketTimeout(int socketTimeout); + void setSocketTimeout(int socketTimeout); /** * Connection is dropped (and restarted) if it stales on read longer than @@ -181,25 +199,36 @@ public interface ManagerConnection * PingThread. *

      * Default is 0, that is no read timeout. - * + * * @param socketReadTimeout the read timeout value to be used in - * milliseconds. + * milliseconds. * @see java.net.Socket#setSoTimeout(int) * @since 0.3 */ void setSocketReadTimeout(int socketReadTimeout); + /** + * Set to true to try reconnecting to ther asterisk serve even + * if the reconnection attempt threw an AuthenticationFailedException.
      + * Default is true. + * + * @param keepAliveAfterAuthenticationFailure true to try + * reconnecting to ther asterisk serve even if the reconnection attempt + * threw an AuthenticationFailedException, false otherwise. + */ + void setKeepAliveAfterAuthenticationFailure(boolean keepAliveAfterAuthenticationFailure); + /** * Logs in to the Asterisk server with the username and password specified * when this connection was created. - * - * @throws IllegalStateException if connection is not in state INITIAL or - * DISCONNECTED. - * @throws IOException if the network connection is disrupted. + * + * @throws IllegalStateException if connection is not in state INITIAL or + * DISCONNECTED. + * @throws IOException if the network connection is disrupted. * @throws AuthenticationFailedException if the username and/or password are - * incorrect or the ChallengeResponse could not be built. - * @throws TimeoutException if a timeout occurs while waiting for the - * protocol identifier. The connection is closed in this case. + * incorrect or the ChallengeResponse could not be built. + * @throws TimeoutException if a timeout occurs while waiting for the + * protocol identifier. The connection is closed in this case. * @see org.asteriskjava.manager.action.LoginAction * @see org.asteriskjava.manager.action.ChallengeAction */ @@ -208,27 +237,27 @@ public interface ManagerConnection /** * Logs in to the Asterisk server with the username and password specified * when this connection was created and a given event mask. - * + * * @param events the event mask. Set to "on" if all events should be send, - * "off" if not events should be sent or a combination of - * "system", "call" and "log" (separated by ',') to specify what - * kind of events should be sent. - * @throws IllegalStateException if connection is not in state INITIAL or - * DISCONNECTED. - * @throws IOException if the network connection is disrupted. + * "off" if not events should be sent or a combination of + * "system", "call" and "log" (separated by ',') to specify what + * kind of events should be sent. + * @throws IllegalStateException if connection is not in state INITIAL or + * DISCONNECTED. + * @throws IOException if the network connection is disrupted. * @throws AuthenticationFailedException if the username and/or password are - * incorrect or the ChallengeResponse could not be built. - * @throws TimeoutException if a timeout occurs while waiting for the - * protocol identifier. The connection is closed in this case. - * @since 0.3 + * incorrect or the ChallengeResponse could not be built. + * @throws TimeoutException if a timeout occurs while waiting for the + * protocol identifier. The connection is closed in this case. * @see org.asteriskjava.manager.action.LoginAction * @see org.asteriskjava.manager.action.ChallengeAction + * @since 0.3 */ void login(String events) throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException; /** * Sends a LogoffAction to the Asterisk server and disconnects. - * + * * @throws IllegalStateException if not in state CONNECTED or RECONNECTING. * @see org.asteriskjava.manager.action.LogoffAction */ @@ -237,15 +266,15 @@ public interface ManagerConnection /** * Returns the protocol identifier, that is a string like "Asterisk Call * Manager/1.0". - * + * * @return the protocol identifier of the Asterisk Manager Interface in use - * if it has already been received; null otherwise + * if it has already been received; null otherwise */ String getProtocolIdentifier(); /** * Returns the lifecycle status of this connection. - * + * * @return the lifecycle status of this connection. */ ManagerConnectionState getState(); @@ -253,39 +282,39 @@ public interface ManagerConnection /** * Sends a ManagerAction to the Asterisk server and waits for the * corresponding ManagerResponse. - * + * * @param action the action to send to the Asterisk server * @return the corresponding response received from the Asterisk server - * @throws IOException if the network connection is disrupted. - * @throws TimeoutException if no response is received within the default - * timeout period. + * @throws IOException if the network connection is disrupted. + * @throws TimeoutException if no response is received within the default + * timeout period. * @throws IllegalArgumentException if the action is null. - * @throws IllegalStateException if you are not connected to an Asterisk - * server. + * @throws IllegalStateException if you are not connected to an Asterisk + * server. * @see #sendAction(ManagerAction, long) * @see #sendAction(ManagerAction, SendActionCallback) */ - ManagerResponse sendAction(ManagerAction action) throws IOException, TimeoutException, IllegalArgumentException, - IllegalStateException; + ManagerResponse sendAction(ManagerAction action) + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException; /** * Sends a ManagerAction to the Asterisk server and waits for the * corresponding {@link ManagerResponse}. - * - * @param action the action to send to the Asterisk server + * + * @param action the action to send to the Asterisk server * @param timeout milliseconds to wait for the response before throwing a - * TimeoutException + * TimeoutException * @return the corresponding response received from the Asterisk server - * @throws IOException if the network connection is disrupted. - * @throws TimeoutException if no response is received within the given - * timeout period. + * @throws IOException if the network connection is disrupted. + * @throws TimeoutException if no response is received within the given + * timeout period. * @throws IllegalArgumentException if the action is null. - * @throws IllegalStateException if you are not connected to an Asterisk - * server. + * @throws IllegalStateException if you are not connected to an Asterisk + * server. * @see #sendAction(ManagerAction, SendActionCallback) */ - ManagerResponse sendAction(ManagerAction action, long timeout) throws IOException, TimeoutException, - IllegalArgumentException, IllegalStateException; + ManagerResponse sendAction(ManagerAction action, long timeout) + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException; /** * Sends a ManagerAction to the Asterisk server and registers a callback @@ -294,27 +323,27 @@ ManagerResponse sendAction(ManagerAction action, long timeout) throws IOExceptio * quickly and does not do any fancy processing because it is called from * the reader thread which is blocked for the time it takes to execute your * callbackHandler. - * - * @param action the action to send to the Asterisk server + * + * @param action the action to send to the Asterisk server * @param callback the callback handler to call when the response is - * received or null if you are not interested in - * the response - * @throws IOException if the network connection is disrupted. + * received or null if you are not interested in the + * response + * @throws IOException if the network connection is disrupted. * @throws IllegalArgumentException if the action is null. - * @throws IllegalStateException if you are not connected to the Asterisk - * server. + * @throws IllegalStateException if you are not connected to the Asterisk + * server. */ - void sendAction(ManagerAction action, SendActionCallback callback) throws IOException, IllegalArgumentException, - IllegalStateException; + void sendAction(ManagerAction action, SendActionCallback callback) + throws IOException, IllegalArgumentException, IllegalStateException; /** * Sends an {@link EventGeneratingAction} to the Asterisk server and waits * for the corresponding {@link ManagerResponse} and the * {@link org.asteriskjava.manager.event.ResponseEvent}s *

      - * EventGeneratingActions are {@link ManagerAction}s that don't return - * their response in the corresponding {@link ManagerResponse} but send a - * series of events that contain the payload. + * EventGeneratingActions are {@link ManagerAction}s that don't return their + * response in the corresponding {@link ManagerResponse} but send a series + * of events that contain the payload. *

      * This method will block until the correpsonding action complete event has * been received. The action complete event is determined by @@ -324,34 +353,34 @@ void sendAction(ManagerAction action, SendActionCallback callback) throws IOExce * {@link org.asteriskjava.manager.action.StatusAction}, * {@link org.asteriskjava.manager.action.QueueStatusAction} or * {@link org.asteriskjava.manager.action.AgentsAction}. - * + * * @param action the action to send to the Asterisk server * @return a ResponseEvents that contains the corresponding response and - * response events received from the Asterisk server - * @throws IOException if the network connection is disrupted. - * @throws EventTimeoutException if no response or not all response events - * are received within the given timeout period. - * @throws IllegalArgumentException if the action is null, - * the actionCompleteEventClass property of the action is - * null or if actionCompleteEventClass is not a - * ResponseEvent. - * @throws IllegalStateException if you are not connected to an Asterisk - * server. + * response events received from the Asterisk server + * @throws IOException if the network connection is disrupted. + * @throws EventTimeoutException if no response or not all response events + * are received within the given timeout period. + * @throws IllegalArgumentException if the action is null, the + * actionCompleteEventClass property of the action is + * null or if actionCompleteEventClass is not a + * ResponseEvent. + * @throws IllegalStateException if you are not connected to an Asterisk + * server. * @see EventGeneratingAction * @see org.asteriskjava.manager.event.ResponseEvent * @since 0.2 */ - ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) throws IOException, EventTimeoutException, - IllegalArgumentException, IllegalStateException; + ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) + throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException; /** * Sends an {@link EventGeneratingAction} to the Asterisk server and waits * for the corresponding {@link ManagerResponse} and the * {@link org.asteriskjava.manager.event.ResponseEvent}s *

      - * EventGeneratingActions are {@link ManagerAction}s that don't return - * their response in the corresponding {@link ManagerResponse} but send a - * series of events that contain the payload. + * EventGeneratingActions are {@link ManagerAction}s that don't return their + * response in the corresponding {@link ManagerResponse} but send a series + * of events that contain the payload. *

      * This method will block until the correpsonding action complete event has * been received but no longer that timeout seconds. The action complete @@ -362,27 +391,42 @@ ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) throws IO * {@link org.asteriskjava.manager.action.StatusAction}, the * {@link org.asteriskjava.manager.action.QueueStatusAction} or the * {@link org.asteriskjava.manager.action.AgentsAction}. - * - * @param action the action to send to the Asterisk server + * + * @param action the action to send to the Asterisk server * @param timeout milliseconds to wait for the response and the action - * complete event before throwing a TimeoutException + * complete event before throwing a TimeoutException * @return a ResponseEvents that contains the corresponding response and - * response events received from the Asterisk server - * @throws IOException if the network connection is disrupted. - * @throws EventTimeoutException if no response or not all response events - * are received within the given timeout period. - * @throws IllegalArgumentException if the action is null, - * the actionCompleteEventClass property of the action is - * null or if actionCompleteEventClass is not a - * ResponseEvent. - * @throws IllegalStateException if you are not connected to an Asterisk - * server. + * response events received from the Asterisk server + * @throws IOException if the network connection is disrupted. + * @throws EventTimeoutException if no response or not all response events + * are received within the given timeout period. + * @throws IllegalArgumentException if the action is null, the + * actionCompleteEventClass property of the action is + * null or if actionCompleteEventClass is not a + * ResponseEvent. + * @throws IllegalStateException if you are not connected to an Asterisk + * server. * @see EventGeneratingAction * @see org.asteriskjava.manager.event.ResponseEvent * @since 0.2 */ - ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) throws IOException, - EventTimeoutException, IllegalArgumentException, IllegalStateException; + ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) + throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException; + + /** + * Asynchronously sends an {@link EventGeneratingAction} to the Asterisk + * server. This is similar to + * {@link #sendEventGeneratingAction(EventGeneratingAction, long)} except it + * does NOT block to wait for the completion. Instead after the action + * completes or fails the result is provided to the optional callback via + * {@link SendEventGeneratingActionCallback#onResponse(ResponseEvents)}. + * + * @see #sendEventGeneratingAction(EventGeneratingAction, long) + */ + void sendEventGeneratingAction( + EventGeneratingAction action, + SendEventGeneratingActionCallback callback) + throws IOException, IllegalArgumentException, IllegalStateException; /** * Registers an event listener that is called whenever an @@ -391,9 +435,9 @@ ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long time *

      * Event listeners are notified about new events in the same order as they * were registered. - * + * * @param eventListener the listener to call whenever a manager event is - * received + * received * @see #removeEventListener(ManagerEventListener) */ void addEventListener(ManagerEventListener eventListener); @@ -402,9 +446,11 @@ ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long time * Unregisters a previously registered event listener. *

      * Does nothing if the given event listener hasn't be been regiered before. - * + * * @param eventListener the listener to remove * @see #addEventListener(ManagerEventListener) */ void removeEventListener(ManagerEventListener eventListener); + + void deregisterEventClass(Class eventClass); } diff --git a/src/main/java/org/asteriskjava/manager/ManagerConnectionFactory.java b/src/main/java/org/asteriskjava/manager/ManagerConnectionFactory.java index 7672b35df..9417c96bd 100644 --- a/src/main/java/org/asteriskjava/manager/ManagerConnectionFactory.java +++ b/src/main/java/org/asteriskjava/manager/ManagerConnectionFactory.java @@ -17,11 +17,11 @@ package org.asteriskjava.manager; /** - * This factory is the canonical way to obtain new + * This factory is the canonical way to obtain new * {@link org.asteriskjava.manager.ManagerConnection}s.

      - * It creates new connections in state + * It creates new connections in state * {@link org.asteriskjava.manager.ManagerConnectionState#INITIAL}. Before - * you can start using such a connection (i.e. sending + * you can start using such a connection (i.e. sending * {@link org.asteriskjava.manager.action.ManagerAction}s you must * {@link org.asteriskjava.manager.ManagerConnection#login()} to change its state * to {@link org.asteriskjava.manager.ManagerConnectionState#CONNECTED}.

      @@ -29,7 +29,7 @@ *

        * ManagerConnectionFactory factory;
        * ManagerConnection connection;
      - * 
      + *
        * factory = new ManagerConnectionFactory("localhost", "manager", "secret");
        * connection = factory.createManagerConnection();
        * connection.login();
      @@ -38,13 +38,12 @@
        * 
      * If want you can use the factory to create multiple connections to the same * server by calling {@link #createManagerConnection()} multiple times.

      - * - * @see org.asteriskjava.manager.ManagerConnection + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.ManagerConnection */ -public class ManagerConnectionFactory -{ +public class ManagerConnectionFactory { private static final int DEFAULT_PORT = 5038; private final String hostname; @@ -55,14 +54,13 @@ public class ManagerConnectionFactory /** * Creates a new ManagerConnectionFactory with the given connection data and * the default port 5038. - * + * * @param hostname the hostname of the Asterisk server to connect to. * @param username the username to use for login as defined in Asterisk's manager.conf. * @param password the password to use for login as defined in Asterisk's manager.conf. * @since 0.3 */ - public ManagerConnectionFactory(String hostname, String username, String password) - { + public ManagerConnectionFactory(String hostname, String username, String password) { this.hostname = hostname; this.port = DEFAULT_PORT; this.username = username; @@ -71,16 +69,15 @@ public ManagerConnectionFactory(String hostname, String username, String passwor /** * Creates a new ManagerConnectionFactory with the given connection data. - * + * * @param hostname the hostname of the Asterisk server to connect to. - * @param port the port where Asterisk listens for incoming Manager API - * connections, usually 5038. + * @param port the port where Asterisk listens for incoming Manager API + * connections, usually 5038. * @param username the username to use for login as defined in Asterisk's manager.conf. * @param password the password to use for login as defined in Asterisk's manager.conf. * @since 0.3 */ - public ManagerConnectionFactory(String hostname, int port, String username, String password) - { + public ManagerConnectionFactory(String hostname, int port, String username, String password) { this.hostname = hostname; this.port = port; this.username = username; @@ -89,23 +86,21 @@ public ManagerConnectionFactory(String hostname, int port, String username, Stri /** * Returns a new ManagerConnection in state {@link ManagerConnectionState#CONNECTED}. - * + * * @return the created connection to the Asterisk server. * @since 0.3 */ - public ManagerConnection createManagerConnection() - { + public ManagerConnection createManagerConnection() { return new DefaultManagerConnection(hostname, port, username, password); } /** * Returns a new SSL secured ManagerConnection in state {@link ManagerConnectionState#CONNECTED}. - * + * * @return the created connection to the Asterisk server. * @since 0.3 */ - public ManagerConnection createSecureManagerConnection() - { + public ManagerConnection createSecureManagerConnection() { DefaultManagerConnection dmc; dmc = new DefaultManagerConnection(hostname, port, username, password); dmc.setSsl(true); diff --git a/src/main/java/org/asteriskjava/manager/ManagerConnectionState.java b/src/main/java/org/asteriskjava/manager/ManagerConnectionState.java index 4ec1209ad..ea058e109 100644 --- a/src/main/java/org/asteriskjava/manager/ManagerConnectionState.java +++ b/src/main/java/org/asteriskjava/manager/ManagerConnectionState.java @@ -2,12 +2,11 @@ /** * The lifecycle status of a {@link org.asteriskjava.manager.ManagerConnection}. - * + * * @author srt * @since 0.3 */ -public enum ManagerConnectionState -{ +public enum ManagerConnectionState { /** * The initial state after the ManagerConnection object has been created * but the connection has not yet been established.

      @@ -15,14 +14,14 @@ public enum ManagerConnectionState * is called. */ INITIAL, - + /** * The connection is being made and login is performed.

      * Changes to {@link #CONNECTED} when login has successfully completed or - * {@link #DISCONNECTED} if login fails. + * {@link #DISCONNECTED} if login fails. */ CONNECTING, - + /** * The connection has been successfully established, login has been perfomed and * the connection is ready to be used.

      @@ -31,7 +30,7 @@ public enum ManagerConnectionState * when {@link org.asteriskjava.manager.ManagerConnection#logoff()} is called. */ CONNECTED, - + /** * The connection has been disrupted and is about to be reestablished.

      * Changes to {@link #CONNECTED} when connection is successfully reestablished or @@ -39,16 +38,16 @@ public enum ManagerConnectionState * is called. */ RECONNECTING, - + /** * The connection is about to be closed by user request.

      * Changes to {@link #DISCONNECTED} when connection has been closed. */ DISCONNECTING, - + /** * The connection has been closed on user's request is not about to be reestablished.

      - * Can be changed to {@link #CONNECTING} by calling + * Can be changed to {@link #CONNECTING} by calling * {@link org.asteriskjava.manager.ManagerConnection#login()}. */ DISCONNECTED diff --git a/src/main/java/org/asteriskjava/manager/ManagerEventListener.java b/src/main/java/org/asteriskjava/manager/ManagerEventListener.java index 33ac2f9a6..bc829999e 100644 --- a/src/main/java/org/asteriskjava/manager/ManagerEventListener.java +++ b/src/main/java/org/asteriskjava/manager/ManagerEventListener.java @@ -16,23 +16,22 @@ */ package org.asteriskjava.manager; -import java.util.EventListener; - import org.asteriskjava.manager.event.ManagerEvent; +import java.util.EventListener; + /** * An interface to listen for events received from an Asterisk server. - * - * @see org.asteriskjava.manager.event.ManagerEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.ManagerEvent */ -public interface ManagerEventListener extends EventListener -{ +public interface ManagerEventListener extends EventListener { /** * This method is called when an event is received. - * + * * @param event the event that has been received */ void onManagerEvent(ManagerEvent event); diff --git a/src/main/java/org/asteriskjava/manager/ManagerEventListenerProxy.java b/src/main/java/org/asteriskjava/manager/ManagerEventListenerProxy.java index b7d39b7a6..12050c8e8 100644 --- a/src/main/java/org/asteriskjava/manager/ManagerEventListenerProxy.java +++ b/src/main/java/org/asteriskjava/manager/ManagerEventListenerProxy.java @@ -1,11 +1,10 @@ package org.asteriskjava.manager; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import org.asteriskjava.manager.event.ManagerEvent; import org.asteriskjava.util.DaemonThreadFactory; +import java.util.concurrent.*; + /** * Proxies a ManagerEventListener and dispatches events asynchronously by using * a single threaded executor.

      @@ -24,64 +23,54 @@ * ... * connection.addEventListener(new ManagerEventListenerProxy(myListener)); * - * + * * @author srt + * @author fink * @since 0.3 - * @version $Id$ */ -public class ManagerEventListenerProxy implements ManagerEventListener -{ - private final ExecutorService executor; - private ManagerEventListener target; +public class ManagerEventListenerProxy implements ManagerEventListener { + private final ThreadPoolExecutor executor; + private final ManagerEventListener target; - /** - * Creates a new ManagerEventListenerProxy.

      - * You must set the target by calling {@link #setTarget(ManagerEventListener)}. - */ - public ManagerEventListenerProxy() - { - this.executor = Executors.newSingleThreadExecutor(new DaemonThreadFactory()); - } /** * Creates a new ManagerEventListenerProxy that notifies the given target * asynchronously when new events are received. - * + * * @param target the target listener to invoke. + * @see Executors#newSingleThreadExecutor(ThreadFactory) */ - public ManagerEventListenerProxy(ManagerEventListener target) - { - this(); + public ManagerEventListenerProxy(ManagerEventListener target) { + executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new DaemonThreadFactory()); this.target = target; - } + if (target == null) { + throw new NullPointerException("ManagerEventListener target is null!"); + } + }//new + + + @Override + public void onManagerEvent(final ManagerEvent event) { + executor.execute(new Runnable() { + @Override + public void run() { + target.onManagerEvent(event); + } + }); + }//onManagerEvent - /** - * Sets the target listener that is notified asynchronously when new events - * are received. - * c - * @param target the target listener to invoke. - */ - public synchronized void setTarget(ManagerEventListener target) - { - this.target = target; - } - public synchronized void onManagerEvent(final ManagerEvent event) - { - if (target != null) - { - executor.execute(new Runnable() - { - public void run() - { - target.onManagerEvent(event); - } - }); - } - } - public void shutdown() { - executor.shutdown(); } + + public static class Access { + private Access() { + + } + + public static int getThreadQueueSize(ManagerEventListenerProxy proxy) { + return proxy.executor.getQueue().size(); + } + }//Access } diff --git a/src/main/java/org/asteriskjava/manager/PingThread.java b/src/main/java/org/asteriskjava/manager/PingThread.java index c30173709..862f882be 100644 --- a/src/main/java/org/asteriskjava/manager/PingThread.java +++ b/src/main/java/org/asteriskjava/manager/PingThread.java @@ -16,28 +16,27 @@ */ package org.asteriskjava.manager; -import java.util.concurrent.atomic.AtomicLong; -import java.util.Set; -import java.util.HashSet; - +import org.asteriskjava.lock.LockableSet; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.action.PingAction; import org.asteriskjava.manager.response.ManagerResponse; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +import java.util.HashSet; +import java.util.concurrent.atomic.AtomicLong; + /** - * A Thread that pings the Asterisk server at a given interval. - * You can use this to prevent the connection being shut down when there is no - * traffic. + * A Thread that pings the Asterisk server at a given interval. You can use this + * to prevent the connection being shut down when there is no traffic. *

      * Since 1.0.0 PingThread supports mutliple connections so do don't have to - * start multiple threads to keep several connections alive. + * start multiple threads to keep several connections alive. * * @author srt * @version $Id$ */ -public class PingThread extends Thread -{ +public class PingThread extends Thread { private static final long DEFAULT_INTERVAL = 20 * 1000L; private static final long DEFAULT_TIMEOUT = 0L; private static final AtomicLong idCounter = new AtomicLong(0); @@ -50,18 +49,17 @@ public class PingThread extends Thread private long interval = DEFAULT_INTERVAL; private long timeout = DEFAULT_TIMEOUT; private volatile boolean die; - private final Set connections; + private final LockableSet connections; /** - * Creates a new PingThread. Use {@link #addConnection(ManagerConnection)} to add connections - * that will be pinged. + * Creates a new PingThread. Use {@link #addConnection(ManagerConnection)} + * to add connections that will be pinged. * * @since 1.0.0 */ - public PingThread() - { + public PingThread() { super(); - this.connections = new HashSet(); + this.connections = new LockableSet<>(new HashSet<>()); this.die = false; long id = idCounter.getAndIncrement(); setName("Asterisk-Java Ping-" + id); @@ -73,38 +71,32 @@ public PingThread() * * @param connection ManagerConnection that is pinged */ - public PingThread(ManagerConnection connection) - { + public PingThread(ManagerConnection connection) { this(); this.connections.add(connection); } /** - * Adjusts how often a PingAction is sent. - *

      + * Adjusts how often a PingAction is sent.
      * Default is 20000ms, i.e. 20 seconds. * * @param interval the interval in milliseconds */ - public void setInterval(long interval) - { + public void setInterval(long interval) { this.interval = interval; } /** * Sets the timeout to wait for the ManagerResponse before throwing an - * excpetion. - *

      + * excpetion.
      * If set to 0 the response will be ignored an no exception will be thrown - * at all. - *

      + * at all.
      * Default is 0. * * @param timeout the timeout in milliseconds or 0 to indicate no timeout. * @since 0.3 */ - public void setTimeout(long timeout) - { + public void setTimeout(long timeout) { this.timeout = timeout; } @@ -114,10 +106,8 @@ public void setTimeout(long timeout) * @param connection the connection to ping. * @since 1.0.0 */ - public void addConnection(ManagerConnection connection) - { - synchronized (connections) - { + public void addConnection(ManagerConnection connection) { + try (LockCloser closer = connections.withLock()) { connections.add(connection); } } @@ -128,10 +118,8 @@ public void addConnection(ManagerConnection connection) * @param connection the connection that will no longer be pinged. * @since 1.0.0 */ - public void removeConnection(ManagerConnection connection) - { - synchronized (connections) - { + public void removeConnection(ManagerConnection connection) { + try (LockCloser closer = connections.withLock()) { connections.remove(connection); } } @@ -139,39 +127,30 @@ public void removeConnection(ManagerConnection connection) /** * Terminates this PingThread. */ - public void die() - { + public void die() { this.die = true; interrupt(); } @Override - public void run() - { - while (!die) - { - try - { + public void run() { + while (!die) { + try { sleep(interval); - } - catch (InterruptedException e) // NOPMD + } catch (InterruptedException e) // NOPMD { Thread.currentThread().interrupt(); } // exit if die is set - if (die) - { + if (die) { break; } - synchronized (connections) - { - for (ManagerConnection c : connections) - { + try (LockCloser closer = connections.withLock()) { + for (ManagerConnection c : connections) { // skip if not connected - if (c.getState() != ManagerConnectionState.CONNECTED) - { + if (c.getState() != ManagerConnectionState.CONNECTED) { continue; } @@ -186,24 +165,17 @@ public void run() * * @param c the connection to ping. */ - protected void ping(ManagerConnection c) - { - try - { - if (timeout <= 0) - { + protected void ping(ManagerConnection c) { + try { + if (timeout <= 0) { c.sendAction(new PingAction(), null); - } - else - { + } else { final ManagerResponse response; response = c.sendAction(new PingAction(), timeout); logger.debug("Ping response '" + response + "' for " + c.toString()); } - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Exception on sending Ping to " + c.toString(), e); } } diff --git a/src/main/java/org/asteriskjava/manager/ResponseEvents.java b/src/main/java/org/asteriskjava/manager/ResponseEvents.java index 568b254fd..a271d733f 100644 --- a/src/main/java/org/asteriskjava/manager/ResponseEvents.java +++ b/src/main/java/org/asteriskjava/manager/ResponseEvents.java @@ -16,28 +16,27 @@ */ package org.asteriskjava.manager; -import java.util.Collection; - import org.asteriskjava.manager.event.ResponseEvent; import org.asteriskjava.manager.response.ManagerResponse; +import java.util.Collection; + /** - * Contains the result of executing an + * Contains the result of executing an * {@link org.asteriskjava.manager.action.EventGeneratingAction}, that is the - * {@link org.asteriskjava.manager.response.ManagerResponse} and any received + * {@link org.asteriskjava.manager.response.ManagerResponse} and any received * {@link org.asteriskjava.manager.event.ManagerEvent}s. - * - * @see org.asteriskjava.manager.action.EventGeneratingAction + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.EventGeneratingAction * @since 0.2 */ -public interface ResponseEvents -{ +public interface ResponseEvents { /** * Returns the response received. - * + * * @return the response received. */ ManagerResponse getResponse(); @@ -45,7 +44,7 @@ public interface ResponseEvents /** * Returns a Collection of ManagerEvents that have been received including * the last one that indicates completion. - * + * * @return a Collection of ManagerEvents received. */ Collection getEvents(); diff --git a/src/main/java/org/asteriskjava/manager/SendActionCallback.java b/src/main/java/org/asteriskjava/manager/SendActionCallback.java index da195b92d..0e315621c 100644 --- a/src/main/java/org/asteriskjava/manager/SendActionCallback.java +++ b/src/main/java/org/asteriskjava/manager/SendActionCallback.java @@ -16,21 +16,21 @@ */ package org.asteriskjava.manager; +import org.asteriskjava.manager.action.ManagerAction; import org.asteriskjava.manager.response.ManagerResponse; /** * Callback interface to send {@link org.asteriskjava.manager.action.ManagerAction}s * asynchronously. - * - * @see org.asteriskjava.manager.ManagerConnection#sendAction(ManagerAction, SendActionCallback) + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.ManagerConnection#sendAction(ManagerAction, SendActionCallback) */ -public interface SendActionCallback -{ +public interface SendActionCallback { /** * This method is called when a response is received. - * + * * @param response the response that has been received */ void onResponse(ManagerResponse response); diff --git a/src/main/java/org/asteriskjava/manager/SendEventGeneratingActionCallback.java b/src/main/java/org/asteriskjava/manager/SendEventGeneratingActionCallback.java new file mode 100644 index 000000000..528e7d643 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/SendEventGeneratingActionCallback.java @@ -0,0 +1,29 @@ +package org.asteriskjava.manager; + +import org.asteriskjava.manager.response.ManagerError; +import org.asteriskjava.manager.response.ManagerResponse; + +/** + * Callback interface to send + * {@link org.asteriskjava.manager.action.EventGeneratingAction} asynchronously. + * + * @see org.asteriskjava.manager.ManagerConnection#sendEventGeneratingAction(org.asteriskjava.manager.action.EventGeneratingAction, SendEventGeneratingActionCallback) + *

      + * Initial response is passed to one of {@link #onResponse(ManagerResponse)} or + * {@link #onErrorResponse(ManagerResponse)}. but not both. + */ +public interface SendEventGeneratingActionCallback { + /** + * Called to notify that + * {@link ManagerConnection#sendEventGeneratingAction(org.asteriskjava.manager.action.EventGeneratingAction, SendEventGeneratingActionCallback)} + * is done. + *

      + * If connection is lost before action is completed then + * {@link ResponseEvents#getResponse()} can be null or list of events might + * be lacking some events including end event. The + * {@link ResponseEvents#getResponse()} can also be {@link ManagerError} + * + * @param responseEvents the response at whatever state it was when action ended. + */ + public void onResponse(ResponseEvents responseEvents); +} diff --git a/src/main/java/org/asteriskjava/manager/TimeoutException.java b/src/main/java/org/asteriskjava/manager/TimeoutException.java index 372df55bc..b9f26612a 100644 --- a/src/main/java/org/asteriskjava/manager/TimeoutException.java +++ b/src/main/java/org/asteriskjava/manager/TimeoutException.java @@ -19,12 +19,11 @@ /** * A TimeoutException is thrown if a ManagerResponse is not received within the * expected time period. - * + * * @author srt * @version $Id$ */ -public class TimeoutException extends Exception -{ +public class TimeoutException extends Exception { /** * Serial version identifier */ @@ -32,11 +31,10 @@ public class TimeoutException extends Exception /** * Creates a new TimeoutException with the given message. - * + * * @param message message with details about the timeout. */ - public TimeoutException(final String message) - { + public TimeoutException(final String message) { super(message); } } diff --git a/src/main/java/org/asteriskjava/manager/action/AbsoluteTimeoutAction.java b/src/main/java/org/asteriskjava/manager/action/AbsoluteTimeoutAction.java index c1ef7c3aa..eb6ec8830 100644 --- a/src/main/java/org/asteriskjava/manager/action/AbsoluteTimeoutAction.java +++ b/src/main/java/org/asteriskjava/manager/action/AbsoluteTimeoutAction.java @@ -29,12 +29,11 @@ * This action corresponds the the AbsoluteTimeout command used in the dialplan. *

      * Implemented in manager.c - * + * * @author srt * @version $Id$ */ -public class AbsoluteTimeoutAction extends AbstractManagerAction -{ +public class AbsoluteTimeoutAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -46,20 +45,18 @@ public class AbsoluteTimeoutAction extends AbstractManagerAction /** * Creates a new empty AbsoluteTimeoutAction. */ - public AbsoluteTimeoutAction() - { + public AbsoluteTimeoutAction() { } /** * Creates a new AbsoluteTimeoutAction with the given channel and timeout. - * + * * @param channel the name of the channel * @param timeout the maximum duation of the call in seconds or 0 to cancel the AbsoluteTimeout * @since 0.2 */ - public AbsoluteTimeoutAction(String channel, Integer timeout) - { + public AbsoluteTimeoutAction(String channel, Integer timeout) { this.channel = channel; this.timeout = timeout; } @@ -68,32 +65,28 @@ public AbsoluteTimeoutAction(String channel, Integer timeout) * Returns the name of this action, i.e. "AbsoluteTimeout". */ @Override - public String getAction() - { + public String getAction() { return "AbsoluteTimeout"; } /** * Returns the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the the maximum duation of the call (in seconds) to set. */ - public Integer getTimeout() - { + public Integer getTimeout() { return timeout; } @@ -101,8 +94,7 @@ public Integer getTimeout() * Sets the the maximum duation of the call (in seconds) to set on channel.

      * Setting the timeout to 0 cancels the timeout. */ - public void setTimeout(Integer timeout) - { + public void setTimeout(Integer timeout) { this.timeout = timeout; } } diff --git a/src/main/java/org/asteriskjava/manager/action/AbstractManagerAction.java b/src/main/java/org/asteriskjava/manager/action/AbstractManagerAction.java index 25dcb2fb7..7280ecda2 100644 --- a/src/main/java/org/asteriskjava/manager/action/AbstractManagerAction.java +++ b/src/main/java/org/asteriskjava/manager/action/AbstractManagerAction.java @@ -16,21 +16,20 @@ */ package org.asteriskjava.manager.action; +import org.asteriskjava.util.ReflectionUtil; + import java.lang.reflect.Method; import java.util.Map; -import org.asteriskjava.util.ReflectionUtil; - /** * This class implements the ManagerAction interface and can serve as base class * for your concrete Action implementations. - * + * * @author srt * @version $Id$ * @since 0.2 */ -public abstract class AbstractManagerAction implements ManagerAction -{ +public abstract class AbstractManagerAction implements ManagerAction { /** * Serializable version identifier. */ @@ -40,40 +39,33 @@ public abstract class AbstractManagerAction implements ManagerAction public abstract String getAction(); - public String getActionId() - { + public String getActionId() { return actionId; } - public void setActionId(String actionId) - { + public void setActionId(String actionId) { this.actionId = actionId; } @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; Map getters; - sb = new StringBuffer(getClass().getName() + "["); + sb = new StringBuilder(getClass().getName() + "["); sb.append("action='").append(getAction()).append("',"); getters = ReflectionUtil.getGetters(getClass()); - for (Map.Entry entry : getters.entrySet()) - { + for (Map.Entry entry : getters.entrySet()) { final String attribute = entry.getKey(); - if ("action".equals(attribute) || "class".equals(attribute)) - { + if ("action".equals(attribute) || "class".equals(attribute)) { continue; } - try - { + try { Object value; value = entry.getValue().invoke(this); sb.append(attribute).append("='").append(value).append("',"); - } - catch (Exception e) // NOPMD + } catch (Exception e) // NOPMD { // swallow } diff --git a/src/main/java/org/asteriskjava/manager/action/AbstractMeetMeMuteAction.java b/src/main/java/org/asteriskjava/manager/action/AbstractMeetMeMuteAction.java index 515097aca..684cc562b 100644 --- a/src/main/java/org/asteriskjava/manager/action/AbstractMeetMeMuteAction.java +++ b/src/main/java/org/asteriskjava/manager/action/AbstractMeetMeMuteAction.java @@ -18,12 +18,11 @@ /** * Abstract base class for mute and unmute actions. - * + * * @author srt * @version $Id$ */ -public abstract class AbstractMeetMeMuteAction extends AbstractManagerAction -{ +public abstract class AbstractMeetMeMuteAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -32,13 +31,11 @@ public abstract class AbstractMeetMeMuteAction extends AbstractManagerAction private String meetMe; private Integer userNum; - protected AbstractMeetMeMuteAction() - { + protected AbstractMeetMeMuteAction() { super(); } - protected AbstractMeetMeMuteAction(String meetMe, Integer userNum) - { + protected AbstractMeetMeMuteAction(String meetMe, Integer userNum) { super(); this.meetMe = meetMe; this.userNum = userNum; @@ -46,43 +43,39 @@ protected AbstractMeetMeMuteAction(String meetMe, Integer userNum) /** * Returns the conference number. - * + * * @return the conference number. */ - public String getMeetMe() - { + public String getMeetMe() { return meetMe; } /** * Sets the conference number.

      * This property is mandatory. - * + * * @param meetMe the conference number. */ - public void setMeetMe(String meetMe) - { + public void setMeetMe(String meetMe) { this.meetMe = meetMe; } /** * Returns the index of the user in the conference. - * + * * @return the index of the user in the conference. */ - public Integer getUserNum() - { + public Integer getUserNum() { return userNum; } /** * Sets the index of the user in the conference.

      * This property is mandatory. - * + * * @param userNum the index of the user in the conference. */ - public void setUserNum(Integer userNum) - { + public void setUserNum(Integer userNum) { this.userNum = userNum; } } diff --git a/src/main/java/org/asteriskjava/manager/action/AgentCallbackLoginAction.java b/src/main/java/org/asteriskjava/manager/action/AgentCallbackLoginAction.java index e00cde322..10598f07e 100644 --- a/src/main/java/org/asteriskjava/manager/action/AgentCallbackLoginAction.java +++ b/src/main/java/org/asteriskjava/manager/action/AgentCallbackLoginAction.java @@ -30,8 +30,8 @@ * @since 0.2 * @deprecated use {@link org.asteriskjava.manager.action.QueueAddAction} instead. */ -@Deprecated public class AgentCallbackLoginAction extends AbstractManagerAction -{ +@Deprecated +public class AgentCallbackLoginAction extends AbstractManagerAction { /** * Serializable version identifier. */ @@ -45,8 +45,7 @@ /** * Creates a new empty AgentCallbackLoginAction. */ - public AgentCallbackLoginAction() - { + public AgentCallbackLoginAction() { } @@ -58,8 +57,7 @@ public AgentCallbackLoginAction() * @param exten the extension that is called to connect a queue member with * this agent */ - public AgentCallbackLoginAction(String agent, String exten) - { + public AgentCallbackLoginAction(String agent, String exten) { this.agent = agent; this.exten = exten; } @@ -73,8 +71,7 @@ public AgentCallbackLoginAction(String agent, String exten) * this agent * @param context the context of the extension to use for callback */ - public AgentCallbackLoginAction(String agent, String exten, String context) - { + public AgentCallbackLoginAction(String agent, String exten, String context) { this(agent, exten); this.context = context; } @@ -95,8 +92,7 @@ public AgentCallbackLoginAction(String agent, String exten, String context) * null if default should be used. * @since 1.0.0 */ - public AgentCallbackLoginAction(String agent, String exten, String context, Boolean ackCall, Long wrapupTime) - { + public AgentCallbackLoginAction(String agent, String exten, String context, Boolean ackCall, Long wrapupTime) { this(agent, exten, context); this.ackCall = ackCall; this.wrapupTime = wrapupTime; @@ -108,8 +104,7 @@ public AgentCallbackLoginAction(String agent, String exten, String context, Bool * @return the name of this action */ @Override - public String getAction() - { + public String getAction() { return "AgentCallbackLogin"; } @@ -118,8 +113,7 @@ public String getAction() * * @return the name of the agent to log in */ - public String getAgent() - { + public String getAgent() { return agent; } @@ -129,8 +123,7 @@ public String getAgent() * * @param agent the name of the agent to log in */ - public void setAgent(String agent) - { + public void setAgent(String agent) { this.agent = agent; } @@ -139,8 +132,7 @@ public void setAgent(String agent) * * @return the extension to use for callback. */ - public String getExten() - { + public String getExten() { return exten; } @@ -150,8 +142,7 @@ public String getExten() * * @param exten the extension to use for callback. */ - public void setExten(String exten) - { + public void setExten(String exten) { this.exten = exten; } @@ -160,8 +151,7 @@ public void setExten(String exten) * * @return the context of the extension to use for callback. */ - public String getContext() - { + public String getContext() { return context; } @@ -170,8 +160,7 @@ public String getContext() * * @param context the context of the extension to use for callback. */ - public void setContext(String context) - { + public void setContext(String context) { this.context = context; } @@ -179,11 +168,10 @@ public void setContext(String context) * Returns if an acknowledgement is needed when agent is called back. * * @return Boolean.TRUE if acknowledgement by '#' is required when agent is - * called back, Boolean.FALSE otherwise. null if - * default should be used. + * called back, Boolean.FALSE otherwise. null if + * default should be used. */ - public Boolean getAckCall() - { + public Boolean getAckCall() { return ackCall; } @@ -196,8 +184,7 @@ public Boolean getAckCall() * '#' when agent is called back, Boolean.FALSE otherwise. * null if default should be used. */ - public void setAckCall(Boolean ackCall) - { + public void setAckCall(Boolean ackCall) { this.ackCall = ackCall; } @@ -206,10 +193,9 @@ public void setAckCall(Boolean ackCall) * can receive a new call. * * @return the minimum amount of time after disconnecting before the caller - * can receive a new call in seconds. + * can receive a new call in seconds. */ - public Long getWrapupTime() - { + public Long getWrapupTime() { return wrapupTime; } @@ -223,8 +209,7 @@ public Long getWrapupTime() * the caller can receive a new call. * null if default should be used. */ - public void setWrapupTime(Long wrapupTime) - { + public void setWrapupTime(Long wrapupTime) { this.wrapupTime = wrapupTime; } } diff --git a/src/main/java/org/asteriskjava/manager/action/AgentLogoffAction.java b/src/main/java/org/asteriskjava/manager/action/AgentLogoffAction.java index 2ed5ba1d4..940bbe1c4 100644 --- a/src/main/java/org/asteriskjava/manager/action/AgentLogoffAction.java +++ b/src/main/java/org/asteriskjava/manager/action/AgentLogoffAction.java @@ -19,13 +19,12 @@ /** * The AgentLogoffAction sets an agent as no longer logged in.

      * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class AgentLogoffAction extends AbstractManagerAction -{ +public class AgentLogoffAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -36,89 +35,81 @@ public class AgentLogoffAction extends AbstractManagerAction /** * Creates a new empty AgentLogoffAction. */ - public AgentLogoffAction() - { + public AgentLogoffAction() { } /** * Creates a new AgentLogoffAction that logs off the given agent - * + * * @param agent the name of the agent to log off. */ - public AgentLogoffAction(String agent) - { + public AgentLogoffAction(String agent) { this.agent = agent; } /** * Creates a new AgentLogoffAction that logs off the given agent - * + * * @param agent the name of the agent to log off. - * @param soft Boolean.TRUE if exisiting calls should not be hung up on - * logout. + * @param soft Boolean.TRUE if exisiting calls should not be hung up on + * logout. */ - public AgentLogoffAction(String agent, Boolean soft) - { + public AgentLogoffAction(String agent, Boolean soft) { this(agent); this.soft = soft; } /** * Returns the name of this action, i.e. "AgentLogoff". - * + * * @return the name of this action */ @Override - public String getAction() - { + public String getAction() { return "AgentLogoff"; } /** * Returns the name of the agent to log off, for example "1002". - * + * * @return the name of the agent to log off */ - public String getAgent() - { + public String getAgent() { return agent; } /** * Sets the name of the agent to log off, for example "1002".

      * This is property is mandatory. - * + * * @param agent the name of the agent to log off */ - public void setAgent(String agent) - { + public void setAgent(String agent) { this.agent = agent; } /** * Returns whether to hangup existing calls or not.

      * Default is to hangup existing calls on logoff. - * + * * @return Boolean.TRUE if existing calls should not be hung up, - * Boolean.FALSE otherwise. null if default should be - * used. + * Boolean.FALSE otherwise. null if default should be + * used. */ - public Boolean getSoft() - { + public Boolean getSoft() { return soft; } /** * Sets whether existing calls should be hung up or not.

      * Default is to hangup existing calls on logoff. - * + * * @param soft Boolean.TRUE if existing calls should not be hung up, - * Boolean.FALSE otherwise. null if default should - * be used. + * Boolean.FALSE otherwise. null if default should + * be used. */ - public void setSoft(Boolean soft) - { + public void setSoft(Boolean soft) { this.soft = soft; } } diff --git a/src/main/java/org/asteriskjava/manager/action/AgentsAction.java b/src/main/java/org/asteriskjava/manager/action/AgentsAction.java index 8e2324d62..2077b93ce 100644 --- a/src/main/java/org/asteriskjava/manager/action/AgentsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/AgentsAction.java @@ -24,16 +24,14 @@ * For each agent an AgentsEvent is generated. After the state of all agents has been * reported an AgentsCompleteEvent is generated.

      * Available since Asterisk 1.2 - * - * @see org.asteriskjava.manager.event.AgentsEvent - * @see org.asteriskjava.manager.event.AgentsCompleteEvent - * + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.AgentsEvent + * @see org.asteriskjava.manager.event.AgentsCompleteEvent * @since 0.2 */ -public class AgentsAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class AgentsAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serializable version identifier */ @@ -42,22 +40,19 @@ public class AgentsAction extends AbstractManagerAction implements EventGenerati /** * Creates a new AgentsAction. */ - public AgentsAction() - { - + public AgentsAction() { + } - + /** * Returns the name of this action, i.e. "Agents". */ @Override - public String getAction() - { + public String getAction() { return "Agents"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return AgentsCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/AgiAction.java b/src/main/java/org/asteriskjava/manager/action/AgiAction.java index 392e62725..014cefd15 100644 --- a/src/main/java/org/asteriskjava/manager/action/AgiAction.java +++ b/src/main/java/org/asteriskjava/manager/action/AgiAction.java @@ -24,16 +24,15 @@ * It will append the application to the specified channel's queue. * If the channel is not inside Async AGI application it will return an error.

      * It is implemented in res/res_agi.c - *

      + *
      * Available since Asterisk 1.6 * - * @see org.asteriskjava.manager.event.AsyncAgiEvent * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.AsyncAgiEvent * @since 1.0.0 */ -public class AgiAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class AgiAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serializable version identifier. */ @@ -46,8 +45,7 @@ public class AgiAction extends AbstractManagerAction implements EventGeneratingA /** * Creates a new empty AgiAction. */ - public AgiAction() - { + public AgiAction() { } @@ -57,8 +55,7 @@ public AgiAction() * @param channel the name of the channel to execute the AGI command on. * @param command the AGI command to execute. */ - public AgiAction(String channel, String command) - { + public AgiAction(String channel, String command) { this.channel = channel; this.command = command; } @@ -70,8 +67,7 @@ public AgiAction(String channel, String command) * @param command the AGI command to execute. * @param commandId the command id to track execution progress. */ - public AgiAction(String channel, String command, String commandId) - { + public AgiAction(String channel, String command, String commandId) { this.channel = channel; this.command = command; this.commandId = commandId; @@ -81,13 +77,11 @@ public AgiAction(String channel, String command, String commandId) * Returns the name of this action. */ @Override - public String getAction() - { + public String getAction() { return "AGI"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return AsyncAgiEvent.class; } @@ -96,8 +90,7 @@ public Class getActionCompleteEventClass() * * @return the name of the channel to execute the AGI command on. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -108,8 +101,7 @@ public String getChannel() * * @param channel the name of the channel to execute the AGI command on. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -118,8 +110,7 @@ public void setChannel(String channel) * * @return the AGI command to execute. */ - public String getCommand() - { + public String getCommand() { return command; } @@ -129,8 +120,7 @@ public String getCommand() * * @param command the AGI command to execute. */ - public void setCommand(String command) - { + public void setCommand(String command) { this.command = command; } @@ -139,8 +129,7 @@ public void setCommand(String command) * * @return the command id to track execution progress. */ - public String getCommandId() - { + public String getCommandId() { return commandId; } @@ -150,8 +139,7 @@ public String getCommandId() * * @param commandId the command id to track execution progress. */ - public void setCommandId(String commandId) - { + public void setCommandId(String commandId) { this.commandId = commandId; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/AtxferAction.java b/src/main/java/org/asteriskjava/manager/action/AtxferAction.java index 01e6f65f7..12b08fc5d 100644 --- a/src/main/java/org/asteriskjava/manager/action/AtxferAction.java +++ b/src/main/java/org/asteriskjava/manager/action/AtxferAction.java @@ -26,8 +26,7 @@ * @version $Id$ * @since 1.0.0 */ -public class AtxferAction extends AbstractManagerAction -{ +public class AtxferAction extends AbstractManagerAction { static final long serialVersionUID = 1L; private String channel; @@ -38,8 +37,7 @@ public class AtxferAction extends AbstractManagerAction /** * Creates a new empty AtxferAction. */ - public AtxferAction() - { + public AtxferAction() { } @@ -52,8 +50,7 @@ public AtxferAction() * @param exten the destination extension * @param priority the destination priority */ - public AtxferAction(String channel, String context, String exten, Integer priority) - { + public AtxferAction(String channel, String context, String exten, Integer priority) { this.channel = channel; this.context = context; this.exten = exten; @@ -65,8 +62,7 @@ public AtxferAction(String channel, String context, String exten, Integer priori * Returns the name of this action, i.e. "Atxfer". */ @Override - public String getAction() - { + public String getAction() { return "Atxfer"; } @@ -75,8 +71,7 @@ public String getAction() * * @return the name of the channel to transfer */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -85,8 +80,7 @@ public String getChannel() * * @param channel the name of the channel to transfer */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -95,8 +89,7 @@ public void setChannel(String channel) * * @return the destination context */ - public String getContext() - { + public String getContext() { return context; } @@ -105,8 +98,7 @@ public String getContext() * * @param context the destination context */ - public void setContext(String context) - { + public void setContext(String context) { this.context = context; } @@ -115,8 +107,7 @@ public void setContext(String context) * * @return the destination extension */ - public String getExten() - { + public String getExten() { return exten; } @@ -125,8 +116,7 @@ public String getExten() * * @param exten the destination extension */ - public void setExten(String exten) - { + public void setExten(String exten) { this.exten = exten; } @@ -135,8 +125,7 @@ public void setExten(String exten) * * @return the destination priority */ - public Integer getPriority() - { + public Integer getPriority() { return priority; } @@ -145,8 +134,7 @@ public Integer getPriority() * * @param priority the destination priority */ - public void setPriority(Integer priority) - { + public void setPriority(Integer priority) { this.priority = priority; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/BridgeAction.java b/src/main/java/org/asteriskjava/manager/action/BridgeAction.java index 1de6df0f9..17121eeda 100644 --- a/src/main/java/org/asteriskjava/manager/action/BridgeAction.java +++ b/src/main/java/org/asteriskjava/manager/action/BridgeAction.java @@ -25,8 +25,7 @@ * @version $Id$ * @since 1.0.0 */ -public class BridgeAction extends AbstractManagerAction -{ +public class BridgeAction extends AbstractManagerAction { /** * Serializable version identifier. */ @@ -39,8 +38,7 @@ public class BridgeAction extends AbstractManagerAction /** * Creates a new empty BridgeAction. */ - public BridgeAction() - { + public BridgeAction() { } @@ -50,8 +48,7 @@ public BridgeAction() * @param channel1 the name of the channel to bridge to channel2. * @param channel2 the name of the channel to bridge to channel1. */ - public BridgeAction(String channel1, String channel2) - { + public BridgeAction(String channel1, String channel2) { this.channel1 = channel1; this.channel2 = channel2; } @@ -63,8 +60,7 @@ public BridgeAction(String channel1, String channel2) * @param channel2 the name of the channel to bridge to channel1. * @param tone true to play a courtesy tone to channel2, false otherwise. */ - public BridgeAction(String channel1, String channel2, Boolean tone) - { + public BridgeAction(String channel1, String channel2, Boolean tone) { this.channel1 = channel1; this.channel2 = channel2; this.tone = tone; @@ -74,8 +70,7 @@ public BridgeAction(String channel1, String channel2, Boolean tone) * Returns the name of this action, i.e. "Bridge". */ @Override - public String getAction() - { + public String getAction() { return "Bridge"; } @@ -84,8 +79,7 @@ public String getAction() * * @return the name of the channel to bridge to channel2. */ - public String getChannel1() - { + public String getChannel1() { return channel1; } @@ -94,8 +88,7 @@ public String getChannel1() * * @param channel1 the name of the channel to bridge to channel2. */ - public void setChannel1(String channel1) - { + public void setChannel1(String channel1) { this.channel1 = channel1; } @@ -104,8 +97,7 @@ public void setChannel1(String channel1) * * @return the name of the channel to bridge to channel1. */ - public String getChannel2() - { + public String getChannel2() { return channel2; } @@ -114,8 +106,7 @@ public String getChannel2() * * @param channel2 the name of the channel to bridge to channel1. */ - public void setChannel2(String channel2) - { + public void setChannel2(String channel2) { this.channel2 = channel2; } @@ -123,10 +114,9 @@ public void setChannel2(String channel2) * Returns whether a courtesy tone will be played to channel2. * * @return true to play a courtesy tone to channel2, false or - * null (if not set) otherwise. + * null (if not set) otherwise. */ - public Boolean getTone() - { + public Boolean getTone() { return tone; } @@ -135,8 +125,7 @@ public Boolean getTone() * * @param tone true to play a courtesy tone to channel2, false otherwise. */ - public void setTone(Boolean tone) - { + public void setTone(Boolean tone) { this.tone = tone; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/ChallengeAction.java b/src/main/java/org/asteriskjava/manager/action/ChallengeAction.java index 01e10a25c..9b0f0a993 100644 --- a/src/main/java/org/asteriskjava/manager/action/ChallengeAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ChallengeAction.java @@ -30,16 +30,14 @@ * @see org.asteriskjava.manager.response.ChallengeResponse */ @ExpectedResponse(ChallengeResponse.class) -public class ChallengeAction extends AbstractManagerAction -{ +public class ChallengeAction extends AbstractManagerAction { static final long serialVersionUID = 7240516124871953971L; private String authType; /** * Creates a new empty ChallengeAction. */ - public ChallengeAction() - { + public ChallengeAction() { } @@ -50,8 +48,7 @@ public ChallengeAction() * @param authType the digest alogrithm to use. * @since 0.2 */ - public ChallengeAction(String authType) - { + public ChallengeAction(String authType) { this.authType = authType; } @@ -59,24 +56,21 @@ public ChallengeAction(String authType) * Returns Returns the name of this action, i.e. "Challenge". */ @Override - public String getAction() - { + public String getAction() { return "Challenge"; } /** * Returns the digest alogrithm to use. */ - public String getAuthType() - { + public String getAuthType() { return authType; } /** * Sets the digest alogrithm to use. Currently asterisk only supports "MD5". */ - public void setAuthType(String authType) - { + public void setAuthType(String authType) { this.authType = authType; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ChangeMonitorAction.java b/src/main/java/org/asteriskjava/manager/action/ChangeMonitorAction.java index a413fd3a4..1947eadcc 100644 --- a/src/main/java/org/asteriskjava/manager/action/ChangeMonitorAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ChangeMonitorAction.java @@ -20,12 +20,11 @@ * The ChangeMonitorAction changes the monitoring filename of a channel. It has * no effect if the channel is not monitored.

      * It is implemented in res/res_monitor.c - * + * * @author srt * @version $Id$ */ -public class ChangeMonitorAction extends AbstractManagerAction -{ +public class ChangeMonitorAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -36,22 +35,20 @@ public class ChangeMonitorAction extends AbstractManagerAction /** * Creates a new empty ChangeMonitorAction. */ - public ChangeMonitorAction() - { + public ChangeMonitorAction() { } /** * Creates a new ChangeMonitorAction that causes monitoring data for the * given channel to be written to the given file(s). - * + * * @param channel the name of the channel that is monitored - * @param file the (base) name of the file(s) to which the voice data is - * written + * @param file the (base) name of the file(s) to which the voice data is + * written * @since 0.2 */ - public ChangeMonitorAction(String channel, String file) - { + public ChangeMonitorAction(String channel, String file) { this.channel = channel; this.file = file; } @@ -60,16 +57,14 @@ public ChangeMonitorAction(String channel, String file) * Returns the name of this action, i.e. "ChangeMonitor". */ @Override - public String getAction() - { + public String getAction() { return "ChangeMonitor"; } /** * Returns the name of the monitored channel. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -77,16 +72,14 @@ public String getChannel() * Sets the name of the monitored channel.

      * This property is mandatory. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the name of the file to which the voice data is written. */ - public String getFile() - { + public String getFile() { return file; } @@ -94,8 +87,7 @@ public String getFile() * Sets the (base) name of the file(s) to which the voice data is written.

      * This property is mandatory. */ - public void setFile(String file) - { + public void setFile(String file) { this.file = file; } } diff --git a/src/main/java/org/asteriskjava/manager/action/CommandAction.java b/src/main/java/org/asteriskjava/manager/action/CommandAction.java index df7a4eaec..118d8acbd 100644 --- a/src/main/java/org/asteriskjava/manager/action/CommandAction.java +++ b/src/main/java/org/asteriskjava/manager/action/CommandAction.java @@ -43,16 +43,14 @@ * @see org.asteriskjava.manager.response.CommandResponse */ @ExpectedResponse(CommandResponse.class) -public class CommandAction extends AbstractManagerAction -{ +public class CommandAction extends AbstractManagerAction { static final long serialVersionUID = 4753117770471622025L; protected String command; /** * Creates a new CommandAction. */ - public CommandAction() - { + public CommandAction() { } @@ -62,8 +60,7 @@ public CommandAction() * @param command the CLI command to execute. * @since 0.2 */ - public CommandAction(String command) - { + public CommandAction(String command) { this.command = command; } @@ -71,24 +68,21 @@ public CommandAction(String command) * Returns the name of this action, i.e. "Command". */ @Override - public String getAction() - { + public String getAction() { return "Command"; } /** * Returns the command. */ - public String getCommand() - { + public String getCommand() { return command; } /** * Sets the CLI command to send to the Asterisk server. */ - public void setCommand(String command) - { + public void setCommand(String command) { this.command = command; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeKickAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeKickAction.java index e6192a62a..eb7527d86 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeKickAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeKickAction.java @@ -2,72 +2,72 @@ /** * The ConfbridgeKickAction kicks a channel out of a conference. - * + * * @author jmb * @version $Id$ */ public class ConfbridgeKickAction extends AbstractManagerAction { - + /** * Serializable version identifier */ - private static final long serialVersionUID = 3827556611709875112L; - - private String conference; + private static final long serialVersionUID = 3827556611709875112L; + + private String conference; private String channel; /** * Creates a new empty ConfbridgeKickAction. */ - public ConfbridgeKickAction() { - super(); - } - + public ConfbridgeKickAction() { + super(); + } + /** * Creates a new ConfbridgeKickAction. - * + * * @param conference the conference number. - * @param channel number of the channel in the conference. + * @param channel number of the channel in the conference. */ - public ConfbridgeKickAction(String conference, String channel) { - this.setConference(conference); - this.setChannel(channel); - } + public ConfbridgeKickAction(String conference, String channel) { + this.setConference(conference); + this.setChannel(channel); + } /** * Returns the name of this action, i.e. "ConfbridgeKick". */ - @Override - public String getAction() { - return "ConfbridgeKick"; - } + @Override + public String getAction() { + return "ConfbridgeKick"; + } - /** + /** * Sets the id of the conference to kick a channel from. - */ - public void setConference(String conference) { - this.conference = conference; - } + */ + public void setConference(String conference) { + this.conference = conference; + } /** * Returns the id of the conference to kick a channel from. - */ - public String getConference() { - return conference; - } + */ + public String getConference() { + return conference; + } /** * Sets the number of the channel to kick. */ - public void setChannel(String channel) { - this.channel = channel; - } + public void setChannel(String channel) { + this.channel = channel; + } /** * Returns the number of the channel to kick. - */ - public String getChannel() { - return channel; - } + */ + public String getChannel() { + return channel; + } } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeListAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeListAction.java index 45d4d4bd7..e22d06589 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeListAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeListAction.java @@ -9,39 +9,32 @@ * * @since 1.0.0 */ -public class ConfbridgeListAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class ConfbridgeListAction extends AbstractManagerAction implements EventGeneratingAction { private static final long serialVersionUID = 1L; private String conference; - public ConfbridgeListAction() - { + public ConfbridgeListAction() { } - public ConfbridgeListAction(String conference) - { + public ConfbridgeListAction(String conference) { this.conference = conference; } - public void setConference(String conference) - { + public void setConference(String conference) { this.conference = conference; } - public String getConference() - { + public String getConference() { return conference; } @Override - public String getAction() - { + public String getAction() { return "ConfbridgeList"; } @Override - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return ConfbridgeListCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeListRoomsAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeListRoomsAction.java index 551ecf3bd..024fb6188 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeListRoomsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeListRoomsAction.java @@ -4,24 +4,26 @@ import org.asteriskjava.manager.event.ResponseEvent; /** - * Lists data about all active conferences. ConfbridgeListRoomsEvent will follow as separate events, - * followed by a final event called ConfbridgeListRoomsComplete. + * Lists data about all active conferences. ConfbridgeListRoomsEvent will follow + * as separate events, followed by a final event called + * ConfbridgeListRoomsComplete. * * @since 1.0.0 */ -public class ConfbridgeListRoomsAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class ConfbridgeListRoomsAction extends AbstractManagerAction implements EventGeneratingAction { private static final long serialVersionUID = 1L; + /** + * note this requires the "reporting" WRITE permission + */ + @Override - public String getAction() - { + public String getAction() { return "ConfbridgeListRooms"; } @Override - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return ConfbridgeListRoomsCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeLockAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeLockAction.java index 64e0704e0..c55b9bfb1 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeLockAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeLockAction.java @@ -2,53 +2,53 @@ /** * The ConfbridgeLockAction lockes a specified conference. - * + * * @author jmb * @version $Id$ */ public class ConfbridgeLockAction extends AbstractManagerAction { - /** + /** * Serializable version identifier */ - private static final long serialVersionUID = 6146611916322541533L; - - private String conference; - + private static final long serialVersionUID = 6146611916322541533L; + + private String conference; + /** * Creates a new empty ConfbridgeLockAction. */ - public ConfbridgeLockAction() { - super(); - } - - /** + public ConfbridgeLockAction() { + super(); + } + + /** * Creates a new ConfbridgeLockAction for a specific conference. - */ - public ConfbridgeLockAction(String conference) { - this.setConference(conference); - } - + */ + public ConfbridgeLockAction(String conference) { + this.setConference(conference); + } + /** * Returns the name of this action "ConfbridgeLock". */ - @Override - public String getAction() { - return "ConfbridgeLock"; - } - - /** + @Override + public String getAction() { + return "ConfbridgeLock"; + } + + /** * Sets the id of the conference to lock. - */ - public void setConference(String conference) { - this.conference = conference; - } - + */ + public void setConference(String conference) { + this.conference = conference; + } + /** * Returns the id of the conference to lock. - */ - public String getConference() { - return conference; - } + */ + public String getConference() { + return conference; + } } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeMuteAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeMuteAction.java index 9e10e62ed..86c688cce 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeMuteAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeMuteAction.java @@ -2,7 +2,7 @@ /** * The ConfbridgeMuteAction mutes a channel in a conference. - * + * * @author jmb * @version $Id$ */ @@ -11,60 +11,60 @@ public class ConfbridgeMuteAction extends AbstractManagerAction { /** * Serializable version identifier */ - private static final long serialVersionUID = 1439791922666681989L; + private static final long serialVersionUID = 1439791922666681989L; - private String conference; + private String conference; private String channel; - + /** * Creates a new empty ConfbridgeMuteAction. */ - public ConfbridgeMuteAction() { - super(); - } + public ConfbridgeMuteAction() { + super(); + } /** * Creates a new ConfbridgeMuteAction. - * + * * @param conference the conference number. - * @param channel number of the channel in the conference. + * @param channel number of the channel in the conference. */ - public ConfbridgeMuteAction(String conference, String channel) { - this.setConference(conference); - this.setChannel(channel); - } - + public ConfbridgeMuteAction(String conference, String channel) { + this.setConference(conference); + this.setChannel(channel); + } + /** * Returns the name of this action, i.e. "ConfbridgeMute". */ - @Override - public String getAction() { - return "ConfbridgeMute"; - } - - /** + @Override + public String getAction() { + return "ConfbridgeMute"; + } + + /** * Sets the id of the conference. - */ - public void setConference(String conference) { - this.conference = conference; - } - + */ + public void setConference(String conference) { + this.conference = conference; + } + /** * Returns the id of the conference. - */ - public String getConference() { - return conference; - } + */ + public String getConference() { + return conference; + } /** * Sets the number of the channel to mute. */ - public void setChannel(String channel) { - this.channel = channel; - } - - public String getChannel() { - return channel; - } - + public void setChannel(String channel) { + this.channel = channel; + } + + public String getChannel() { + return channel; + } + } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeSetSingleVideoSrcAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeSetSingleVideoSrcAction.java index a8f89b5ce..7d6f33e29 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeSetSingleVideoSrcAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeSetSingleVideoSrcAction.java @@ -2,61 +2,61 @@ /** * The ConfbridgeSetSingleVideoSrcAction sets a conference user as the single video source distributed to all other video-capable participants. - * + * * @author jmb * @version $Id$ */ public class ConfbridgeSetSingleVideoSrcAction extends AbstractManagerAction { - /** + /** * Serializable version identifier */ - private static final long serialVersionUID = 88241670521642551L; - - private String conference; - private String channel; - + private static final long serialVersionUID = 88241670521642551L; + + private String conference; + private String channel; + /** * Creates a new empty ConfbridgeSetSingleVideoSrcAction. */ - public ConfbridgeSetSingleVideoSrcAction() { - super(); - } - + public ConfbridgeSetSingleVideoSrcAction() { + super(); + } + /** * Returns the name of this action "ConfbridgeSetSingleVideoSrc". */ - @Override - public String getAction() { - return "ConfbridgeSetSingleVideoSrc"; - } - - /** + @Override + public String getAction() { + return "ConfbridgeSetSingleVideoSrc"; + } + + /** * Sets the id of the conference for which the video source is to be set. - */ - public void setConference(String conference) { - this.conference = conference; - } - + */ + public void setConference(String conference) { + this.conference = conference; + } + /** * Returns the id of the conference for which the video source is to be set. - */ - public String getConference() { - return conference; - } + */ + public String getConference() { + return conference; + } - /** + /** * Sets the channel which will be the single video source of the conference. - */ - public void setChannel(String channel) { - this.channel = channel; - } - - /** + */ + public void setChannel(String channel) { + this.channel = channel; + } + + /** * Returns the channel which will be the single video source of the conference. - */ - public String getChannel() { - return channel; - } + */ + public String getChannel() { + return channel; + } } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeStartRecordAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeStartRecordAction.java index 8202944ed..ff92772c1 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeStartRecordAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeStartRecordAction.java @@ -1,54 +1,76 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.asteriskjava.manager.action; /** * The ConfbridgeStartAction starts an audio recording of a conference. - * + * * @author jmb * @version $Id$ */ public class ConfbridgeStartRecordAction extends AbstractManagerAction { - /** * Serializable version identifier */ - private static final long serialVersionUID = 3059632508521358701L; - - private String conference; - + private static final long serialVersionUID = 3059632508521358701L; + + private String conference; + private String recordFile; + /** * Creates a new empty ConfbridgeStartRecordAction. */ - public ConfbridgeStartRecordAction() { - super(); - } - - /** + public ConfbridgeStartRecordAction() { + super(); + } + + /** * Creates a new ConfbridgeStartRecordAction for a specific conference. - */ - public ConfbridgeStartRecordAction(String conference) { - this.setConference(conference); - } - + */ + public ConfbridgeStartRecordAction(String conference) { + this.setConference(conference); + } + /** * Returns the name of this action, i.e. "ConfbridgeStartRecord". */ - @Override - public String getAction() { - return "ConfbridgeStartRecord"; - } - - /** + @Override + public String getAction() { + return "ConfbridgeStartRecord"; + } + + /** * Sets the id of the conference for which to start an audio recording. - */ - public void setConference(String conference) { - this.conference = conference; - } - + */ + public void setConference(String conference) { + this.conference = conference; + } + /** * Returns the id of the conference for which to start an audio recording. - */ - public String getConference() { - return conference; - } + */ + public String getConference() { + return conference; + } + + public String getRecordFile() { + return recordFile; + } + public void setRecordFile(String recordFile) { + this.recordFile = recordFile; + } } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeStopRecordAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeStopRecordAction.java index 5abf5dec8..2a5d8c6ec 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeStopRecordAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeStopRecordAction.java @@ -2,7 +2,7 @@ /** * The ConfbridgeStopAction stops an audio recording of a conference. - * + * * @author jmb * @version $Id$ */ @@ -11,44 +11,44 @@ public class ConfbridgeStopRecordAction extends AbstractManagerAction { /** * Serializable version identifier */ - private static final long serialVersionUID = 7429055239528793083L; - - private String conference; + private static final long serialVersionUID = 7429055239528793083L; + + private String conference; /** * Creates a new empty ConfbridgeStopRecordAction. */ - public ConfbridgeStopRecordAction() { - super(); - } - - /** + public ConfbridgeStopRecordAction() { + super(); + } + + /** * Creates a new ConfbridgeStopRecordAction for a specific conference. - */ - public ConfbridgeStopRecordAction(String conference) { - this.setConference(conference); - } - + */ + public ConfbridgeStopRecordAction(String conference) { + this.setConference(conference); + } + /** * Returns the name of this action, i.e. "ConfbridgeStopRecord". */ - @Override - public String getAction() { - return "ConfbridgeStopRecord"; - } + @Override + public String getAction() { + return "ConfbridgeStopRecord"; + } - /** + /** * Sets the id of the conference for which to stop an audio recording. - */ - public void setConference(String conference) { - this.conference = conference; - } + */ + public void setConference(String conference) { + this.conference = conference; + } /** * Returns the id of the conference for which to stop an audio recording. - */ - public String getConference() { - return conference; - } + */ + public String getConference() { + return conference; + } } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeUnlockAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeUnlockAction.java index 056dac808..fb91b522f 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeUnlockAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeUnlockAction.java @@ -2,53 +2,53 @@ /** * The ConfbridgeUnlockAction unlocks a specified conference. - * + * * @author jmb * @version $Id$ */ public class ConfbridgeUnlockAction extends AbstractManagerAction { - /** + /** * Serializable version identifier */ - private static final long serialVersionUID = 88241670521642551L; - - private String conference; - + private static final long serialVersionUID = 88241670521642551L; + + private String conference; + /** * Creates a new empty ConfbridgeUnlockAction. */ - public ConfbridgeUnlockAction() { - super(); - } - - /** + public ConfbridgeUnlockAction() { + super(); + } + + /** * Creates a new ConfbridgeUnlockAction for a specific conference. - */ - public ConfbridgeUnlockAction(String conference) { - this.setConference(conference); - } - + */ + public ConfbridgeUnlockAction(String conference) { + this.setConference(conference); + } + /** * Returns the name of this action "ConfbridgeUnlock". */ - @Override - public String getAction() { - return "ConfbridgeUnlock"; - } - - /** + @Override + public String getAction() { + return "ConfbridgeUnlock"; + } + + /** * Sets the id of the conference to unlock. - */ - public void setConference(String conference) { - this.conference = conference; - } - + */ + public void setConference(String conference) { + this.conference = conference; + } + /** * Returns the id of the conference to unlock. - */ - public String getConference() { - return conference; - } + */ + public String getConference() { + return conference; + } } diff --git a/src/main/java/org/asteriskjava/manager/action/ConfbridgeUnmuteAction.java b/src/main/java/org/asteriskjava/manager/action/ConfbridgeUnmuteAction.java index 40a18ece5..f6a4845ff 100644 --- a/src/main/java/org/asteriskjava/manager/action/ConfbridgeUnmuteAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ConfbridgeUnmuteAction.java @@ -2,73 +2,73 @@ /** * The ConfbridgeUnmuteAction unmutes a channel in a conference. - * + * * @author jmb * @version $Id$ */ public class ConfbridgeUnmuteAction extends AbstractManagerAction { - /** + /** * Serializable version identifier */ - private static final long serialVersionUID = -590852239774371298L; - - private String conference; + private static final long serialVersionUID = -590852239774371298L; + + private String conference; private String channel; - + /** * Creates a new empty ConfbridgeUnmuteAction. */ - public ConfbridgeUnmuteAction() { - super(); - } + public ConfbridgeUnmuteAction() { + super(); + } /** * Creates a new ConfbridgeUnmuteAction. - * + * * @param conference the conference number. - * @param channel number of the channel in the conference. + * @param channel number of the channel in the conference. */ - public ConfbridgeUnmuteAction(String conference, String channel) { - this.setConference(conference); - this.setChannel(channel); - } + public ConfbridgeUnmuteAction(String conference, String channel) { + this.setConference(conference); + this.setChannel(channel); + } /** * Returns the name of this action, i.e. "ConfbridgeUnmute". */ - @Override - public String getAction() { - return "ConfbridgeUnmute"; - } + @Override + public String getAction() { + return "ConfbridgeUnmute"; + } - /** + /** * Sets the id of the conference. - */ - public void setConference(String conference) { - this.conference = conference; - } + */ + public void setConference(String conference) { + this.conference = conference; + } /** * Returns the id of the conference. - */ - public String getConference() { - return conference; - } + */ + public String getConference() { + return conference; + } /** * Sets the number of the channel to unmute. */ - public void setChannel(String channel) { - this.channel = channel; - } + public void setChannel(String channel) { + this.channel = channel; + } /** * Returns the number of the channel to unmute. - */ - public String getChannel() { - return channel; - } - + */ + public String getChannel() { + return channel; + } + } diff --git a/src/main/java/org/asteriskjava/manager/action/CoreSettingsAction.java b/src/main/java/org/asteriskjava/manager/action/CoreSettingsAction.java index 64dee5171..0a81b36b2 100644 --- a/src/main/java/org/asteriskjava/manager/action/CoreSettingsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/CoreSettingsAction.java @@ -31,15 +31,13 @@ * @since 1.0.0 */ @ExpectedResponse(CoreSettingsResponse.class) -public class CoreSettingsAction extends AbstractManagerAction -{ +public class CoreSettingsAction extends AbstractManagerAction { static final long serialVersionUID = 1L; /** * Creates a new CoreSettingsAction. */ - public CoreSettingsAction() - { + public CoreSettingsAction() { } @@ -47,8 +45,7 @@ public CoreSettingsAction() * Returns the name of this action, i.e. "CoreSettings". */ @Override - public String getAction() - { + public String getAction() { return "CoreSettings"; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/CoreShowChannelsAction.java b/src/main/java/org/asteriskjava/manager/action/CoreShowChannelsAction.java index 4c0eea236..b6210c2c2 100644 --- a/src/main/java/org/asteriskjava/manager/action/CoreShowChannelsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/CoreShowChannelsAction.java @@ -1,12 +1,12 @@ /* * Copyright 2009 Sebastian. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,27 +32,23 @@ * @see org.asteriskjava.manager.event.CoreShowChannelsCompleteEvent * @since 1.0.0 */ -public class CoreShowChannelsAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class CoreShowChannelsAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serializable version identifier. */ static final long serialVersionUID = 0L; - public CoreShowChannelsAction() - { + public CoreShowChannelsAction() { } @Override - public String getAction() - { + public String getAction() { return "CoreShowChannels"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return CoreShowChannelsCompleteEvent.class; } diff --git a/src/main/java/org/asteriskjava/manager/action/CoreStatusAction.java b/src/main/java/org/asteriskjava/manager/action/CoreStatusAction.java index 5f7180497..7a178d5ed 100644 --- a/src/main/java/org/asteriskjava/manager/action/CoreStatusAction.java +++ b/src/main/java/org/asteriskjava/manager/action/CoreStatusAction.java @@ -30,15 +30,13 @@ * @since 1.0.0 */ @ExpectedResponse(CoreStatusResponse.class) -public class CoreStatusAction extends AbstractManagerAction -{ +public class CoreStatusAction extends AbstractManagerAction { static final long serialVersionUID = 1L; /** * Creates a new CoreStatusAction. */ - public CoreStatusAction() - { + public CoreStatusAction() { } @@ -46,8 +44,7 @@ public CoreStatusAction() * Returns the name of this action, i.e. "CoreStatus". */ @Override - public String getAction() - { + public String getAction() { return "CoreStatus"; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/DahdiShowChannelsAction.java b/src/main/java/org/asteriskjava/manager/action/DahdiShowChannelsAction.java new file mode 100644 index 000000000..a52b21cbd --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/DahdiShowChannelsAction.java @@ -0,0 +1,58 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +import org.asteriskjava.manager.event.DahdiShowChannelsCompleteEvent; +import org.asteriskjava.manager.event.ResponseEvent; + +/** + * The DahdiShowChannelsAction requests the state of all Dahdi channels.

      + * For each Dahdi channel aDahdiShowChannelsEvent is generated. After all Dahdi + * channels have been listed a DahdiShowChannelsCompleteEvent is generated. + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.event.DahdiShowChannelsEvent + * @see org.asteriskjava.manager.event.DahdiShowChannelsCompleteEvent + */ +public class DahdiShowChannelsAction extends AbstractManagerAction + implements + EventGeneratingAction { + /** + * Serializable version identifier + */ + private static final long serialVersionUID = 8697000330085766825L; + + /** + * Creates a new DahdiShowChannelsAction. + */ + public DahdiShowChannelsAction() { + + } + + /** + * Returns the name of this action, i.e. "DahdiShowChannels". + */ + @Override + public String getAction() { + return "DahdiShowChannels"; + } + + public Class getActionCompleteEventClass() { + return DahdiShowChannelsCompleteEvent.class; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/DbDelAction.java b/src/main/java/org/asteriskjava/manager/action/DbDelAction.java index f64aa4dc4..528424fe0 100644 --- a/src/main/java/org/asteriskjava/manager/action/DbDelAction.java +++ b/src/main/java/org/asteriskjava/manager/action/DbDelAction.java @@ -19,11 +19,10 @@ /** * Deletes an entry in the Asterisk database for a given family and key.

      * Available since Asterisk 1.2 with BRIStuff patches and since Asterisk 1.6 - * + * * @author gmi */ -public class DbDelAction extends AbstractManagerAction -{ +public class DbDelAction extends AbstractManagerAction { private static final long serialVersionUID = 921037572305993779L; private String family; private String key; @@ -31,66 +30,59 @@ public class DbDelAction extends AbstractManagerAction /** * Creates a new empty DbDelAction. */ - public DbDelAction() - { + public DbDelAction() { } /** * Creates a new DbDelAction that deletes the value of the database - * + * * @param family the family of the key - * @param key the key of the entry to delete + * @param key the key of the entry to delete */ - public DbDelAction(String family, String key) - { + public DbDelAction(String family, String key) { this.family = family; this.key = key; } @Override - public String getAction() - { + public String getAction() { return "DBDel"; } /** * Returns the family of the key to delete - * + * * @return the family of the key to delete */ - public String getFamily() - { + public String getFamily() { return family; } /** * Sets the family of the key to delete - * + * * @param family the family of the key to delete */ - public void setFamily(String family) - { + public void setFamily(String family) { this.family = family; } /** * Returns the the key to delete - * + * * @return the key to delete */ - public String getKey() - { + public String getKey() { return key; } /** * Sets the key to delete - * + * * @param key the key to delete */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } } diff --git a/src/main/java/org/asteriskjava/manager/action/DbDelTreeAction.java b/src/main/java/org/asteriskjava/manager/action/DbDelTreeAction.java index 2807135df..6b21c94d4 100644 --- a/src/main/java/org/asteriskjava/manager/action/DbDelTreeAction.java +++ b/src/main/java/org/asteriskjava/manager/action/DbDelTreeAction.java @@ -23,8 +23,7 @@ * @author gmi * @since 1.0.0 */ -public class DbDelTreeAction extends AbstractManagerAction -{ +public class DbDelTreeAction extends AbstractManagerAction { private static final long serialVersionUID = 1L; private String family; private String key; @@ -32,8 +31,7 @@ public class DbDelTreeAction extends AbstractManagerAction /** * Creates a new empty DbDelTreeAction. */ - public DbDelTreeAction() - { + public DbDelTreeAction() { } @@ -41,17 +39,15 @@ public DbDelTreeAction() * Creates a new DbDelTreeAction. * * @param family the family of the key - * @param key the key of the entries to delete + * @param key the key of the entries to delete */ - public DbDelTreeAction(String family, String key) - { + public DbDelTreeAction(String family, String key) { this.family = family; this.key = key; } @Override - public String getAction() - { + public String getAction() { return "DBDelTree"; } @@ -60,8 +56,7 @@ public String getAction() * * @return the family of the key to delete */ - public String getFamily() - { + public String getFamily() { return family; } @@ -70,8 +65,7 @@ public String getFamily() * * @param family the family of the key to delete */ - public void setFamily(String family) - { + public void setFamily(String family) { this.family = family; } @@ -80,8 +74,7 @@ public void setFamily(String family) * * @return the key to delete */ - public String getKey() - { + public String getKey() { return key; } @@ -90,8 +83,7 @@ public String getKey() * * @param key the key to delete */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/DbGetAction.java b/src/main/java/org/asteriskjava/manager/action/DbGetAction.java index eceda8b05..591abf8b0 100644 --- a/src/main/java/org/asteriskjava/manager/action/DbGetAction.java +++ b/src/main/java/org/asteriskjava/manager/action/DbGetAction.java @@ -31,8 +31,7 @@ * @see org.asteriskjava.manager.event.DbGetResponseEvent * @since 0.2 */ -public class DbGetAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class DbGetAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serial version identifier */ @@ -43,8 +42,7 @@ public class DbGetAction extends AbstractManagerAction implements EventGeneratin /** * Creates a new empty DbGetAction. */ - public DbGetAction() - { + public DbGetAction() { } @@ -56,15 +54,13 @@ public DbGetAction() * @param key the key of the entry to retrieve * @since 0.2 */ - public DbGetAction(String family, String key) - { + public DbGetAction(String family, String key) { this.family = family; this.key = key; } @Override - public String getAction() - { + public String getAction() { return "DBGet"; } @@ -73,8 +69,7 @@ public String getAction() * * @return the family of the key. */ - public String getFamily() - { + public String getFamily() { return family; } @@ -83,8 +78,7 @@ public String getFamily() * * @param family the family of the key. */ - public void setFamily(String family) - { + public void setFamily(String family) { this.family = family; } @@ -93,8 +87,7 @@ public void setFamily(String family) * * @return the key of the entry to retrieve. */ - public String getKey() - { + public String getKey() { return key; } @@ -103,13 +96,11 @@ public String getKey() * * @param key the key of the entry to retrieve. */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return DbGetResponseEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/DbPutAction.java b/src/main/java/org/asteriskjava/manager/action/DbPutAction.java index 9eb4d1f28..d91242c50 100644 --- a/src/main/java/org/asteriskjava/manager/action/DbPutAction.java +++ b/src/main/java/org/asteriskjava/manager/action/DbPutAction.java @@ -20,13 +20,12 @@ * Adds or updates an entry in the Asterisk database for a given family, key, * and value.

      * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class DbPutAction extends AbstractManagerAction -{ +public class DbPutAction extends AbstractManagerAction { /** * Serial version identifier. */ @@ -38,101 +37,91 @@ public class DbPutAction extends AbstractManagerAction /** * Creates a new empty DbPutAction. */ - public DbPutAction() - { + public DbPutAction() { } /** * Creates a new DbPutAction that sets the value of the database entry with * the given key in the given family. - * + * * @param family the family of the key - * @param key the key of the entry to set - * @param val the value to set + * @param key the key of the entry to set + * @param val the value to set * @since 0.2 */ - public DbPutAction(String family, String key, String val) - { + public DbPutAction(String family, String key, String val) { this.family = family; this.key = key; this.val = val; } @Override - public String getAction() - { + public String getAction() { return "DBPut"; } /** * Returns the family of the key to set. - * + * * @return the family of the key to set. */ - public String getFamily() - { + public String getFamily() { return family; } /** * Sets the family of the key to set. - * + * * @param family the family of the key to set. */ - public void setFamily(String family) - { + public void setFamily(String family) { this.family = family; } /** * Returns the the key to set. - * + * * @return the key to set. */ - public String getKey() - { + public String getKey() { return key; } /** * Sets the key to set. - * + * * @param key the key to set. */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } /** * Returns the value to set. - * + * * @return the value to set. */ - public String getVal() - { + public String getVal() { return val; } /** * Sets the value to set. - * + * * @param val the value to set. */ - public void setVal(String val) - { + public void setVal(String val) { this.val = val; } - + /** * Returns the value to set for BRIstuffed versions. - * + * * @return the value to set. * @since 1.0.0 */ - public String getValue() - { + public String getValue() { return val; } } diff --git a/src/main/java/org/asteriskjava/manager/action/DongleSendSMSAction.java b/src/main/java/org/asteriskjava/manager/action/DongleSendSMSAction.java new file mode 100644 index 000000000..a0dde3f58 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/DongleSendSMSAction.java @@ -0,0 +1,37 @@ +package org.asteriskjava.manager.action; + +public class DongleSendSMSAction extends AbstractManagerAction { + static final long serialVersionUID = 8194597741743334704L; + private String device; + private String number; + private String message; + + @Override + public String getAction() { + return "DongleSendSMS"; + } + + public String getDevice() { + return this.device; + } + + public void setDevice(String d) { + this.device = d; + } + + public String getNumber() { + return this.number; + } + + public void setNumber(String callerId) { + this.number = callerId; + } + + public String getMessage() { + return this.message; + } + + public void setMessage(String m) { + this.message = m; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/DongleShowDevicesAction.java b/src/main/java/org/asteriskjava/manager/action/DongleShowDevicesAction.java new file mode 100644 index 000000000..c2418b717 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/DongleShowDevicesAction.java @@ -0,0 +1,33 @@ +package org.asteriskjava.manager.action; + +import org.asteriskjava.manager.event.DongleShowDevicesCompleteEvent; +import org.asteriskjava.manager.event.ResponseEvent; + + +public class DongleShowDevicesAction extends AbstractManagerAction + implements + EventGeneratingAction { + /** + * Serializable version identifier + */ + private static final long serialVersionUID = 8697000330085466825L; + + /** + * Creates a new DahdiShowChannelsAction. + */ + public DongleShowDevicesAction() { + + } + + /** + * Returns the name of this action, i.e. "DahdiShowChannels". + */ + @Override + public String getAction() { + return "DongleShowDevices"; + } + + public Class getActionCompleteEventClass() { + return DongleShowDevicesCompleteEvent.class; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/EventGeneratingAction.java b/src/main/java/org/asteriskjava/manager/action/EventGeneratingAction.java index c521748a7..acd4bf04e 100644 --- a/src/main/java/org/asteriskjava/manager/action/EventGeneratingAction.java +++ b/src/main/java/org/asteriskjava/manager/action/EventGeneratingAction.java @@ -24,18 +24,17 @@ * events.

      * The event type that indicates that Asterisk is finished is returned by the * getActionCompleteEventClass() method. - * - * @see org.asteriskjava.manager.event.ResponseEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.ResponseEvent * @since 0.2 */ -public interface EventGeneratingAction extends ManagerAction -{ +public interface EventGeneratingAction extends ManagerAction { /** * Returns the event type that indicates that Asterisk is finished sending * response events for this action. - * + * * @return a Class that is an instance of ResponseEvent. * @see org.asteriskjava.manager.event.ResponseEvent */ diff --git a/src/main/java/org/asteriskjava/manager/action/EventsAction.java b/src/main/java/org/asteriskjava/manager/action/EventsAction.java index 811867c03..953a47ce8 100644 --- a/src/main/java/org/asteriskjava/manager/action/EventsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/EventsAction.java @@ -19,12 +19,11 @@ /** * With the EventsAction you can specify what kind of events should be sent to * this manager connection. - * + * * @author srt * @version $Id$ */ -public class EventsAction extends AbstractManagerAction -{ +public class EventsAction extends AbstractManagerAction { /** * Serializable version identifier. */ @@ -35,23 +34,21 @@ public class EventsAction extends AbstractManagerAction /** * Creates a new empty EventsAction. */ - public EventsAction() - { + public EventsAction() { } /** * Creates a new EventsAction that applies the given event mask to the * current manager connection. - * + * * @param eventMask the event mask. Set to "on" if all events should be - * send, "off" if not events should be sent or a combination of - * "system", "call" and "log" (separated by ',') to specify what - * kind of events should be sent. + * send, "off" if not events should be sent or a combination of + * "system", "call" and "log" (separated by ',') to specify what + * kind of events should be sent. * @since 0.2 */ - public EventsAction(String eventMask) - { + public EventsAction(String eventMask) { this.eventMask = eventMask; } @@ -59,16 +56,14 @@ public EventsAction(String eventMask) * Returns the name of this action, i.e. "Events". */ @Override - public String getAction() - { + public String getAction() { return "Events"; } /** * Returns the event mask. */ - public String getEventMask() - { + public String getEventMask() { return eventMask; } @@ -78,8 +73,7 @@ public String getEventMask() * sent or a combination of "system", "call" and "log" (separated by ',') to * specify what kind of events should be sent. */ - public void setEventMask(String eventMask) - { + public void setEventMask(String eventMask) { this.eventMask = eventMask; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ExecAction.java b/src/main/java/org/asteriskjava/manager/action/ExecAction.java new file mode 100644 index 000000000..7fa229e13 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/ExecAction.java @@ -0,0 +1,93 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +import org.asteriskjava.manager.ExpectedResponse; +import org.asteriskjava.manager.response.CommandResponse; + +/** + * The CommandAction sends a command line interface (CLI) command to the + * asterisk server. + *

      + * For a list of supported commands type help on Asterisk's command + * line. + *

      + * In response to a CommandAction you will receive a CommandResponse that + * contains the CLI output. + *

      + * Example: + * + *

      + * CommandAction commandAction = new CommandAction("iax2 show peers");
      + * CommandResponse response = (CommandResponse) c.sendAction(commandAction);
      + * for (String line : response.getResult())
      + * {
      + *     System.out.println(line);
      + * }
      + * 
      + *

      + * Where c is an instance of + * {@link org.asteriskjava.manager.ManagerConnection}. + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.response.CommandResponse + */ +@ExpectedResponse(CommandResponse.class) +public class ExecAction extends AbstractManagerAction { + static final long serialVersionUID = 4753117770471622025L; + protected String command; + + /** + * Creates a new CommandAction. + */ + public ExecAction() { + + } + + /** + * Creates a new CommandAction with the given command. + * + * @param command the CLI command to execute. + * @since 0.2 + */ + public ExecAction(String command) { + this.command = command; + } + + /** + * Returns the name of this action, i.e. "Command". + */ + @Override + public String getAction() { + return "exec"; + } + + /** + * Returns the command. + */ + public String getCommand() { + return command; + } + + /** + * Sets the CLI command to send to the Asterisk server. + */ + public void setCommand(String command) { + this.command = command; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/ExtensionStateAction.java b/src/main/java/org/asteriskjava/manager/action/ExtensionStateAction.java index 9f2b3be4f..b3062022a 100644 --- a/src/main/java/org/asteriskjava/manager/action/ExtensionStateAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ExtensionStateAction.java @@ -28,8 +28,7 @@ * @version $Id$ */ @ExpectedResponse(ExtensionStateResponse.class) -public class ExtensionStateAction extends AbstractManagerAction -{ +public class ExtensionStateAction extends AbstractManagerAction { static final long serialVersionUID = 6537408784388696403L; private String exten; @@ -38,20 +37,18 @@ public class ExtensionStateAction extends AbstractManagerAction /** * Creates a new ExtensionStateAction. */ - public ExtensionStateAction() - { + public ExtensionStateAction() { } /** * Creates a new ExtensionStateAction that queries the state of the given extension in * the given context. * - * @param exten the extension to query. + * @param exten the extension to query. * @param context the name of the context that contains the extension to query. * @since 1.0.0 */ - public ExtensionStateAction(String exten, String context) - { + public ExtensionStateAction(String exten, String context) { this.exten = exten; this.context = context; } @@ -60,8 +57,7 @@ public ExtensionStateAction(String exten, String context) * Returns the name of this action, i.e. "ExtensionState". */ @Override - public String getAction() - { + public String getAction() { return "ExtensionState"; } @@ -70,8 +66,7 @@ public String getAction() * * @return the extension to query. */ - public String getExten() - { + public String getExten() { return exten; } @@ -80,8 +75,7 @@ public String getExten() * * @param exten the extension to query. */ - public void setExten(String exten) - { + public void setExten(String exten) { this.exten = exten; } @@ -90,8 +84,7 @@ public void setExten(String exten) * * @return the name of the context that contains the extension to query. */ - public String getContext() - { + public String getContext() { return context; } @@ -100,8 +93,7 @@ public String getContext() * * @param context the name of the context that contains the extension to query. */ - public void setContext(String context) - { + public void setContext(String context) { this.context = context; } } diff --git a/src/main/java/org/asteriskjava/manager/action/FaxLicenseListAction.java b/src/main/java/org/asteriskjava/manager/action/FaxLicenseListAction.java new file mode 100644 index 000000000..1dd8d560d --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/FaxLicenseListAction.java @@ -0,0 +1,16 @@ +package org.asteriskjava.manager.action; + +import org.asteriskjava.manager.event.FaxLicenseListCompleteEvent; +import org.asteriskjava.manager.event.ResponseEvent; + +public final class FaxLicenseListAction extends AbstractManagerAction implements EventGeneratingAction { + @Override + public String getAction() { + return "FaxLicenseList"; + } + + @Override + public Class getActionCompleteEventClass() { + return FaxLicenseListCompleteEvent.class; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/FaxLicenseStatusAction.java b/src/main/java/org/asteriskjava/manager/action/FaxLicenseStatusAction.java new file mode 100644 index 000000000..5768ded9f --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/FaxLicenseStatusAction.java @@ -0,0 +1,12 @@ +package org.asteriskjava.manager.action; + +import org.asteriskjava.manager.ExpectedResponse; +import org.asteriskjava.manager.response.FaxLicenseStatusResponse; + +@ExpectedResponse(FaxLicenseStatusResponse.class) +public final class FaxLicenseStatusAction extends AbstractManagerAction { + @Override + public String getAction() { + return "FaxLicenseStatus"; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/FilterAction.java b/src/main/java/org/asteriskjava/manager/action/FilterAction.java new file mode 100644 index 000000000..ec4ddcc32 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/FilterAction.java @@ -0,0 +1,100 @@ +/* + * Copyright 2019 Richie Chauhan + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +/** + * The FilterAction dynamically adds filters for the current user in a manager session. + * The filters added are only used for the current session. Once the connection is closed the filters are removed. + *

      + * This command requires the user has read access to specific events(manager.conf) and system permission + * because it can be used to create filters that may bypass filters defined in manager.conf + *

      + * There are 2 Types of filters: + * Blacklist: The event you no longer want to receive. It starts with an exclamation. eg. "!RTCPReceived". + * Whitelist: The event you are interested in receiving. eg. "RTCPReceived". + *

      + * Regular expressions can be used for the filters. + *

      + * Evaluation of the filters is as follows: + * If no filters are configured all events are reported as normal. + * If there are white filters only: Then it is implied that all events are black listed and only the specified white filter events are returned. + * If there are black filters only: Then it is implied that all events are white listed and only the specified black filter events are removed. + * If there are both white and black filters: Then it is implied that all events are black listed and only the specified white filter events are returned, + * and then specific blacklisted events are further removed. (Limited use cases) + * + * @author aavaz + * @version $Id$ + */ +public class FilterAction extends AbstractManagerAction { + static final long serialVersionUID = 5537508784388696503L; + + private String operation = "Add";//No other option other than Add at the moment. + private String filter; + + /** + * Creates a new FilterAction. + */ + public FilterAction() { + } + + /** + * Creates a new FilterAction with the filter specified + * + * @param filter the whitelist or blacklist filter to be added. + * @since ??? + */ + public FilterAction(String filter) { + this.filter = filter; + } + + /** + * Returns the name of this action, i.e. "Filter". + */ + @Override + public String getAction() { + return "Filter"; + } + + /** + * Returns the filter operation which is "Add" by default. + * + * @return the filter operation which is "Add" by default + */ + public String getOperation() { + return operation; + } + + /** + * Returns the filter. + * + * @return the filter. + */ + public String getFilter() { + return filter; + } + + /** + * Sets the filter. + * + * @param filter add the whitelist or blacklist event to be filtered. + */ + public void setFilter(String filter) { + this.filter = filter; + } + +} + diff --git a/src/main/java/org/asteriskjava/manager/action/GetConfigAction.java b/src/main/java/org/asteriskjava/manager/action/GetConfigAction.java index dbea4242a..e64de5148 100644 --- a/src/main/java/org/asteriskjava/manager/action/GetConfigAction.java +++ b/src/main/java/org/asteriskjava/manager/action/GetConfigAction.java @@ -28,16 +28,14 @@ * @since 0.3 */ @ExpectedResponse(GetConfigResponse.class) -public class GetConfigAction extends AbstractManagerAction -{ +public class GetConfigAction extends AbstractManagerAction { static final long serialVersionUID = 4753117770471622025L; private String filename; /** * Creates a new GetConfigAction. */ - public GetConfigAction() - { + public GetConfigAction() { } @@ -46,8 +44,7 @@ public GetConfigAction() * * @param filename the name of the file to get. */ - public GetConfigAction(String filename) - { + public GetConfigAction(String filename) { this.filename = filename; } @@ -55,24 +52,21 @@ public GetConfigAction(String filename) * Returns the name of this action, i.e. "GetConfig". */ @Override - public String getAction() - { + public String getAction() { return "GetConfig"; } /** * Returns the filename. */ - public String getFilename() - { + public String getFilename() { return filename; } /** * Sets filename. */ - public void setFilename(String filename) - { + public void setFilename(String filename) { this.filename = filename; } } diff --git a/src/main/java/org/asteriskjava/manager/action/GetVarAction.java b/src/main/java/org/asteriskjava/manager/action/GetVarAction.java index 17f988b5f..6d0f14727 100644 --- a/src/main/java/org/asteriskjava/manager/action/GetVarAction.java +++ b/src/main/java/org/asteriskjava/manager/action/GetVarAction.java @@ -42,7 +42,7 @@ * String value = response.getAttribute("Value"); * System.out.println("MY_VAR on " + channel + " is " + value); * - * Where c is an instance of + * Where c is an instance of * {@link org.asteriskjava.manager.ManagerConnection} and channel * contains the name of a channel instance, for example "SIP/1234-9cd". *

      @@ -52,13 +52,12 @@ *

      * Since Asterisk 1.4 this action also supports built-in functions like * DB(), CALLERID() and ENV(). - * + * * @author srt * @version $Id$ */ @ExpectedResponse(GetVarResponse.class) -public class GetVarAction extends AbstractManagerAction -{ +public class GetVarAction extends AbstractManagerAction { private static final long serialVersionUID = 5239805071977668779L; private String channel; private String variable; @@ -66,32 +65,29 @@ public class GetVarAction extends AbstractManagerAction /** * Creates a new empty GetVarAction. */ - public GetVarAction() - { + public GetVarAction() { } /** * Creates a new GetVarAction that queries for the given global variable. - * + * * @param variable the name of the global variable to query. * @since 0.2 */ - public GetVarAction(String variable) - { + public GetVarAction(String variable) { this.variable = variable; } /** * Creates a new GetVarAction that queries for the given local channel * variable. - * - * @param channel the name of the channel, for example "SIP/1234-9cd". + * + * @param channel the name of the channel, for example "SIP/1234-9cd". * @param variable the name of the variable to query. * @since 0.2 */ - public GetVarAction(String channel, String variable) - { + public GetVarAction(String channel, String variable) { this.channel = channel; this.variable = variable; } @@ -100,8 +96,7 @@ public GetVarAction(String channel, String variable) * Returns the name of this action, i.e. "GetVar". */ @Override - public String getAction() - { + public String getAction() { return "GetVar"; } @@ -109,36 +104,32 @@ public String getAction() * Returns the name of the channel if you query for a local channel variable * or null if it is a global variable. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel if you query for a local channel variable. * Leave empty to query for a global variable. - * + * * @param channel the channel if you query for a local channel variable or - * null to query for a gloabl variable. + * null to query for a gloabl variable. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Retruns the name of the variable to query. */ - public String getVariable() - { + public String getVariable() { return variable; } /** * Sets the name of the variable to query. */ - public void setVariable(String variable) - { + public void setVariable(String variable) { this.variable = variable; } } diff --git a/src/main/java/org/asteriskjava/manager/action/HangupAction.java b/src/main/java/org/asteriskjava/manager/action/HangupAction.java index dde0b24b8..84cdd34fe 100644 --- a/src/main/java/org/asteriskjava/manager/action/HangupAction.java +++ b/src/main/java/org/asteriskjava/manager/action/HangupAction.java @@ -16,19 +16,31 @@ */ package org.asteriskjava.manager.action; +import org.asteriskjava.manager.event.ChannelsHungupListComplete; +import org.asteriskjava.manager.event.ResponseEvent; + /** - * The HangupAction causes Asterisk to hang up a given channel.

      + * The HangupAction causes Asterisk to hang up a given channel. + *

      * Hangup with a cause code is only supported by Asterisk versions later than 1.6.2. + *

      + * If the provided channel is surrounded by {@code /forward slashes/}, Asterisk + * will interpret the value as a + * POSIX Extended Regular Expression (ERE), + * allowing multiple channels to be hung up at once. + *

      + * If you are passing a regular expression to this action, ensure that you also + * use one of the {@link org.asteriskjava.manager.ManagerConnection#sendEventGeneratingAction(EventGeneratingAction)} + * overloads to capture the response correctly. * * @author srt * @version $Id$ */ -public class HangupAction extends AbstractManagerAction -{ +public class HangupAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serializable version identifier */ - static final long serialVersionUID = 0L; + private static final long serialVersionUID = -7534073930283445113L; private String channel; private Integer cause; @@ -36,32 +48,29 @@ public class HangupAction extends AbstractManagerAction /** * Creates a new empty HangupAction. */ - public HangupAction() - { + public HangupAction() { } /** * Creates a new HangupAction that hangs up the given channel. * - * @param channel the name of the channel to hangup. + * @param channelOrRegex the name of the channel to hangup. * @since 0.2 */ - public HangupAction(String channel) - { - this.channel = channel; + public HangupAction(String channelOrRegex) { + this.channel = channelOrRegex; } /** * Creates a new HangupAction that hangs up the given channel with the given cause code. * - * @param channel the name of the channel to hangup. - * @param cause the cause code. The cause code must be >= 0 and <= 127. + * @param channelOrRegex the name of the channel to hangup. + * @param cause the cause code. The cause code must be >= 0 and <= 127. * @since 1.0.0 */ - public HangupAction(String channel, int cause) - { - this.channel = channel; + public HangupAction(String channelOrRegex, int cause) { + this.channel = channelOrRegex; this.cause = cause; } @@ -69,8 +78,7 @@ public HangupAction(String channel, int cause) * Returns the name of this action, i.e. "Hangup". */ @Override - public String getAction() - { + public String getAction() { return "Hangup"; } @@ -79,8 +87,7 @@ public String getAction() * * @return the name of the channel to hangup. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -90,8 +97,7 @@ public String getChannel() * * @param channel the name of the channel to hangup. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -101,20 +107,23 @@ public void setChannel(String channel) * @return the hangup cause. * @since 1.0.0 */ - public Integer getCause() - { + public Integer getCause() { return cause; } /** - * Sets the hangup cause. The cause code must be >= 0 and <= 127.

      + * Sets the hangup cause. The cause code must be >= 0 and <= 127.

      * This property is optional. * * @param cause the hangup cause. * @since 1.0.0 */ - public void setCause(Integer cause) - { + public void setCause(Integer cause) { this.cause = cause; } + + @Override + public Class getActionCompleteEventClass() { + return ChannelsHungupListComplete.class; + } } diff --git a/src/main/java/org/asteriskjava/manager/action/IaxPeerListAction.java b/src/main/java/org/asteriskjava/manager/action/IaxPeerListAction.java index 5bc5463ab..3463ce453 100644 --- a/src/main/java/org/asteriskjava/manager/action/IaxPeerListAction.java +++ b/src/main/java/org/asteriskjava/manager/action/IaxPeerListAction.java @@ -32,8 +32,7 @@ * @see org.asteriskjava.manager.event.PeerlistCompleteEvent * @since 1.0.0 */ -public class IaxPeerListAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class IaxPeerListAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serial version identifier. */ @@ -42,19 +41,16 @@ public class IaxPeerListAction extends AbstractManagerAction implements EventGen /** * Creates a new IaxPeersAction. */ - public IaxPeerListAction() - { + public IaxPeerListAction() { } @Override - public String getAction() - { + public String getAction() { return "IAXpeerlist"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return PeerlistCompleteEvent.class; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/JabberSendAction.java b/src/main/java/org/asteriskjava/manager/action/JabberSendAction.java index a90c42c9a..17bb9519f 100644 --- a/src/main/java/org/asteriskjava/manager/action/JabberSendAction.java +++ b/src/main/java/org/asteriskjava/manager/action/JabberSendAction.java @@ -24,8 +24,7 @@ * @version $Id$ * @since 1.0.0 */ -public class JabberSendAction extends AbstractManagerAction -{ +public class JabberSendAction extends AbstractManagerAction { private static final long serialVersionUID = 1L; private String jabber; @@ -35,8 +34,7 @@ public class JabberSendAction extends AbstractManagerAction /** * Creates a new JabberSendAction. */ - public JabberSendAction() - { + public JabberSendAction() { super(); } @@ -47,8 +45,7 @@ public JabberSendAction() * @param screenName the JID of the recipient. * @param message the message to send to the recipient. */ - public JabberSendAction(String jabber, String screenName, String message) - { + public JabberSendAction(String jabber, String screenName, String message) { this.jabber = jabber; this.screenName = screenName; this.message = message; @@ -58,13 +55,11 @@ public JabberSendAction(String jabber, String screenName, String message) * Returns the name of this action, i.e. "Ping". */ @Override - public String getAction() - { + public String getAction() { return "JabberSend"; } - public String getJabber() - { + public String getJabber() { return jabber; } @@ -73,13 +68,11 @@ public String getJabber() * * @param jabber the client or transport Asterisk uses to connect to Jabber. */ - public void setJabber(String jabber) - { + public void setJabber(String jabber) { this.jabber = jabber; } - public String getScreenName() - { + public String getScreenName() { return screenName; } @@ -88,13 +81,11 @@ public String getScreenName() * * @param screenName the JID of the recipient. */ - public void setScreenName(String screenName) - { + public void setScreenName(String screenName) { this.screenName = screenName; } - public String getMessage() - { + public String getMessage() { return message; } @@ -103,8 +94,7 @@ public String getMessage() * * @param message the message to send to the recipient. */ - public void setMessage(String message) - { + public void setMessage(String message) { this.message = message; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/ListCommandsAction.java b/src/main/java/org/asteriskjava/manager/action/ListCommandsAction.java index 2b55b4c7b..916324ff3 100644 --- a/src/main/java/org/asteriskjava/manager/action/ListCommandsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ListCommandsAction.java @@ -19,14 +19,13 @@ /** * The ListCommandsAction returns possible commands in the Manager interface. *

      - * Use the getAttributes method on the ManagerResponse for a map of commands and explanations. - * - * @see org.asteriskjava.manager.response.ManagerResponse#getAttributes() + * Use the getAttributes method on the ManagerResponse for a map of commands and explanations. + * * @author martins + * @see org.asteriskjava.manager.response.ManagerResponse#getAttributes() * @since 0.3 */ -public class ListCommandsAction extends AbstractManagerAction -{ +public class ListCommandsAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -35,8 +34,7 @@ public class ListCommandsAction extends AbstractManagerAction /** * Creates a new ListCommandsAction. */ - public ListCommandsAction() - { + public ListCommandsAction() { } @@ -44,8 +42,7 @@ public ListCommandsAction() * Returns the name of this action, i.e. "ListCommands". */ @Override - public String getAction() - { + public String getAction() { return "ListCommands"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/LocalOptimizeAwayAction.java b/src/main/java/org/asteriskjava/manager/action/LocalOptimizeAwayAction.java new file mode 100644 index 000000000..d307c53d5 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/LocalOptimizeAwayAction.java @@ -0,0 +1,76 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +/** + * LocalOptimizeAway action -- Optimize away a local channel when possible. + *

      + * Available since Asterisk 1.8 + * + * @author SYON Communications Inc. + */ +public class LocalOptimizeAwayAction extends AbstractManagerAction { + /** + * Serializable version identifier. + */ + private static final long serialVersionUID = 1L; + private String channel; + + /** + * Creates a new empty LocalOptimizeAwayAction. + */ + public LocalOptimizeAwayAction() { + + } + + /** + * Creates a new LocalOptimizeAwayAction with channel name. + * + * @param channel Name of the channel for clears the flag. + */ + public LocalOptimizeAwayAction(String channel) { + this.channel = channel; + } + + /** + * Returns the name of this action, i.e. "LocalOptimizeAway". + */ + @Override + public String getAction() { + return "LocalOptimizeAway"; + } + + /** + * Sets the name of the channel. + * + * @return Name of the channel for clears the flag. + */ + public String getChannel() { + return channel; + } + + /** + * Returns the name of tha channel. + * + * @param channel Name of the channel for clears the flag. + */ + public void setChannel(String channel) { + this.channel = channel; + } + +} + diff --git a/src/main/java/org/asteriskjava/manager/action/LoginAction.java b/src/main/java/org/asteriskjava/manager/action/LoginAction.java index 82e933ff8..0a9f61f39 100644 --- a/src/main/java/org/asteriskjava/manager/action/LoginAction.java +++ b/src/main/java/org/asteriskjava/manager/action/LoginAction.java @@ -23,14 +23,13 @@ * An unsuccessful login results in an ManagerError being received from the * server with a message set to "Authentication failed" and the socket being * closed by Asterisk. - * - * @see org.asteriskjava.manager.action.ChallengeAction - * @see org.asteriskjava.manager.response.ManagerError + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.ChallengeAction + * @see org.asteriskjava.manager.response.ManagerError */ -public class LoginAction extends AbstractManagerAction -{ +public class LoginAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -45,40 +44,37 @@ public class LoginAction extends AbstractManagerAction /** * Creates a new empty LoginAction. */ - public LoginAction() - { - + public LoginAction() { + } - + /** * Creates a new LoginAction that performs a cleartext login.

      * You should not use cleartext login if you are concerned about security, - * using {@see ChallengeAction} and login with a password hash instead. - * + * using {@link ChallengeAction} and login with a password hash instead. + * * @param username the username as configured in Asterisk's - * manager.conf - * @param secret the user's password as configured in Asterisk's - * manager.conf + * manager.conf + * @param secret the user's password as configured in Asterisk's + * manager.conf * @since 0.2 */ - public LoginAction(String username, String secret) - { + public LoginAction(String username, String secret) { this.username = username; this.secret = secret; } /** * Creates a new LoginAction that performs a login via challenge/response. - * + * * @param username the username as configured in Asterisk's - * manager.conf + * manager.conf * @param authType the digest alogrithm, must match the digest algorithm - * that was used with the corresponding ChallengeAction. - * @param key the hash of the user's password and the challenge + * that was used with the corresponding ChallengeAction. + * @param key the hash of the user's password and the challenge * @since 0.2 */ - public LoginAction(String username, String authType, String key) - { + public LoginAction(String username, String authType, String key) { this.username = username; this.authType = authType; this.key = key; @@ -86,21 +82,20 @@ public LoginAction(String username, String authType, String key) /** * Creates a new LoginAction that performs a login via challenge/response. - * + * * @param username the username as configured in Asterisk's - * manager.conf + * manager.conf * @param authType the digest alogrithm, must match the digest algorithm - * that was used with the corresponding ChallengeAction. - * @param key the hash of the user's password and the challenge - * @param events the event mask. Set to "on" if all events should be send, - * "off" if not events should be sent or a combination of - * "system", "call" and "log" (separated by ',') to specify what - * kind of events should be sent. + * that was used with the corresponding ChallengeAction. + * @param key the hash of the user's password and the challenge + * @param events the event mask. Set to "on" if all events should be send, + * "off" if not events should be sent or a combination of + * "system", "call" and "log" (separated by ',') to specify what + * kind of events should be sent. * @since 0.2 */ public LoginAction(String username, String authType, String key, - String events) - { + String events) { this.username = username; this.authType = authType; this.key = key; @@ -111,32 +106,28 @@ public LoginAction(String username, String authType, String key, * Returns the name of this action, i.e. "Login". */ @Override - public String getAction() - { + public String getAction() { return "Login"; } /** * Returns the username. */ - public String getUsername() - { + public String getUsername() { return username; } /** * Sets the username as configured in asterik's manager.conf. */ - public void setUsername(String username) - { + public void setUsername(String username) { this.username = username; } /** * Returns the secret. */ - public String getSecret() - { + public String getSecret() { return secret; } @@ -146,16 +137,14 @@ public String getSecret() * manager.conf.

      * The secret and key properties are mutually exclusive. */ - public void setSecret(String secret) - { + public void setSecret(String secret) { this.secret = secret; } /** * Returns the digest alogrithm when using challenge/response. */ - public String getAuthType() - { + public String getAuthType() { return authType; } @@ -165,47 +154,42 @@ public String getAuthType() * the user's password.

      * Currently Asterisk supports only "MD5". */ - public void setAuthType(String authType) - { + public void setAuthType(String authType) { this.authType = authType; } /** * @return Returns the key. */ - public String getKey() - { + public String getKey() { return key; } /** * @param key The key to set. */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } /** * Returns the event mask. - * + * * @return the event mask. */ - public String getEvents() - { + public String getEvents() { return events; } /** * Sets the event mask. - * + * * @param events the event mask. Set to "on" if all events should be send, - * "off" if not events should be sent or a combination of - * "system", "call" and "log" (separated by ',') to specify what - * kind of events should be sent. + * "off" if not events should be sent or a combination of + * "system", "call" and "log" (separated by ',') to specify what + * kind of events should be sent. */ - public void setEvents(String events) - { + public void setEvents(String events) { this.events = events; } } diff --git a/src/main/java/org/asteriskjava/manager/action/LogoffAction.java b/src/main/java/org/asteriskjava/manager/action/LogoffAction.java index c71063013..a5ef175af 100644 --- a/src/main/java/org/asteriskjava/manager/action/LogoffAction.java +++ b/src/main/java/org/asteriskjava/manager/action/LogoffAction.java @@ -18,12 +18,11 @@ /** * The LogoffAction causes the server to close the connection. - * + * * @author srt * @version $Id$ */ -public class LogoffAction extends AbstractManagerAction -{ +public class LogoffAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -32,8 +31,7 @@ public class LogoffAction extends AbstractManagerAction /** * Creates a new LogoffAction. */ - public LogoffAction() - { + public LogoffAction() { } @@ -41,8 +39,7 @@ public LogoffAction() * Returns the name of this action, i.e. "Logoff". */ @Override - public String getAction() - { + public String getAction() { return "Logoff"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/MWIDeleteAction.java b/src/main/java/org/asteriskjava/manager/action/MWIDeleteAction.java new file mode 100644 index 000000000..646f95a4a --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/MWIDeleteAction.java @@ -0,0 +1,48 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +public class MWIDeleteAction extends AbstractManagerAction { + static final long serialVersionUID = 1L; + private String mailbox; + + /** + * Creates a new MWIDeleteAction. + */ + public MWIDeleteAction() { + + } + + public MWIDeleteAction(String mailbox) { + this.mailbox = mailbox; + + } + + public String getMailbox() { + return mailbox; + } + + public void setMailbox(String mailbox) { + this.mailbox = mailbox; + } + + @Override + public String getAction() { + return "MWIDelete"; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/action/MWIUpdateAction.java b/src/main/java/org/asteriskjava/manager/action/MWIUpdateAction.java new file mode 100644 index 000000000..a9adfe154 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/MWIUpdateAction.java @@ -0,0 +1,68 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +public class MWIUpdateAction extends AbstractManagerAction { + static final long serialVersionUID = 1L; + private String mailbox; + private int oldMessages; + private int newMessages; + + /** + * Creates a new MWIUpdateAction. + */ + public MWIUpdateAction() { + + } + + public MWIUpdateAction(String mailbox, int oldMessages, int newMessages) { + this.mailbox = mailbox; + this.oldMessages = oldMessages; + this.newMessages = newMessages; + + } + + public String getMailbox() { + return mailbox; + } + + public void setMailbox(String mailbox) { + this.mailbox = mailbox; + } + + public int getOldMessages() { + return oldMessages; + } + + public void setOldMessages(int oldMessages) { + this.oldMessages = oldMessages; + } + + public int getNewMessages() { + return newMessages; + } + + public void setNewMessages(int newMessages) { + this.newMessages = newMessages; + } + + @Override + public String getAction() { + return "MWIUpdate"; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/action/MailboxCountAction.java b/src/main/java/org/asteriskjava/manager/action/MailboxCountAction.java index 12fed592a..7a2bb7e84 100644 --- a/src/main/java/org/asteriskjava/manager/action/MailboxCountAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MailboxCountAction.java @@ -18,8 +18,7 @@ * @see org.asteriskjava.manager.response.MailboxCountResponse */ @ExpectedResponse(MailboxCountResponse.class) -public class MailboxCountAction extends AbstractManagerAction -{ +public class MailboxCountAction extends AbstractManagerAction { static final long serialVersionUID = -6900421919824575941L; private String mailbox; @@ -27,8 +26,7 @@ public class MailboxCountAction extends AbstractManagerAction /** * Creates a new empty MailboxCountAction. */ - public MailboxCountAction() - { + public MailboxCountAction() { } @@ -42,8 +40,7 @@ public MailboxCountAction() * "default" is assumed. * @since 0.2 */ - public MailboxCountAction(String mailbox) - { + public MailboxCountAction(String mailbox) { this.mailbox = mailbox; } @@ -51,16 +48,14 @@ public MailboxCountAction(String mailbox) * Returns the name of this action, i.e. "MailboxCount". */ @Override - public String getAction() - { + public String getAction() { return "MailboxCount"; } /** * Returns the name of the mailbox to query. */ - public String getMailbox() - { + public String getMailbox() { return mailbox; } @@ -70,8 +65,7 @@ public String getMailbox() * mailboxnumber@context.If no context is specified "default" is assumed.

      * This property is mandatory. */ - public void setMailbox(String mailbox) - { + public void setMailbox(String mailbox) { this.mailbox = mailbox; } } diff --git a/src/main/java/org/asteriskjava/manager/action/MailboxStatusAction.java b/src/main/java/org/asteriskjava/manager/action/MailboxStatusAction.java index e567ae4fc..a9091058d 100644 --- a/src/main/java/org/asteriskjava/manager/action/MailboxStatusAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MailboxStatusAction.java @@ -28,8 +28,7 @@ * @see org.asteriskjava.manager.response.MailboxStatusResponse */ @ExpectedResponse(MailboxStatusResponse.class) -public class MailboxStatusAction extends AbstractManagerAction -{ +public class MailboxStatusAction extends AbstractManagerAction { static final long serialVersionUID = -3845028207155711950L; private String mailbox; @@ -37,8 +36,7 @@ public class MailboxStatusAction extends AbstractManagerAction /** * Creates a new empty MailboxStatusAction. */ - public MailboxStatusAction() - { + public MailboxStatusAction() { } @@ -52,8 +50,7 @@ public MailboxStatusAction() * "default" is assumed. * @since 0.2 */ - public MailboxStatusAction(String mailbox) - { + public MailboxStatusAction(String mailbox) { this.mailbox = mailbox; } @@ -61,16 +58,14 @@ public MailboxStatusAction(String mailbox) * Returns the name of this action, i.e. "MailboxStatus". */ @Override - public String getAction() - { + public String getAction() { return "MailboxStatus"; } /** * Returns the name of the mailbox to query. */ - public String getMailbox() - { + public String getMailbox() { return mailbox; } @@ -84,8 +79,7 @@ public String getMailbox() * This property is mandatory.

      * Example: "1234,1235@mycontext" */ - public void setMailbox(String mailbox) - { + public void setMailbox(String mailbox) { this.mailbox = mailbox; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ManagerAction.java b/src/main/java/org/asteriskjava/manager/action/ManagerAction.java index 83ee2a6e6..93c578dab 100644 --- a/src/main/java/org/asteriskjava/manager/action/ManagerAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ManagerAction.java @@ -27,12 +27,11 @@ * engine.

      * There is one conrete subclass of ManagerAction per each supported Asterisk * Action. - * + * * @author srt * @version $Id$ */ -public interface ManagerAction extends Serializable -{ +public interface ManagerAction extends Serializable { /** * Returns the name of the action for example "Hangup". */ @@ -40,7 +39,7 @@ public interface ManagerAction extends Serializable /** * Returns the action id. - * + * * @return the user provied action id. */ String getActionId(); @@ -51,14 +50,14 @@ public interface ManagerAction extends Serializable * returned by the Asterisk server will include the same id. This way * the action id can be used to track actions and their corresponding * responses and response events.

      - * Note that Asterisk-Java uses its own internal action id to match + * Note that Asterisk-Java uses its own internal action id to match * actions with the corresponding responses and events. Though the internal - * action is never exposed to the application code. So if you want to + * action is never exposed to the application code. So if you want to * handle reponses or response events on your own your application must * set a unique action id using this method otherwise the action id of * the reponse and response event objects passed to your application * will be null. - * + * * @param actionId the user provided action id to set. * @see org.asteriskjava.manager.response.ManagerResponse#getActionId() * @see org.asteriskjava.manager.event.ResponseEvent#getActionId() diff --git a/src/main/java/org/asteriskjava/manager/action/MeetMeMuteAction.java b/src/main/java/org/asteriskjava/manager/action/MeetMeMuteAction.java index ff607beab..28ff55fbc 100644 --- a/src/main/java/org/asteriskjava/manager/action/MeetMeMuteAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MeetMeMuteAction.java @@ -20,12 +20,11 @@ * The MeetMeMuteAction mutes a user in a conference.

      * Defined in apps/app_meetme.c

      * Available since Asterisk 1.4. - * + * * @author srt * @version $Id$ */ -public class MeetMeMuteAction extends AbstractMeetMeMuteAction -{ +public class MeetMeMuteAction extends AbstractMeetMeMuteAction { /** * Serializable version identifier */ @@ -34,19 +33,17 @@ public class MeetMeMuteAction extends AbstractMeetMeMuteAction /** * Creates a new empty MeetMeMuteAction. */ - public MeetMeMuteAction() - { + public MeetMeMuteAction() { super(); } /** * Creates a new MeetMeMuteAction. - * - * @param meetMe the conference number. + * + * @param meetMe the conference number. * @param userNum the index of the user in the conference. */ - public MeetMeMuteAction(String meetMe, Integer userNum) - { + public MeetMeMuteAction(String meetMe, Integer userNum) { super(meetMe, userNum); } @@ -54,8 +51,7 @@ public MeetMeMuteAction(String meetMe, Integer userNum) * Returns the name of this action, i.e. "MeetMeMute". */ @Override - public String getAction() - { + public String getAction() { return "MeetMeMute"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/MeetMeUnmuteAction.java b/src/main/java/org/asteriskjava/manager/action/MeetMeUnmuteAction.java index 6fa44a1f9..96137e241 100644 --- a/src/main/java/org/asteriskjava/manager/action/MeetMeUnmuteAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MeetMeUnmuteAction.java @@ -20,12 +20,11 @@ * The MeetMeUnmuteAction unmutes a user in a conference.

      * Defined in apps/app_meetme.c

      * Available since Asterisk 1.4. - * + * * @author srt * @version $Id$ */ -public class MeetMeUnmuteAction extends AbstractMeetMeMuteAction -{ +public class MeetMeUnmuteAction extends AbstractMeetMeMuteAction { /** * Serializable version identifier */ @@ -34,19 +33,17 @@ public class MeetMeUnmuteAction extends AbstractMeetMeMuteAction /** * Creates a new empty MeetMeUnmuteAction. */ - public MeetMeUnmuteAction() - { + public MeetMeUnmuteAction() { super(); } /** * Creates a new MeetMeUnmuteAction. - * - * @param meetMe the conference number. + * + * @param meetMe the conference number. * @param userNum the index of the user in the conference. */ - public MeetMeUnmuteAction(String meetMe, Integer userNum) - { + public MeetMeUnmuteAction(String meetMe, Integer userNum) { super(meetMe, userNum); } @@ -54,8 +51,7 @@ public MeetMeUnmuteAction(String meetMe, Integer userNum) * Returns the name of this action, i.e. "MeetMeUnmute". */ @Override - public String getAction() - { + public String getAction() { return "MeetMeUnmute"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/MessageSendAction.java b/src/main/java/org/asteriskjava/manager/action/MessageSendAction.java new file mode 100644 index 000000000..b13218c65 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/MessageSendAction.java @@ -0,0 +1,137 @@ +package org.asteriskjava.manager.action; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Send a custom SIP message to the specified peer. Available since Asterisk 11 + * + * @author Michael Will + * @version $Id$ + * @since 1.0.0 + */ +public class MessageSendAction extends AbstractManagerAction { + + private static final long serialVersionUID = -6554282385166411723L; + private String to; + private String from; + private String body; + private String base64body; + private Map variables; + + @Override + public String getAction() { + return "MessageSend"; + } + + /** + * Returns the variables to set on the originated call. + * + * @return a Map containing the variable names as key and their values as + * value. + * @since 1.0.0 + */ + public Map getVariables() { + return variables; + } + + /** + * Sets an variable on the originated call. + * + * @param name the name of the variable to set. + * @param value the value of the variable to set. + * @since 1.0.0 + */ + public void setVariable(String name, String value) { + if (variables == null) { + variables = new LinkedHashMap<>(); + } + + variables.put(name, value); + } + + /** + * Retrives destination of message + * + * @return String in format like sip:userid + */ + public String getTo() { + return to; + } + + /** + * Set destination of message + * + * @param to String in format like sip:userid + */ + public void setTo(String to) { + this.to = to; + } + + /** + * get From String + * + * @return String in form like sip:asterisk@server-ip + */ + public String getFrom() { + return from; + } + + /** + * set From String + * + * @param String from in form like sip:asterisk@server-ip + */ + public void setFrom(String from) { + this.from = from; + } + + /** + * Content of the message in plain text ascii + * Please consider to use getBase64Body instead to avoid encoding problems + * + * @return String with Message content + */ + public String getBody() { + return body; + } + + /** + * Sets the content of the message + * Please consider to use setBase64Body instead to avoid encoding problems + * + * @param body String with plain ascii content + */ + public void setBody(String body) { + this.body = body; + } + + /** + * Retrieves content encoded in base64 + * + * @return Base64 encoded String + * @code new String(Base64.decode(getBase64body(), Formatting (for ex "UTF-8")) + */ + public String getBase64body() { + return base64body; + } + + /** + * Sets the content of the message body encode in base64 + *

      + * {@code MessageSendAction sipSendMessage = new MessageSendAction(); + * sipSendMessage.setTo("sip:phoneuserid"); + * sipSendMessage.setVariable("Content-Type", "text/plain"); + * sipSendMessage.setVariable("P-hint", "usrloc applied"); + *

      + * sipSendMessage.setActionId(UUID.randomUUID().toString()); + * sipSendMessage.setBase64body(new String(Base64.encodeBase64(message.getBytes("UTF-8")), "UTF-8")); + * } + * + * @param base64body + */ + public void setBase64body(String base64body) { + this.base64body = base64body; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/action/MixMonitorAction.java b/src/main/java/org/asteriskjava/manager/action/MixMonitorAction.java new file mode 100644 index 000000000..fa7bc94c5 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/MixMonitorAction.java @@ -0,0 +1,188 @@ +/* + * Copyright 2018 CallShaper, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +import org.asteriskjava.manager.ExpectedResponse; +import org.asteriskjava.manager.response.MixMonitorResponse; + +/** + * Start a MixMonitor on the specified channel. + *

      + * Available since Asterisk 11 + * + * @see org.asteriskjava.manager.response.MixMonitorResponse + * @see StopMixMonitorAction + * @see PauseMixMonitorAction + * @see MixMonitorMuteAction + */ +@ExpectedResponse(MixMonitorResponse.class) +public class MixMonitorAction extends AbstractManagerAction { + private static final long serialVersionUID = 1L; + private String channel; + private String file; + private String options; + private String command; + + /** + * Creates a new empty MixMonitorAction + */ + public MixMonitorAction() { + super(); + } + + /** + * Creates a new MixMonitorAction that starts monitoring the given channel + * using a default filename. + * + * @param channel the name of the channel to monitor + */ + public MixMonitorAction(String channel) { + this(channel, null, null, null); + } + + /** + * Creates a new MixMonitorAction that starts monitoring the given channel + * with the specified filename. + * + * @param channel the name of the channel to monitor + * @param filename the filename to use for the recording + */ + public MixMonitorAction(String channel, String filename) { + this(channel, filename, null, null); + } + + /** + * Creates a new MixMonitorAction with options that starts monitoring the + * given channel with the specified filename. + * + * @param channel the name of the channel to monitor + * @param filename the filename to use for the recording + * @param options the MixMonitor options to use when starting the recording + */ + public MixMonitorAction(String channel, String filename, String options) { + this(channel, filename, options, null); + } + + /** + * Creates a new MixMonitorAction with options that starts monitoring the + * given channel with the specified filename. Also takes a command to + * execute when the recording has ended. + *

      + * The {@code command} option has been available since Asterisk 12 + * + * @param channel the name of the channel to monitor + * @param filename the filename to use for the recording + * @param options the MixMonitor options to use when starting the recording + * @param command the command to execute when the recording is complete + */ + public MixMonitorAction(String channel, String filename, String options, String command) { + this.channel = channel; + this.file = filename; + this.options = options; + this.command = command; + } + + /** + * Returns the name of this action, i.e. "MixMonitor" + * + * @return the name of the AMI action that this class implements + */ + @Override + public String getAction() { + return "MixMonitor"; + } + + /** + * Returns the name of the Asterisk channel to monitor. + * + * @return the Asterisk channel name + */ + public String getChannel() { + return channel; + } + + /** + * Sets the name of the Asterisk channel to the given value. + * + * @param channel the Asterisk channel name + */ + public void setChannel(String channel) { + this.channel = channel; + } + + /** + * Returns the filename that Asterisk will use when saving the recording. + * + * @return the recording filename + */ + public String getFile() { + return file; + } + + /** + * Sets the filename that Asterisk will use when saving the recording. + * + * @param filename the recording filename + */ + public void setFile(String filename) { + this.file = filename; + } + + /** + * Gets the options that are passed to MixMonitor. + * + * @return the MixMonitor options + */ + public String getOptions() { + return options; + } + + /** + * Sets the options that are passed to MixMonitor. These should be + * specified in the same format you would use if you were invoking + * the MixMonitor dialplan application. + * + * @param options the MixMonitor options + */ + public void setOptions(String options) { + this.options = options; + } + + /** + * Get the command to be executed when the MixMonitor recording has + * ended. + *

      + * Available since Asterisk 12 + * + * @return the command to execute + */ + public String getCommand() { + return command; + } + + /** + * Sets the command to be executed when the MixMonitor recording has + * ended. + *

      + * Available since Asterisk 12 + * + * @param command the command to execute + */ + public void setCommand(String command) { + this.command = command; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/MixMonitorMuteAction.java b/src/main/java/org/asteriskjava/manager/action/MixMonitorMuteAction.java new file mode 100644 index 000000000..1110c239c --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/MixMonitorMuteAction.java @@ -0,0 +1,144 @@ +/* + * Copyright 2012 Stefan Reuter. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.action; + +/** + * MixMonitorMute can be used to mute and un-mute an existing recording. + * + * @author Bob Wienholt + * @version $Id$ + */ +public class MixMonitorMuteAction extends AbstractManagerAction { + private static final long serialVersionUID = 1L; + private String channel; + private String direction; + private Integer state; + + /** + * Creates a new empty MixMonitorMuteAction + */ + public MixMonitorMuteAction() { + super(); + } + + /** + * Mutes the monitor on the given channel. + * + * @param channel + */ + public MixMonitorMuteAction(String channel) { + super(); + this.channel = channel; + } + + /** + * Mutes the monitor on the given channel for the given portion + * of the call. + * + * @param channel + * @param direction + */ + public MixMonitorMuteAction(String channel, String direction) { + super(); + this.channel = channel; + this.direction = direction; + } + + /** + * Either mutes or un-mutes the monitor on the given channel for + * the given portion of the call. + * + * @param channel + * @param direction + * @param state + */ + public MixMonitorMuteAction(String channel, String direction, Integer state) { + super(); + this.channel = channel; + this.direction = direction; + this.state = state; + } + + /** + * Either mutes or un-mutes the monitor on the given channel. + * + * @param channel + * @param state + */ + public MixMonitorMuteAction(String channel, Integer state) { + super(); + this.channel = channel; + this.state = state; + } + + /** + * Returns the name of this action. + */ + @Override + public String getAction() { + return "MixMonitorMute"; + } + + /** + * Returns the name of the channel to mute. + */ + public String getChannel() { + return channel; + } + + /** + * Sets the name of the channel to mute. + * + * @param channel + */ + public void setChannel(String channel) { + this.channel = channel; + } + + /** + * Gets the direction of the part of the recording to mute. + */ + public String getDirection() { + return direction; + } + + /** + * Sets the direction of the part of the recording to mute. + * Can be one of: read, write, or both. Defaults to both. + * + * @param direction + */ + public void setDirection(String direction) { + this.direction = direction; + } + + /** + * Gets the state of the mute. + */ + public Integer getState() { + return state; + } + + /** + * Sets the state of the mute operation. 1 = on, 0 = off. + * + * @param state + */ + public void setState(Integer state) { + this.state = state; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/action/ModuleCheckAction.java b/src/main/java/org/asteriskjava/manager/action/ModuleCheckAction.java index 8822b4582..3c368d3aa 100644 --- a/src/main/java/org/asteriskjava/manager/action/ModuleCheckAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ModuleCheckAction.java @@ -31,8 +31,7 @@ * @since 1.0.0 */ @ExpectedResponse(ModuleCheckResponse.class) -public class ModuleCheckAction extends AbstractManagerAction -{ +public class ModuleCheckAction extends AbstractManagerAction { static final long serialVersionUID = 1L; private String module; @@ -40,8 +39,7 @@ public class ModuleCheckAction extends AbstractManagerAction /** * Creates a new ModuleCheckAction. */ - public ModuleCheckAction() - { + public ModuleCheckAction() { } @@ -50,8 +48,7 @@ public ModuleCheckAction() * * @param module the name of the module (including or not including the ".so" extension). */ - public ModuleCheckAction(String module) - { + public ModuleCheckAction(String module) { this.module = module; } @@ -59,8 +56,7 @@ public ModuleCheckAction(String module) * Returns the name of this action, i.e. "ModuleLoad". */ @Override - public String getAction() - { + public String getAction() { return "ModuleCheck"; } @@ -69,8 +65,7 @@ public String getAction() * * @return the name of the module to check. */ - public String getModule() - { + public String getModule() { return module; } @@ -79,8 +74,7 @@ public String getModule() * * @param module the name of the module (including or not including the ".so" extension) to check. */ - public void setModule(String module) - { + public void setModule(String module) { this.module = module; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/ModuleLoadAction.java b/src/main/java/org/asteriskjava/manager/action/ModuleLoadAction.java index 0d92b99cf..632b28bff 100644 --- a/src/main/java/org/asteriskjava/manager/action/ModuleLoadAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ModuleLoadAction.java @@ -24,8 +24,7 @@ * @version $Id$ * @since 1.0.0 */ -public class ModuleLoadAction extends AbstractManagerAction -{ +public class ModuleLoadAction extends AbstractManagerAction { static final long serialVersionUID = 1L; public static final String SUBSYSTEM_CDR = "cdr"; @@ -46,8 +45,7 @@ public class ModuleLoadAction extends AbstractManagerAction /** * Creates a new ModuleLoadAction. */ - public ModuleLoadAction() - { + public ModuleLoadAction() { } @@ -59,8 +57,7 @@ public ModuleLoadAction() * to reload all modules. * @param loadType the operation to perform ("load", "unload" or "reload"). */ - public ModuleLoadAction(String module, String loadType) - { + public ModuleLoadAction(String module, String loadType) { this.module = module; this.loadType = loadType; } @@ -69,8 +66,7 @@ public ModuleLoadAction(String module, String loadType) * Returns the name of this action, i.e. "ModuleLoad". */ @Override - public String getAction() - { + public String getAction() { return "ModuleLoad"; } @@ -79,8 +75,7 @@ public String getAction() * * @return the name of the module or subsystem to perform the operation on. */ - public String getModule() - { + public String getModule() { return module; } @@ -99,8 +94,7 @@ public String getModule() * @see #SUBSYSTEM_RTP * @see #SUBSYSTEM_HTTP */ - public void setModule(String module) - { + public void setModule(String module) { this.module = module; } @@ -109,8 +103,7 @@ public void setModule(String module) * * @return the operation to perform. */ - public String getLoadType() - { + public String getLoadType() { return loadType; } @@ -122,8 +115,7 @@ public String getLoadType() * @see #LOAD_TYPE_UNLOAD * @see #LOAD_TYPE_RELOAD */ - public void setLoadType(String loadType) - { + public void setLoadType(String loadType) { this.loadType = loadType; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/MonitorAction.java b/src/main/java/org/asteriskjava/manager/action/MonitorAction.java index ba8416771..dfd47f6f2 100644 --- a/src/main/java/org/asteriskjava/manager/action/MonitorAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MonitorAction.java @@ -19,12 +19,11 @@ /** * The MonitorAction starts monitoring (recording) a channel.

      * It is implemented in res/res_monitor.c - * + * * @author srt * @version $Id$ */ -public class MonitorAction extends AbstractManagerAction -{ +public class MonitorAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -37,8 +36,7 @@ public class MonitorAction extends AbstractManagerAction /** * Creates a new empty MonitorAction. */ - public MonitorAction() - { + public MonitorAction() { super(); } @@ -46,14 +44,13 @@ public MonitorAction() * Creates a new MonitorAction that starts monitoring the given channel and * writes voice data to the given files.

      * The format of the files is "wav", they are not mixed. - * + * * @param channel the name of the channel to monitor - * @param file the (base) name of the files to which the voice data is - * written + * @param file the (base) name of the files to which the voice data is + * written * @since 0.2 */ - public MonitorAction(String channel, String file) - { + public MonitorAction(String channel, String file) { super(); this.channel = channel; this.file = file; @@ -63,15 +60,14 @@ public MonitorAction(String channel, String file) * Creates a new MonitorAction that starts monitoring the given channel and * writes voice data to the given files.

      * The files are not mixed. - * + * * @param channel the name of the channel to monitor - * @param file the (base) name of the files to which the voice data is - * written - * @param format the format to use for encoding the voice files + * @param file the (base) name of the files to which the voice data is + * written + * @param format the format to use for encoding the voice files * @since 0.2 */ - public MonitorAction(String channel, String file, String format) - { + public MonitorAction(String channel, String file, String format) { super(); this.channel = channel; this.file = file; @@ -81,17 +77,16 @@ public MonitorAction(String channel, String file, String format) /** * Creates a new MonitorAction that starts monitoring the given channel and * writes voice data to the given file(s). - * + * * @param channel the name of the channel to monitor - * @param file the (base) name of the file(s) to which the voice data is - * written - * @param format the format to use for encoding the voice files - * @param mix true if the two voice files should be joined at the end of the - * call + * @param file the (base) name of the file(s) to which the voice data is + * written + * @param format the format to use for encoding the voice files + * @param mix true if the two voice files should be joined at the end of the + * call * @since 0.2 */ - public MonitorAction(String channel, String file, String format, Boolean mix) - { + public MonitorAction(String channel, String file, String format, Boolean mix) { super(); this.channel = channel; this.file = file; @@ -103,16 +98,14 @@ public MonitorAction(String channel, String file, String format, Boolean mix) * Returns the name of this action, i.e. "Monitor". */ @Override - public String getAction() - { + public String getAction() { return "Monitor"; } /** * Returns the name of the channel to monitor. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -120,16 +113,14 @@ public String getChannel() * Sets the name of the channel to monitor.

      * This property is mandatory. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the name of the file to which the voice data is written. */ - public String getFile() - { + public String getFile() { return file; } @@ -138,16 +129,14 @@ public String getFile() * If this property is not set it defaults to to the channel name as per CLI * with the '/' replaced by '-'. */ - public void setFile(String file) - { + public void setFile(String file) { this.file = file; } /** * Returns the format to use for encoding the voice files. */ - public String getFormat() - { + public String getFormat() { return format; } @@ -155,8 +144,7 @@ public String getFormat() * Sets the format to use for encoding the voice files.

      * If this property is not set it defaults to "wav". */ - public void setFormat(String format) - { + public void setFormat(String format) { this.format = format; } @@ -164,8 +152,7 @@ public void setFormat(String format) * Returns true if the two voice files should be joined at the end of the * call. */ - public Boolean getMix() - { + public Boolean getMix() { return mix; } @@ -173,8 +160,7 @@ public Boolean getMix() * Set to true if the two voice files should be joined at the end of the * call. */ - public void setMix(Boolean mix) - { + public void setMix(Boolean mix) { this.mix = mix; } } diff --git a/src/main/java/org/asteriskjava/manager/action/MuteAudioAction.java b/src/main/java/org/asteriskjava/manager/action/MuteAudioAction.java new file mode 100644 index 000000000..0b49c16b0 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/MuteAudioAction.java @@ -0,0 +1,155 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +/** + * Action: MuteAudio Synopsis: Mute an audio stream Privilege: system,all + * Description: Mute an incoming or outbound audio stream in a channel. + * Variables: Channel: The channel you want to mute. Direction: in | out + * |all The stream you want to mute. State: on | off Whether to turn mute on or + * off. ActionID: Optional action ID for this AMI transaction. + *

      + * It is defined in res/res_mutestream.c. + *

      + * Available since Asterisk 1.8 + * + * @author sbs + * @version $Id: MuteAction.java 938 2007-12-31 03:23:38Z srt $ + * @since 1.0.0 + */ +public class MuteAudioAction extends AbstractManagerAction { + /** + * Serializable version identifier. + */ + private static final long serialVersionUID = 0L; + + private String channel; + + /** + * The audio direct (relative to the pbx) which is to be muted. + */ + public enum Direction { + IN("in"), OUT("out"), ALL("all"); + + String value; + + Direction(String value) { + this.value = value; + } + + public String toString() { + return this.value; + } + } + + private Direction direction; + + /** + * Controls whether to mute (on) or unmute (off) the call + **/ + public enum State { + MUTE("on"), UNMUTE("off"); //$NON-NLS-1$//$NON-NLS-2$ + + String value; + + State(String value) { + this.value = value; + } + + public String toString() { + return this.value; + } + + } + + private State state; + + /** + * Creates a new empty MuteAction. + */ + public MuteAudioAction() { + + } + + /** + * Creates a new MuteAction that Mutes or Unmutes the two given channel. + * + * @param channel the name of the channel to Mute. + * @param direction the audio direction which is to be muted/unmuted + * @param state controls whether we are muting or unmuting the channel. + */ + + public MuteAudioAction(String channel, Direction direction, State state) { + this.channel = channel; + this.direction = direction; + this.state = state; + } + + /** + * Returns the name of this action, i.e. "MuteAudio". + */ + @Override + public String getAction() { + return "MuteAudio"; //$NON-NLS-1$ + } + + /** + * Returns the name of the channel to monitor. + */ + public String getChannel() { + return this.channel; + } + + /** + * Returns the audio direction which is to be muted/unmuted. + */ + public Direction getDirection() { + return this.direction; + } + + /** + * Returns the state controls whether we are muting or unmuting the channel. + */ + public State getState() { + return this.state; + } + + /** + * Sets the name of the channel to monitor.

      + * This property is mandatory. + */ + public void setChannel(String channel) { + this.channel = channel; + } + + /** + * Sets the audio direction which is to be muted/unmuted.

      + * This property is mandatory. + */ + public void setDirection(Direction direction) { + this.direction = direction; + } + + /** + * Sets the state controls whether we are muting or unmuting the channel.

      + * This property is mandatory. + */ + public void setState(State state) { + this.state = state; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/action/OriginateAction.java b/src/main/java/org/asteriskjava/manager/action/OriginateAction.java index ed94d43dd..964e2b77e 100644 --- a/src/main/java/org/asteriskjava/manager/action/OriginateAction.java +++ b/src/main/java/org/asteriskjava/manager/action/OriginateAction.java @@ -18,22 +18,26 @@ import org.asteriskjava.manager.event.OriginateResponseEvent; import org.asteriskjava.manager.event.ResponseEvent; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; import java.util.*; - /** * The OriginateAction generates an outgoing call to the extension in the given * context with the given priority or to a given application with optional - * parameters.

      + * parameters. + *

      * If you want to connect to an extension use the properties context, exten and * priority. If you want to connect to an application use the properties * application and data if needed. Note that no call detail record will be * written when directly connecting to an application, so it may be better to - * connect to an extension that starts the application you wish to connect to.

      + * connect to an extension that starts the application you wish to connect to. + *

      * The response to this action is sent when the channel has been answered and * asterisk starts connecting it to the given extension. So be careful not to - * choose a too short timeout when waiting for the response.

      + * choose a too short timeout when waiting for the response. + *

      * If you set async to true Asterisk reports an OriginateSuccess- * and OriginateFailureEvents. The action id of these events equals the action * id of this OriginateAction. @@ -42,8 +46,10 @@ * @version $Id$ * @see org.asteriskjava.manager.event.OriginateResponseEvent */ -public class OriginateAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class OriginateAction extends AbstractManagerAction implements EventGeneratingAction { + + private final Log logger = LogFactory.getLog(getClass()); + /** * Serializable version identifier */ @@ -62,6 +68,14 @@ public class OriginateAction extends AbstractManagerAction implements EventGener private String data; private Boolean async; private String codecs; + private Boolean earlyMedia; + + private String channelId; + private String otherChannelId; + + // starting at ten saves on a formatter. + private int headerCounter = 10; + private Set preventDuplicateSipHeaders = new HashSet<>(); /** * Returns the name of this action, i.e. "Originate". @@ -69,8 +83,7 @@ public class OriginateAction extends AbstractManagerAction implements EventGener * @return the name of this action. */ @Override - public String getAction() - { + public String getAction() { return "Originate"; } @@ -79,65 +92,69 @@ public String getAction() * * @return the account code to use for the originated call. */ - public String getAccount() - { + public String getAccount() { return account; } /** - * Sets the account code to use for the originated call.

      + * Sets the account code to use for the originated call. + *

      * The account code is included in the call detail record generated for this * call and will be used for billing. * * @param account the account code to use for the originated call. */ - public void setAccount(String account) - { + public void setAccount(String account) { this.account = account; } /** * Returns the caller id to set on the outgoing channel. */ - public String getCallerId() - { + public String getCallerId() { return callerId; } /** - * Sets the caller id to set on the outgoing channel.

      + * Sets the caller id to set on the outgoing channel. + *

      * This includes both the Caller*Id Number and Caller*Id Name in the form * "Jon Doe <1234>". * * @param callerId the caller id to set on the outgoing channel. */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } /** - * Returns the calling presentation for the outgoing channel.

      + * Returns the calling presentation for the outgoing channel. + *

      * This property is only available on BRIstuffed Asterisk servers. * * @return the calling presentation for the outgoing channel. * @see #setCallingPres(Integer) */ - public Integer getCallingPres() - { + public Integer getCallingPres() { return callingPres; } /** - * Sets the calling presentation for the outgoing channel.

      - * The number is an octet and the only bits you need worry about are bits 1,2,6 and 7.

      + * Sets the calling presentation for the outgoing channel. + *

      + * The number is an octet and the only bits you need worry about are bits + * 1,2,6 and 7. + *

      * Bits 1 and 2 define the screening indicator and bits 6 and 7 define the - * presentation indicator.

      - * In essence, it says, 'Is the person who has been called allowed to see the callers number?' - * (presentation) and 'What authority was used to verify that this is a genuine number?' - * (screening).

      - *

      + * presentation indicator. + *

      + * In essence, it says, 'Is the person who has been called allowed to see + * the callers number?' (presentation) and 'What authority was used to + * verify that this is a genuine number?' (screening). + *

      + *
      * Presentation indicator (Bits 6 and 7): + * *

            * Bits Meaning
            *  7 6
      @@ -146,7 +163,9 @@ public Integer getCallingPres()
            *  1 0 Number not available due to interworking
            *  1 1 Reserved
            * 
      + *

      * Screening indicator (Bits 1 and 2): + * *

            * Bits Meaning
            *  2 1
      @@ -155,80 +174,78 @@ public Integer getCallingPres()
            *  1 0 User-provided, verified and failed
            *  1 1 Network provided
            * 
      + *

      * Examples for some general settings: + * *

            * Presentation Allowed, Network Provided: 3 (00000011)
            * Presentation Restricted, User-provided, not screened: 32 (00100000)
            * Presentation Restricted, User-provided, verified, and passed: 33 (00100001)
            * Presentation Restricted, Network Provided: 35 (00100011)
            * 
      + *

      * This property is only available on BRIstuffed Asterisk servers. * * @param callingPres the calling presentation for the outgoing channel. */ - public void setCallingPres(Integer callingPres) - { + public void setCallingPres(Integer callingPres) { this.callingPres = callingPres; } /** * Returns the name of the channel to connect to the outgoing call. */ - public String getChannel() - { + public String getChannel() { return channel; } /** - * Sets the name of the channel to connect to the outgoing call.

      + * Sets the name of the channel to connect to the outgoing call. + *

      * This property is mandatory. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the name of the context of the extension to connect to. */ - public String getContext() - { + public String getContext() { return context; } /** - * Sets the name of the context of the extension to connect to.

      + * Sets the name of the context of the extension to connect to. + *

      * If you set the context you also have to set the exten and priority * properties. */ - public void setContext(String context) - { + public void setContext(String context) { this.context = context; } /** * Returns the extension to connect to. */ - public String getExten() - { + public String getExten() { return exten; } /** - * Sets the extension to connect to.

      + * Sets the extension to connect to. + *

      * If you set the extension you also have to set the context and priority * properties. */ - public void setExten(String exten) - { + public void setExten(String exten) { this.exten = exten; } /** * Returns the priority of the extension to connect to. */ - public Integer getPriority() - { + public Integer getPriority() { return priority; } @@ -236,110 +253,124 @@ public Integer getPriority() * Sets the priority of the extension to connect to. If you set the priority * you also have to set the context and exten properties. */ - public void setPriority(Integer priority) - { + public void setPriority(Integer priority) { this.priority = priority; } /** * Returns the name of the application to connect to. */ - public String getApplication() - { + public String getApplication() { return application; } /** * Sets the name of the application to connect to. */ - public void setApplication(String application) - { + public void setApplication(String application) { this.application = application; } /** * Returns the parameters to pass to the application. */ - public String getData() - { + public String getData() { return data; } /** * Sets the parameters to pass to the application. */ - public void setData(String data) - { + public void setData(String data) { this.data = data; } /** * Returns the timeout for the origination. */ - public Long getTimeout() - { + public Long getTimeout() { return timeout; } /** - * Sets the timeout (in milliseconds) for the origination.

      + * Sets the timeout (in milliseconds) for the origination. + *

      * The channel must be answered within this time, otherwise the origination - * is considered to have failed and an OriginateFailureEvent is generated.

      + * is considered to have failed and an OriginateFailureEvent is generated. + *

      * If not set, Asterisk assumes a default value of 30000 meaning 30 seconds. * * @param timeout the timeout in milliseconds - * @deprecated use {@see #setTimeout(Long)} instead. + * @deprecated use {@link #setTimeout(Long)} instead. */ - @Deprecated public void setTimeout(Integer timeout) - { - this.timeout = timeout.longValue(); + @Deprecated + public void setTimeout(Integer timeout) { + if (timeout != null) { + if (timeout < 1000) { + logger.error("A timeout of 1000 will cause the originate to almost cretainly fail!"); + } + if (timeout < 10000) { + logger.warn( + "A timeout of less than 10000 will cause the originate to fail if not answered within 10 seconds!"); + } + this.timeout = timeout.longValue(); + } else { + this.timeout = null; + } } /** - * Sets the timeout (in milliseconds) for the origination.

      + * Sets the timeout (in milliseconds) for the origination. + *

      * The channel must be answered within this time, otherwise the origination - * is considered to have failed and an OriginateFailureEvent is generated.

      + * is considered to have failed and an OriginateFailureEvent is generated. + *

      * If not set, Asterisk assumes a default value of 30000 meaning 30 seconds. * * @param timeout the timeout in milliseconds */ - public void setTimeout(Long timeout) - { + public void setTimeout(Long timeout) { + if (timeout != null) { + if (timeout < 1000) { + logger.error("A timeout of 1000 will cause the originate to almost cretainly fail!"); + } + if (timeout < 10000) { + logger.warn( + "A timeout of less than 100000 will cause the originate to fail if not answered within 10 seconds!"); + } + } this.timeout = timeout; } /** - * Sets the variables to set on the originated call.

      + * Sets the variables to set on the originated call. + *

      * Variable assignments are of the form "VARNAME=VALUE". You can specify - * multiple variable assignments separated by the '|' character.

      + * multiple variable assignments separated by the '|' character. + *

      * Example: "VAR1=abc|VAR2=def" sets the channel variables VAR1 to "abc" and * VAR2 to "def". * * @deprecated use {@link #setVariables(Map)} instead. */ - @Deprecated public void setVariable(String variable) - { + @Deprecated + public void setVariable(String variable) { final StringTokenizer st; - if (variable == null) - { + if (variable == null) { this.variables = null; return; } st = new StringTokenizer(variable, "|"); - variables = new LinkedHashMap(); - while (st.hasMoreTokens()) - { + variables = new LinkedHashMap<>(); + while (st.hasMoreTokens()) { String[] keyValue; keyValue = st.nextToken().split("=", 2); - if (keyValue.length < 2) - { + if (keyValue.length < 2) { variables.put(keyValue[0], null); - } - else - { + } else { variables.put(keyValue[0], keyValue[1]); } } @@ -352,11 +383,9 @@ public void setTimeout(Long timeout) * @param value the value of the variable to set. * @since 0.3 */ - public void setVariable(String name, String value) - { - if (variables == null) - { - variables = new LinkedHashMap(); + public void setVariable(String name, String value) { + if (variables == null) { + variables = new LinkedHashMap<>(); } variables.put(name, value); @@ -365,12 +394,11 @@ public void setVariable(String name, String value) /** * Returns the variables to set on the originated call. * - * @return a Map containing the variable names as key and their - * values as value. + * @return a Map containing the variable names as key and their values as + * value. * @since 0.2 */ - public Map getVariables() - { + public Map getVariables() { return variables; } @@ -381,16 +409,18 @@ public Map getVariables() * values as value. * @since 0.2 */ - public void setVariables(Map variables) - { - this.variables = variables; + public void setVariables(Map variables) { + if (this.variables != null) { + this.variables.putAll(variables); + } else { + this.variables = variables; + } } /** * Returns true if this is a fast origination. */ - public Boolean getAsync() - { + public Boolean getAsync() { return async; } @@ -398,60 +428,120 @@ public Boolean getAsync() * Set to true for fast origination. Only with fast origination Asterisk * will send OriginateSuccess- and OriginateFailureEvents. */ - public void setAsync(Boolean async) - { + public void setAsync(Boolean async) { this.async = async; } + /** + * @param earlyMedia the earlyMedia to set + */ + public void setEarlyMedia(Boolean earlyMedia) { + this.earlyMedia = earlyMedia; + } + + /** + * @return the earlyMedia + */ + public Boolean getEarlyMedia() { + return earlyMedia; + } + /** * Returns the codecs to use for the call. * * @return the codecs to use for the call. * @since 1.0.0 */ - public String getCodecs() - { + public String getCodecs() { return codecs; } /** - * Sets the codecs to use for the call. For example "alaw, ulaw, h264".

      + * Sets the codecs to use for the call. For example "alaw, ulaw, h264". + *

      * Available since Asterisk 1.6. * * @param codecs comma separated list of codecs to use for the call. * @since 1.0.0 */ - public void setCodecs(String codecs) - { + public void setCodecs(String codecs) { this.codecs = codecs; } /** - * Sets the codecs to use for the call.

      + * Sets the codecs to use for the call. + *

      * Available since Asterisk 1.6. * * @param codecs list of codecs to use for the call. * @since 1.0.0 */ - public void setCodecs(List codecs) - { - if (codecs == null || codecs.isEmpty()) - { + public void setCodecs(List codecs) { + if (codecs == null || codecs.isEmpty()) { this.codecs = null; return; } Iterator iter = codecs.iterator(); - StringBuffer buffer = new StringBuffer(iter.next()); - while (iter.hasNext()) - { + StringBuilder buffer = new StringBuilder(iter.next()); + while (iter.hasNext()) { buffer.append(",").append(iter.next()); } this.codecs = buffer.toString(); } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return OriginateResponseEvent.class; } + + public void addSipHeader(VariableInheritance inheritance, String header) { + if (!preventDuplicateSipHeaders.contains(header)) { + setVariable(inheritance.getPrefix() + "SIPADDHEADER" + (headerCounter++), header); + preventDuplicateSipHeaders.add(header); + if (headerCounter > 50) { + logger.warn("I think only 50 headers are allowed by asterisk?"); + } + } else { + logger.error("Already added the sip header " + header); + } + } + + public void addPjSipHeader(VariableInheritance inheritance, String header) { + if (header != null) { + String[] parts = header.split(":"); + if (parts.length == 2) { + String varName = "PJSIP_HEADER" + "(add," + parts[0] + ")"; + String varValue = parts[1]; + + if (!preventDuplicateSipHeaders.contains(header)) { + setVariable(varName, varValue); + preventDuplicateSipHeaders.add(header); + } else { + logger.error("Already added the sip header " + header); + } + } + } + } + + /** + * this will be the channels uniqueID + * + * @param channelId + */ + public void setChannelId(String channelId) { + this.channelId = channelId; + } + + public String getChannelId() { + return channelId; + } + + public void setOtherChannelId(String otherChannelId) { + this.otherChannelId = otherChannelId; + } + + public String getOtherChannelId() { + return otherChannelId; + } + } diff --git a/src/main/java/org/asteriskjava/manager/action/PJSIPNotifyAction.java b/src/main/java/org/asteriskjava/manager/action/PJSIPNotifyAction.java new file mode 100644 index 000000000..40dd386b8 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/PJSIPNotifyAction.java @@ -0,0 +1,135 @@ +/* + * Copyright 2018 IPerity BV + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Send a NOTIFY to either an endpoint or an arbitrary URI. + *

      + * Either a URI, a channel or an endpoint can be specified. + *

      + *

      + * See: https://wiki.asterisk.org/wiki/display/AST/Asterisk+15+ManagerAction_PJSIPNotify + */ +public class PJSIPNotifyAction extends AbstractManagerAction implements ManagerAction { + private static final long serialVersionUID = 8198467461743334704L; + private String channel; + private String endpoint; + private String uri; + private Map variables; + + public PJSIPNotifyAction() { + super(); + } + + @Override + public String getAction() { + return "PJSIPNotify"; + } + + /** + * Get the PJSIP channel to send the NOTIFY on. + * + * @return + */ + public String getChannel() { + return this.channel; + } + + /** + * Get the PJSIP endpoint to which to send the NOTIFY. + * + * @return + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Get the URI to which to send the NOTIFY. + * + * @return + */ + public String getUri() { + return this.uri; + } + + /** + * Set the PJSIP channel name to send the NOTIFY on. This must be a PJSIP channel, + * ie. start with "PJSIP/". + * + * @param channel + */ + public void setChannel(String channel) { + this.channel = channel; + } + + /** + * Set the PJSIP endpoint to send to NOTIFY to. + * + * @param endpoint + */ + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } + + /** + * Set an abritrary URI to send the NOTIFY to. + * + * @param uri + */ + public void setUri(String uri) { + this.uri = uri; + } + + /** + * Add a variable. + *

      + * Use the 'content' variable to specify the NOTIFY body. + * + * @param name + * @param value + */ + public void setVariable(String name, String value) { + if (this.variables == null) { + this.variables = new LinkedHashMap<>(); + } + + this.variables.put(name, value); + } + + /** + * Set all variables. See {@link #setVariable(String, String)}. + * + * @param variables + */ + public void setVariables(Map variables) { + this.variables = variables; + } + + /** + * Get the variables. + * + * @return + */ + public Map getVariables() { + return this.variables; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/action/PJSipShowContactsAction.java b/src/main/java/org/asteriskjava/manager/action/PJSipShowContactsAction.java new file mode 100644 index 000000000..bc899dc48 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/PJSipShowContactsAction.java @@ -0,0 +1,58 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +import org.asteriskjava.manager.event.ContactListComplete; +import org.asteriskjava.manager.event.ResponseEvent; + +/** + * Retrieves a list of all defined PJSIP contacts. + *

      + * For each contact that is found a ContactList is sent by Asterisk containing + * the details. When all contact have been reported a ContactListComplete is + * sent. + *

      + * Available since Asterisk 16 Permission required: write=system + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.event.ContactList + * @see org.asteriskjava.manager.event.ContactListComplete + * @since 0.2 + */ +public class PJSipShowContactsAction extends AbstractManagerAction implements EventGeneratingAction { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = 921037572305993779L; + + /** + * Creates a new SipPeersAction. + */ + public PJSipShowContactsAction() { + + } + + @Override + public String getAction() { + return "PJSIPShowContacts"; + } + + public Class getActionCompleteEventClass() { + return ContactListComplete.class; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/PJSipShowEndpointAction.java b/src/main/java/org/asteriskjava/manager/action/PJSipShowEndpointAction.java new file mode 100644 index 000000000..78c643be3 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/PJSipShowEndpointAction.java @@ -0,0 +1,76 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +import org.asteriskjava.manager.event.EndpointDetailComplete; +import org.asteriskjava.manager.event.ResponseEvent; + +/** + * Retrieves details about a given endpoint. + *

      + * For the given endpoint, the call will return several events, including + * EndpointDetail, AorDetail, AuthDetail, TransportDetail, ContactStatusDetail,and IdentifyDetail. + *

      + * Some events may appear multiple times. + *

      + * When all events have been reported an EndpointDetailComplete is + * sent. + *

      + * Available since Asterisk 12 Permission required: write=system + * + * @author Steve Sether + * @version $Id$ + * @see org.asteriskjava.manager.event.ContactStatusDetail + * @see org.asteriskjava.manager.event.AorDetail + * @see org.asteriskjava.manager.event.EndpointDetail + * @see org.asteriskjava.manager.event.TransportDetail + * @see org.asteriskjava.manager.event.AuthDetail + * @see org.asteriskjava.manager.event.EndpointDetailComplete + * @since 12 + */ +public class PJSipShowEndpointAction extends AbstractManagerAction implements EventGeneratingAction { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = -5508189961610900058L; + private String endpoint; + + + public String getEndpoint() { + return endpoint; + } + + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } + + /** + * Creates a new SipPeersAction. + */ + public PJSipShowEndpointAction() { + + } + + @Override + public String getAction() { + return "PJSIPShowEndpoint"; + } + + public Class getActionCompleteEventClass() { + return EndpointDetailComplete.class; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/PJSipShowEndpointsAction.java b/src/main/java/org/asteriskjava/manager/action/PJSipShowEndpointsAction.java new file mode 100644 index 000000000..71c738724 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/PJSipShowEndpointsAction.java @@ -0,0 +1,58 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +import org.asteriskjava.manager.event.EndpointListComplete; +import org.asteriskjava.manager.event.ResponseEvent; + +/** + * Retrieves a list of all defined SIP peers. + *

      + * For each peer that is found a PeerEntryEvent is sent by Asterisk containing + * the details. When all peers have been reported a PeerlistCompleteEvent is + * sent. + *

      + * Available since Asterisk 12 Permission required: write=system + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.event.PeerEntryEvent + * @see org.asteriskjava.manager.event.PeerlistCompleteEvent + * @since 12 + */ +public class PJSipShowEndpointsAction extends AbstractManagerAction implements EventGeneratingAction { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = 921037572305993779L; + + /** + * Creates a new SipPeersAction. + */ + public PJSipShowEndpointsAction() { + + } + + @Override + public String getAction() { + return "PJSIPShowEndpoints"; + } + + public Class getActionCompleteEventClass() { + return EndpointListComplete.class; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/ParkAction.java b/src/main/java/org/asteriskjava/manager/action/ParkAction.java index 7693c097e..ed6d30855 100644 --- a/src/main/java/org/asteriskjava/manager/action/ParkAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ParkAction.java @@ -21,12 +21,11 @@ *

      * Defined in res/res_features.c

      * Available since Asterisk 1.4. - * + * * @author srt * @version $Id$ */ -public class ParkAction extends AbstractManagerAction -{ +public class ParkAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -39,20 +38,18 @@ public class ParkAction extends AbstractManagerAction /** * Creates a new empty ParkAction. */ - public ParkAction() - { + public ParkAction() { super(); } /** * Creates a new ParkAction. - * - * @param channel name of the channel to park. + * + * @param channel name of the channel to park. * @param channel2 name of the channel to announce park info to and return - * to on timeout. + * to on timeout. */ - public ParkAction(String channel, String channel2) - { + public ParkAction(String channel, String channel2) { super(); this.channel = channel; this.channel2 = channel2; @@ -60,14 +57,13 @@ public ParkAction(String channel, String channel2) /** * Creates a new ParkAction with a timeout. - * - * @param channel the name of the channel to park. + * + * @param channel the name of the channel to park. * @param channel2 the name of the channel to announce park info to and - * return to on timeout. - * @param timeout the timeout in seconds before callback. + * return to on timeout. + * @param timeout the timeout in seconds before callback. */ - public ParkAction(String channel, String channel2, Integer timeout) - { + public ParkAction(String channel, String channel2, Integer timeout) { super(); this.channel = channel; this.channel2 = channel2; @@ -78,41 +74,37 @@ public ParkAction(String channel, String channel2, Integer timeout) * Returns the name of this action, i.e. "Park". */ @Override - public String getAction() - { + public String getAction() { return "Park"; } /** * Returns the name of the channel to park. - * + * * @return the name of the channel to park. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel to park.

      * This property is mandatory. - * + * * @param channel the name of the channel to park. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the name of the channel to announce park info to and return to on * timeout. - * + * * @return the name of the channel to announce park info to and return to on - * timeout. + * timeout. */ - public String getChannel2() - { + public String getChannel2() { return channel2; } @@ -120,32 +112,29 @@ public String getChannel2() * Sets the name of the channel to announce park info to and return to on * timeout.

      * This property is mandatory. - * + * * @param channel2 the name of the channel to announce park info to and - * return to on timeout. + * return to on timeout. */ - public void setChannel2(String channel2) - { + public void setChannel2(String channel2) { this.channel2 = channel2; } /** * Returns the timeout in seconds before callback. - * + * * @return the timeout in seconds before callback. */ - public Integer getTimeout() - { + public Integer getTimeout() { return timeout; } /** * Sets the timeout in seconds before callback. - * + * * @param timeout the timeout in seconds before callback. */ - public void setTimeout(Integer timeout) - { + public void setTimeout(Integer timeout) { this.timeout = timeout; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ParkedCallsAction.java b/src/main/java/org/asteriskjava/manager/action/ParkedCallsAction.java index 2ab3efb3f..0f519e0de 100644 --- a/src/main/java/org/asteriskjava/manager/action/ParkedCallsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ParkedCallsAction.java @@ -23,16 +23,15 @@ * The ParkedCallsAction requests a list of all currently parked calls.

      * For each active channel a ParkedCallEvent is generated. After all parked * calls have been reported a ParkedCallsCompleteEvent is generated. - * - * @see org.asteriskjava.manager.event.ParkedCallEvent - * @see org.asteriskjava.manager.event.ParkedCallsCompleteEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.ParkedCallEvent + * @see org.asteriskjava.manager.event.ParkedCallsCompleteEvent */ public class ParkedCallsAction extends AbstractManagerAction implements - EventGeneratingAction -{ + EventGeneratingAction { /** * Serializable version identifier */ @@ -41,8 +40,7 @@ public class ParkedCallsAction extends AbstractManagerAction /** * Creates a new ParkedCallsAction. */ - public ParkedCallsAction() - { + public ParkedCallsAction() { } @@ -50,13 +48,11 @@ public ParkedCallsAction() * Returns the name of this action, i.e. "ParkedCalls". */ @Override - public String getAction() - { + public String getAction() { return "ParkedCalls"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return ParkedCallsCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/PauseMixMonitorAction.java b/src/main/java/org/asteriskjava/manager/action/PauseMixMonitorAction.java new file mode 100644 index 000000000..31992b30c --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/PauseMixMonitorAction.java @@ -0,0 +1,79 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.asteriskjava.manager.action; + +/** + * The PauseMixMonitorAction temporarily stop/start monitoring (recording) a/both channel(s). + *

      + * Available since Asterisk 1.4. + * Channel - Used to specify the channel to mute. + * Direction - Which part of the recording to mute: read, write or both (from channel, to channel or both channels). + * State - Turn mute on or off : 1 to turn on, 0 to turn off. + * + * @author Adrian Videanu + * @version $Id$ + * @since 0.3 + */ + +public class PauseMixMonitorAction extends AbstractManagerAction { + + private static final long serialVersionUID = -7438670441797420390L; + + private String channel; + private Integer state; + private String direction; + + public PauseMixMonitorAction() { + super(); + } + + public PauseMixMonitorAction(String ch, Integer st, String dir) { + this.channel = ch; + this.state = st; + this.direction = dir; + } + + @Override + public String getAction() { + return "MixMonitorMute"; + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public Integer getState() { + return state; + } + + public void setState(Integer state) { + this.state = state; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/PauseMonitorAction.java b/src/main/java/org/asteriskjava/manager/action/PauseMonitorAction.java index e69600cc7..041ee56e3 100644 --- a/src/main/java/org/asteriskjava/manager/action/PauseMonitorAction.java +++ b/src/main/java/org/asteriskjava/manager/action/PauseMonitorAction.java @@ -22,14 +22,13 @@ * It is implemented in res/res_monitor.c *

      * Available since Asterisk 1.4. - * - * @see UnpauseMonitorAction + * * @author srt - * @since 0.3 * @version $Id$ + * @see UnpauseMonitorAction + * @since 0.3 */ -public class PauseMonitorAction extends AbstractManagerAction -{ +public class PauseMonitorAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -43,40 +42,36 @@ public class PauseMonitorAction extends AbstractManagerAction /** * Creates a new empty PauseMonitorAction. */ - public PauseMonitorAction() - { + public PauseMonitorAction() { } /** * Creates a new PauseMonitorAction that temporarily stops monitoring the * given channel. - * + * * @param channel the name of the channel to temporarily stop monitoring. */ - public PauseMonitorAction(String channel) - { + public PauseMonitorAction(String channel) { this.channel = channel; } /** * Returns the name of this action, i.e. "PauseMonitor". - * + * * @return the name of this action. */ @Override - public String getAction() - { + public String getAction() { return "PauseMonitor"; } /** * Returns the name of the channel to temporarily stop monitoring. - * + * * @return the name of the channel to temporarily stop monitoring. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -84,11 +79,10 @@ public String getChannel() * Sets the name of the channel to temporarily stop monitoring. *

      * This property is mandatory. - * + * * @param channel the name of the channel to temporarily stop monitoring. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } } diff --git a/src/main/java/org/asteriskjava/manager/action/PingAction.java b/src/main/java/org/asteriskjava/manager/action/PingAction.java index 36a907fa3..58be89a06 100644 --- a/src/main/java/org/asteriskjava/manager/action/PingAction.java +++ b/src/main/java/org/asteriskjava/manager/action/PingAction.java @@ -23,13 +23,12 @@ * The PingAction is used to keep the manager connection open and performs no operation.

      * Asterisk versions prior to 1.6 send a "Pong" response, since Asterisk 1.6 a * "Success" response is sent with a "Ping" property set to "Pong". - * + * * @author srt * @version $Id$ */ @ExpectedResponse(PingResponse.class) -public class PingAction extends AbstractManagerAction -{ +public class PingAction extends AbstractManagerAction { /** * Serializable version identifier. */ @@ -38,8 +37,7 @@ public class PingAction extends AbstractManagerAction /** * Creates a new PingAction. */ - public PingAction() - { + public PingAction() { super(); } @@ -47,8 +45,7 @@ public PingAction() * Returns the name of this action, i.e. "Ping". */ @Override - public String getAction() - { + public String getAction() { return "Ping"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/PlayDtmfAction.java b/src/main/java/org/asteriskjava/manager/action/PlayDtmfAction.java index db4b9c175..c0b71995c 100644 --- a/src/main/java/org/asteriskjava/manager/action/PlayDtmfAction.java +++ b/src/main/java/org/asteriskjava/manager/action/PlayDtmfAction.java @@ -17,16 +17,17 @@ package org.asteriskjava.manager.action; /** - * The PlayDTMFAction plays a DTMF digit on the specified channel.

      - * It is definied in apps/app_senddtmf.c.

      + * The PlayDTMFAction plays a DTMF digit on the specified channel. + *

      + * It is definied in apps/app_senddtmf.c. + *

      * Available since Asterisk 1.2.8 - * - * @since 0.3 + * * @author srt * @version $Id$ + * @since 0.3 */ -public class PlayDtmfAction extends AbstractManagerAction -{ +public class PlayDtmfAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -34,23 +35,22 @@ public class PlayDtmfAction extends AbstractManagerAction private String channel; private String digit; + private Integer duration = null; + private Boolean receive; /** * Creates a new empty PlayDtmfAction. */ - public PlayDtmfAction() - { - + public PlayDtmfAction() { } /** * Creates a new PlayDtmfAction that sends the given DTMF digit to the given channel. - * + * * @param channel the name of the channel to send the digit to. - * @param digit the DTML digit to play. + * @param digit the DTML digit to play. */ - public PlayDtmfAction(String channel, String digit) - { + public PlayDtmfAction(String channel, String digit) { this.channel = channel; this.digit = digit; } @@ -59,48 +59,73 @@ public PlayDtmfAction(String channel, String digit) * Returns the name of this action, i.e. "PlayDTMF". */ @Override - public String getAction() - { + public String getAction() { return "PlayDTMF"; } + /** + * Returns the 'receive' property of this action. + * (since asterisk 16.7.0) + * + * @return the receive property, or null if not set + */ + public Boolean getReceive() { + return this.receive; + } + + /** + * Set the receive property of the action. + * (since asterisk 16.7.0) + * + * @param receive value for receive, or null to unset + */ + public void setReceive(Boolean receive) { + this.receive = receive; + } + /** * Returns the name of the channel to send the digit to. - * + * * @return the name of the channel to send the digit to. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel to send the digit to. - * + * * @param channel the name of the channel to send the digit to. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the DTMF digit to play. - * + * * @return the DTMF digit to play. */ - public String getDigit() - { + public String getDigit() { return digit; } /** * Sets the DTMF digit to play. - * + * * @param digit the DTMF digit to play. */ - public void setDigit(String digit) - { + public void setDigit(String digit) { this.digit = digit; } + + public void setDuration(Integer duration) + { + this.duration = duration; + } + + public Integer getDuration() + { + return duration; + } } diff --git a/src/main/java/org/asteriskjava/manager/action/QueueAddAction.java b/src/main/java/org/asteriskjava/manager/action/QueueAddAction.java index dcb2d84e1..cf432bd03 100644 --- a/src/main/java/org/asteriskjava/manager/action/QueueAddAction.java +++ b/src/main/java/org/asteriskjava/manager/action/QueueAddAction.java @@ -20,26 +20,26 @@ * The QueueAddAction adds a new member to a queue.

      * It is implemented in apps/app_queue.c

      * The memberName property was added in Asterisk 1.4, the - * stateInterface property in Asterisk 1.6. + * stateInterface property in Asterisk 1.6, + * the reason property in Asterisk 20. * * @author srt * @version $Id$ */ -public class QueueAddAction extends AbstractManagerAction -{ +public class QueueAddAction extends AbstractManagerAction { private static final long serialVersionUID = 2L; private String queue; private String iface; private Integer penalty; private Boolean paused; + private String reason; private String memberName; private String stateInterface; /** * Creates a new empty QueueAddAction. */ - public QueueAddAction() - { + public QueueAddAction() { } @@ -52,8 +52,7 @@ public QueueAddAction() * use the channel name, e.g. "SIP/1234". * @since 0.2 */ - public QueueAddAction(String queue, String iface) - { + public QueueAddAction(String queue, String iface) { this.queue = queue; this.iface = iface; } @@ -70,8 +69,7 @@ public QueueAddAction(String queue, String iface) * distributed members with higher penalties are considered last. * @since 0.2 */ - public QueueAddAction(String queue, String iface, Integer penalty) - { + public QueueAddAction(String queue, String iface, Integer penalty) { this.queue = queue; this.iface = iface; this.penalty = penalty; @@ -81,8 +79,7 @@ public QueueAddAction(String queue, String iface, Integer penalty) * Returns the name of this action, i.e. "QueueAdd". */ @Override - public String getAction() - { + public String getAction() { return "QueueAdd"; } @@ -91,8 +88,7 @@ public String getAction() * * @return the name of the queue the new member will be added to. */ - public String getQueue() - { + public String getQueue() { return queue; } @@ -102,8 +98,7 @@ public String getQueue() * * @param queue the name of the queue the new member will be added to. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } @@ -112,8 +107,7 @@ public void setQueue(String queue) * * @return the name of the channel to dial to reach this member. */ - public String getInterface() - { + public String getInterface() { return iface; } @@ -123,8 +117,7 @@ public String getInterface() * * @param iface the name of the channel to dial to reach this member, e.g. "SIP/1234". */ - public void setInterface(String iface) - { + public void setInterface(String iface) { this.iface = iface; } @@ -133,8 +126,7 @@ public void setInterface(String iface) * * @return the penalty for this member. */ - public Integer getPenalty() - { + public Integer getPenalty() { return penalty; } @@ -147,8 +139,7 @@ public Integer getPenalty() * * @param penalty the penalty for this member. */ - public void setPenalty(Integer penalty) - { + public void setPenalty(Integer penalty) { this.penalty = penalty; } @@ -158,8 +149,7 @@ public void setPenalty(Integer penalty) * @return Boolean.TRUE if the queue member should be paused when added. * @since 0.2 */ - public Boolean getPaused() - { + public Boolean getPaused() { return paused; } @@ -170,10 +160,29 @@ public Boolean getPaused() * added. * @since 0.2 */ - public void setPaused(Boolean paused) - { + public void setPaused(Boolean paused) { this.paused = paused; } + + /** + * Returns the queue member pause reason. + * Available since Asterisk 20. + * + * @return Pause reason. + */ + public String getReason() { + return reason; + } + + /** + * Sets the queue member pause reason. + * Available since Asterisk 20. + * + * @param reason. + */ + public void setReason(String reason) { + this.reason = reason; + } /** * Returns the name of the queue memeber (agent name).

      @@ -182,8 +191,7 @@ public void setPaused(Boolean paused) * @return the name of the queue memeber (agent name). * @since 1.0.0 */ - public String getMemberName() - { + public String getMemberName() { return memberName; } @@ -194,8 +202,7 @@ public String getMemberName() * @param memberName the name of the queue memeber (agent name). * @since 1.0.0 */ - public void setMemberName(String memberName) - { + public void setMemberName(String memberName) { this.memberName = memberName; } @@ -206,8 +213,7 @@ public void setMemberName(String memberName) * @return the name of the channel from which to read devicestate changes. * @since 1.0.0 */ - public String getStateInterface() - { + public String getStateInterface() { return stateInterface; } @@ -218,8 +224,7 @@ public String getStateInterface() * @param stateInterface the name of the channel from which to read devicestate changes. * @since 1.0.0 */ - public void setStateInterface(String stateInterface) - { + public void setStateInterface(String stateInterface) { this.stateInterface = stateInterface; } } diff --git a/src/main/java/org/asteriskjava/manager/action/QueueChangePriorityCallerAction.java b/src/main/java/org/asteriskjava/manager/action/QueueChangePriorityCallerAction.java new file mode 100644 index 000000000..a0f0ac2e9 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/QueueChangePriorityCallerAction.java @@ -0,0 +1,111 @@ +package org.asteriskjava.manager.action; + +/** + * The QueueChangePriorityCallerAction requests to change priority of caller. + * Priority cannot be less than 0. + */ + +public class QueueChangePriorityCallerAction extends AbstractManagerAction { + + /** + * Serializable version identifier + */ + + private final static long serialVersionUID = -1554562185648L; + + private String queue; + private String caller; + private Integer priority; + + /** + * Creates a new empty QueueChangePriorityCallerAction. + */ + + public QueueChangePriorityCallerAction() { + } + + /** + * Creates a new QueueChangePriorityCAllerAction with all required parameters. + * + * @param queue name of queue. + * @param caller caller channel name. + * @param priority priority value to set. + */ + + public QueueChangePriorityCallerAction(String queue, String caller, Integer priority) { + this.queue = queue; + this.caller = caller; + this.priority = priority; + } + + /** + * Returns the name of this action, i.e. "QueueChangePriorityCaller" + * + * @return String, name of action + */ + + @Override + public String getAction() { + return "QueueChangePriorityCaller"; + } + + /** + * Returns the queue that caller is inside. + * + * @return queue name + */ + + public String getQueue() { + return queue; + } + + /** + * Sets the queue filter. + * + * @param queue queue name + */ + + public void setQueue(String queue) { + this.queue = queue; + } + + /** + * Returns the caller to change priority. + * + * @return String caller name + */ + + public String getCaller() { + return caller; + } + + /** + * Sets the caller to change priority. If not sets then nothing changes. + * + * @param caller caller name + */ + + public void setCaller(String caller) { + this.caller = caller; + } + + /** + * Returns priority to set to given caller. + * + * @return integer priority value + */ + + public Integer getPriority() { + return priority; + } + + /** + * Sets priority to given caller. If nothing sets then nothing changes. + * + * @param priority priority value + */ + + public void setPriority(Integer priority) { + this.priority = priority; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/QueueLogAction.java b/src/main/java/org/asteriskjava/manager/action/QueueLogAction.java index fa69f942b..ce72f7a4f 100644 --- a/src/main/java/org/asteriskjava/manager/action/QueueLogAction.java +++ b/src/main/java/org/asteriskjava/manager/action/QueueLogAction.java @@ -25,8 +25,7 @@ * @version $Id$ * @since 1.0.0 */ -public class QueueLogAction extends AbstractManagerAction -{ +public class QueueLogAction extends AbstractManagerAction { private static final long serialVersionUID = 1L; private String iface; @@ -38,8 +37,7 @@ public class QueueLogAction extends AbstractManagerAction /** * Creates a new empty QueueLogAction. */ - public QueueLogAction() - { + public QueueLogAction() { } @@ -49,8 +47,7 @@ public QueueLogAction() * @param queue the name of the queue to log the event for. * @param event the event to log. */ - public QueueLogAction(String queue, String event) - { + public QueueLogAction(String queue, String event) { this.queue = queue; this.event = event; } @@ -64,8 +61,7 @@ public QueueLogAction(String queue, String event) * @param iface the interface of the member to log the event for, may be null. * @param uniqueId the unique id of the channel to log the event for, may be null. */ - public QueueLogAction(String queue, String event, String message, String iface, String uniqueId) - { + public QueueLogAction(String queue, String event, String message, String iface, String uniqueId) { this.queue = queue; this.event = event; this.message = message; @@ -79,8 +75,7 @@ public QueueLogAction(String queue, String event, String message, String iface, * @return the name of this action. */ @Override - public String getAction() - { + public String getAction() { return "QueueLog"; } @@ -89,8 +84,7 @@ public String getAction() * * @return the interface of the member to log the event for. */ - public String getInterface() - { + public String getInterface() { return iface; } @@ -99,8 +93,7 @@ public String getInterface() * * @param iface the interface of the member to log the event for. */ - public void setInterface(String iface) - { + public void setInterface(String iface) { this.iface = iface; } @@ -109,8 +102,7 @@ public void setInterface(String iface) * * @return the name of the queue to log the event for. */ - public String getQueue() - { + public String getQueue() { return queue; } @@ -120,8 +112,7 @@ public String getQueue() * * @param queue the name of the queue to log the event for. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } @@ -130,8 +121,7 @@ public void setQueue(String queue) * * @return the unique id of the channel to log the event for. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -140,8 +130,7 @@ public String getUniqueId() * * @param uniqueId the unique id of the channel to log the event for. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -150,8 +139,7 @@ public void setUniqueId(String uniqueId) * * @return the event to log. */ - public String getEvent() - { + public String getEvent() { return event; } @@ -161,8 +149,7 @@ public String getEvent() * * @param event the event to log. */ - public void setEvent(String event) - { + public void setEvent(String event) { this.event = event; } @@ -171,8 +158,7 @@ public void setEvent(String event) * * @return the message to log. */ - public String getMessage() - { + public String getMessage() { return message; } @@ -181,8 +167,7 @@ public String getMessage() * * @param message the message to log. */ - public void setMessage(String message) - { + public void setMessage(String message) { this.message = message; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/QueueMemberRingInUseAction.java b/src/main/java/org/asteriskjava/manager/action/QueueMemberRingInUseAction.java new file mode 100644 index 000000000..347ffbb74 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/QueueMemberRingInUseAction.java @@ -0,0 +1,118 @@ +package org.asteriskjava.manager.action; + +/** + * The QueueMemberRingInUseAction requests to change RingInUse value of queue member. + */ + +public class QueueMemberRingInUseAction extends AbstractManagerAction { + + /** + * Serializable version identifier + */ + + private final static long serialVersionUID = -1554562185640L; + + /** + * Queue name where member is located; + */ + + private String queue; + + /** + * RingInUse value. + */ + + private Boolean ringInUse; + + /** + * Interface where need to change RingInUse value; + */ + + private String iface; + + /** + * Creates a new empty QueueMemberRingInUseAction. + */ + + public QueueMemberRingInUseAction() { + } + + /** + * Creates a new QueueMemberRingInUseAction with mandatory properties queue, ringInUse and iface. + * + * @param queue queueName. + * @param ringInUse value to set. + * @param iface interface where to set ringInUse. + */ + + public QueueMemberRingInUseAction(String queue, Boolean ringInUse, String iface) { + this.queue = queue; + this.ringInUse = ringInUse; + this.iface = iface; + } + + @Override + public String getAction() { + return "QueueMemberRingInUse"; + } + + /** + * Returns queue name where interface is located. + * + * @return queue name; + */ + + public String getQueue() { + return queue; + } + + /** + * Sets queue name where interface is located. + * + * @param queue queue name; + */ + + public void setQueue(String queue) { + this.queue = queue; + } + + /** + * Returns RingInUse value of selected interface. + * + * @return ringInUse value; + */ + + public Boolean getRingInUse() { + return ringInUse; + } + + /** + * Sets RingInUse to selected interface. + * + * @param ringInUse value. + */ + + public void setRingInUse(Boolean ringInUse) { + this.ringInUse = ringInUse; + } + + /** + * Returns interface value eg. SIP/203. + * + * @return interface value. + */ + + public String getInterface() { + return iface; + } + + /** + * Sets interface value where RingInUse changes. + * + * @param iface name + */ + + public void setInterface(String iface) { + this.iface = iface; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/QueuePauseAction.java b/src/main/java/org/asteriskjava/manager/action/QueuePauseAction.java index b67b58503..654d5520c 100644 --- a/src/main/java/org/asteriskjava/manager/action/QueuePauseAction.java +++ b/src/main/java/org/asteriskjava/manager/action/QueuePauseAction.java @@ -21,13 +21,12 @@ * available again).

      * It is implemented in apps/app_queue.c

      * Available since Asterisk 1.2. - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class QueuePauseAction extends AbstractManagerAction -{ +public class QueuePauseAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -36,23 +35,22 @@ public class QueuePauseAction extends AbstractManagerAction private String iface; private Boolean paused; private String queue; + private String reason; /** * Creates a new empty QueuePauseAction. */ - public QueuePauseAction() - { + public QueuePauseAction() { } /** * Creates a new QueuePauseAction that makes the member on the given * interface unavailable on all queues. - * + * * @param iface the interface of the member to make unavailable */ - public QueuePauseAction(String iface) - { + public QueuePauseAction(String iface) { this.iface = iface; this.paused = Boolean.TRUE; } @@ -60,12 +58,11 @@ public QueuePauseAction(String iface) /** * Creates a new QueuePauseAction that makes the member on the given * interface unavailable on the given queue. - * + * * @param iface the interface of the member to make unavailable * @param queue the queue the member is made unvailable on */ - public QueuePauseAction(String iface, String queue) - { + public QueuePauseAction(String iface, String queue) { this.iface = iface; this.queue = queue; this.paused = Boolean.TRUE; @@ -74,13 +71,12 @@ public QueuePauseAction(String iface, String queue) /** * Creates a new QueuePauseAction that makes the member on the given * interface available or unavailable on all queues. - * - * @param iface the interface of the member to make unavailable + * + * @param iface the interface of the member to make unavailable * @param paused Boolean.TRUE to make the member unavailbale, Boolean.FALSE - * to make the member available + * to make the member available */ - public QueuePauseAction(String iface, Boolean paused) - { + public QueuePauseAction(String iface, Boolean paused) { this.iface = iface; this.paused = paused; } @@ -88,14 +84,13 @@ public QueuePauseAction(String iface, Boolean paused) /** * Creates a new QueuePauseAction that makes the member on the given * interface unavailable on the given queue. - * - * @param iface the interface of the member to make unavailable - * @param queue the queue the member is made unvailable on + * + * @param iface the interface of the member to make unavailable + * @param queue the queue the member is made unvailable on * @param paused Boolean.TRUE to make the member unavailbale, Boolean.FALSE - * to make the member available + * to make the member available */ - public QueuePauseAction(String iface, String queue, Boolean paused) - { + public QueuePauseAction(String iface, String queue, Boolean paused) { this.iface = iface; this.queue = queue; this.paused = paused; @@ -103,81 +98,94 @@ public QueuePauseAction(String iface, String queue, Boolean paused) /** * Returns the name of this action, i.e. "QueuePause". - * + * * @return the name of this action. */ @Override - public String getAction() - { + public String getAction() { return "QueuePause"; } /** * Returns the interface of the member to make available or unavailable. - * + * * @return the interface of the member to make available or unavailable. */ - public String getInterface() - { + public String getInterface() { return iface; } /** * Sets the interface of the member to make available or unavailable.

      * This property is mandatory. - * + * * @param iface the interface of the member to make available or - * unavailable. + * unavailable. */ - public void setInterface(String iface) - { + public void setInterface(String iface) { this.iface = iface; } /** * Returns the name of the queue the member is made available or unavailable * on. - * + * * @return the name of the queue the member is made available or unavailable - * on or null for all queues. + * on or null for all queues. */ - public String getQueue() - { + public String getQueue() { return queue; } /** * Sets the name of the queue the member is made available or unavailable * on. - * + * * @param queue the name of the queue the member is made available or - * unavailable on or null for all queues. + * unavailable on or null for all queues. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } /** * Returns if the member is made available or unavailable. - * + * * @return Boolean.TRUE to make the member unavailbale, Boolean.FALSE to - * make the member available + * make the member available */ - public Boolean getPaused() - { + public Boolean getPaused() { return paused; } /** * Sets if the member is made available or unavailable.

      * This property is mandatory. - * + * * @param paused Boolean.TRUE to make the member unavailbale, Boolean.FALSE - * to make the member available + * to make the member available */ - public void setPaused(Boolean paused) - { + public void setPaused(Boolean paused) { this.paused = paused; } + + /** + * Sets the name of the local reason.

      + * Available since Asterisk 1.6. + * + * @return Name of the local reason for clears the flag. + */ + public String getReason() { + return reason; + } + + /** + * Returns the name of the reason.

      + * Available since Asterisk 1.6. + * + * @param reason Name of the local reason for clears the flag. + */ + public void setReason(String reason) { + this.reason = reason; + } } diff --git a/src/main/java/org/asteriskjava/manager/action/QueuePenaltyAction.java b/src/main/java/org/asteriskjava/manager/action/QueuePenaltyAction.java index 8f6d91410..4d3405f16 100644 --- a/src/main/java/org/asteriskjava/manager/action/QueuePenaltyAction.java +++ b/src/main/java/org/asteriskjava/manager/action/QueuePenaltyAction.java @@ -25,8 +25,7 @@ * @version $Id$ * @since 1.0.0 */ -public class QueuePenaltyAction extends AbstractManagerAction -{ +public class QueuePenaltyAction extends AbstractManagerAction { /** * Serializable version identifier. */ @@ -39,8 +38,7 @@ public class QueuePenaltyAction extends AbstractManagerAction /** * Creates a new empty QueuePenaltyAction. */ - public QueuePenaltyAction() - { + public QueuePenaltyAction() { } @@ -51,8 +49,7 @@ public QueuePenaltyAction() * @param iface the interface of the member to set the penalty for * @param penalty new penalty value. */ - public QueuePenaltyAction(String iface, int penalty) - { + public QueuePenaltyAction(String iface, int penalty) { this.iface = iface; this.penalty = penalty; } @@ -65,8 +62,7 @@ public QueuePenaltyAction(String iface, int penalty) * @param penalty new penalty value. * @param queue the queue the member is assigned the penalty for */ - public QueuePenaltyAction(String iface, int penalty, String queue) - { + public QueuePenaltyAction(String iface, int penalty, String queue) { this.iface = iface; this.penalty = penalty; this.queue = queue; @@ -78,8 +74,7 @@ public QueuePenaltyAction(String iface, int penalty, String queue) * @return the name of this action. */ @Override - public String getAction() - { + public String getAction() { return "QueuePenalty"; } @@ -88,8 +83,7 @@ public String getAction() * * @return the interface of the member to to set the penalty for. */ - public String getInterface() - { + public String getInterface() { return iface; } @@ -99,8 +93,7 @@ public String getInterface() * * @param iface the interface of the member to to set the penalty for. */ - public void setInterface(String iface) - { + public void setInterface(String iface) { this.iface = iface; } @@ -109,8 +102,7 @@ public void setInterface(String iface) * * @return the new penalty. */ - public Integer getPenalty() - { + public Integer getPenalty() { return penalty; } @@ -120,8 +112,7 @@ public Integer getPenalty() * * @param penalty the new penalty. */ - public void setPenalty(Integer penalty) - { + public void setPenalty(Integer penalty) { this.penalty = penalty; } @@ -130,8 +121,7 @@ public void setPenalty(Integer penalty) * * @return the name of the queue. */ - public String getQueue() - { + public String getQueue() { return queue; } @@ -140,8 +130,7 @@ public String getQueue() * * @param queue the name of the queue or null for all queues. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/QueueRemoveAction.java b/src/main/java/org/asteriskjava/manager/action/QueueRemoveAction.java index 4f1ff5d60..b474715f2 100644 --- a/src/main/java/org/asteriskjava/manager/action/QueueRemoveAction.java +++ b/src/main/java/org/asteriskjava/manager/action/QueueRemoveAction.java @@ -19,12 +19,11 @@ /** * The QueueRemoveAction removes a member from a queue.

      * It is implemented in apps/app_queue.c - * + * * @author srt * @version $Id$ */ -public class QueueRemoveAction extends AbstractManagerAction -{ +public class QueueRemoveAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -39,62 +38,56 @@ public class QueueRemoveAction extends AbstractManagerAction /** * Creates a new empty QueueRemoveAction. */ - public QueueRemoveAction() - { + public QueueRemoveAction() { } /** * Creates a new QueueRemoveAction that removes the member on the given * interface from the given queue. - * + * * @param queue the name of the queue the member will be removed from * @param iface the interface of the member to remove * @since 0.2 */ - public QueueRemoveAction(String queue, String iface) - { + public QueueRemoveAction(String queue, String iface) { this.queue = queue; this.iface = iface; } /** * Returns the name of this action, i.e. "QueueRemove". - * + * * @return the name of this action. */ @Override - public String getAction() - { + public String getAction() { return "QueueRemove"; } /** * Returns the name of the queue the member will be removed from. - * + * * @return the name of the queue the member will be removed from. */ - public String getQueue() - { + public String getQueue() { return queue; } /** * Sets the name of the queue the member will be removed from.

      * This property is mandatory. - * + * * @param queue the name of the queue the member will be removed from. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } /** * Returns the interface to remove. */ - public String getInterface() - { + public String getInterface() { return iface; } @@ -102,8 +95,7 @@ public String getInterface() * Sets the interface to remove.

      * This property is mandatory. */ - public void setInterface(String iface) - { + public void setInterface(String iface) { this.iface = iface; } } diff --git a/src/main/java/org/asteriskjava/manager/action/QueueResetAction.java b/src/main/java/org/asteriskjava/manager/action/QueueResetAction.java index e602aadf3..c9158d1e3 100644 --- a/src/main/java/org/asteriskjava/manager/action/QueueResetAction.java +++ b/src/main/java/org/asteriskjava/manager/action/QueueResetAction.java @@ -24,8 +24,7 @@ * @author Sebastian * @since 1.0.0 */ -public class QueueResetAction extends AbstractManagerAction -{ +public class QueueResetAction extends AbstractManagerAction { private static final long serialVersionUID = 1L; private String queue; @@ -33,8 +32,7 @@ public class QueueResetAction extends AbstractManagerAction /** * Creates a new QueueResetAction that resets statistical data of all queues. */ - public QueueResetAction() - { + public QueueResetAction() { } /** @@ -42,14 +40,12 @@ public QueueResetAction() * * @param queue the name of the queue to reset. */ - public QueueResetAction(String queue) - { + public QueueResetAction(String queue) { this.queue = queue; } @Override - public String getAction() - { + public String getAction() { return "QueueReset"; } @@ -58,8 +54,7 @@ public String getAction() * * @return the name of the queue to reset or null for all queues. */ - public String getQueue() - { + public String getQueue() { return queue; } @@ -68,8 +63,7 @@ public String getQueue() * * @param queue the name of the queue to reset or null for all queues. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } } diff --git a/src/main/java/org/asteriskjava/manager/action/QueueStatusAction.java b/src/main/java/org/asteriskjava/manager/action/QueueStatusAction.java index 1d24cc397..d92958778 100644 --- a/src/main/java/org/asteriskjava/manager/action/QueueStatusAction.java +++ b/src/main/java/org/asteriskjava/manager/action/QueueStatusAction.java @@ -28,18 +28,17 @@ * Since Asterisk 1.2 a QueueStatusCompleteEvent is sent to denote the end of * the generated dump.

      * This action is implemented in apps/app_queue.c - * + * + * @author srt + * @version $Id$ * @see org.asteriskjava.manager.event.QueueParamsEvent * @see org.asteriskjava.manager.event.QueueMemberEvent * @see org.asteriskjava.manager.event.QueueEntryEvent * @see org.asteriskjava.manager.event.QueueStatusCompleteEvent - * @author srt - * @version $Id$ */ public class QueueStatusAction extends AbstractManagerAction implements - EventGeneratingAction -{ + EventGeneratingAction { /** * Serializable version identifier */ @@ -51,8 +50,7 @@ public class QueueStatusAction extends AbstractManagerAction /** * Creates a new QueueStatusAction. */ - public QueueStatusAction() - { + public QueueStatusAction() { } @@ -60,59 +58,53 @@ public QueueStatusAction() * Returns the name of this action, i.e. "QueueStatus". */ @Override - public String getAction() - { + public String getAction() { return "QueueStatus"; } /** * Returns the queue filter. - * + * * @return the queue filter. * @since 0.2 */ - public String getQueue() - { + public String getQueue() { return queue; } /** * Sets the queue filter. If set QueueParamEvents are only generated for the * given queue name. - * + * * @param queue the queue filter. * @since 0.2 */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } /** * Returns the member filter. - * + * * @return the member filter. * @since 0.2 */ - public String getMember() - { + public String getMember() { return member; } /** * Sets the member filter. If set QueueMemberEvents are only generated for the * given member name. - * + * * @param member the member filter. * @since 0.2 */ - public void setMember(String member) - { + public void setMember(String member) { this.member = member; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return QueueStatusCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/QueueSummaryAction.java b/src/main/java/org/asteriskjava/manager/action/QueueSummaryAction.java index b4899861d..c1a5520ec 100644 --- a/src/main/java/org/asteriskjava/manager/action/QueueSummaryAction.java +++ b/src/main/java/org/asteriskjava/manager/action/QueueSummaryAction.java @@ -10,16 +10,15 @@ * Available in Asterisk post-1.4. *

      * This action has been added by - * {@linkplain http://bugs.digium.com/view.php?id=8035}. - * - * @see QueueSummaryEvent - * @see QueueSummaryCompleteEvent + * http://bugs.digium.com/view.php?id=8035. + * * @author srt * @version $Id$ + * @see QueueSummaryEvent + * @see QueueSummaryCompleteEvent * @since 0.3 */ -public class QueueSummaryAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class QueueSummaryAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serial version identifier. */ @@ -30,52 +29,46 @@ public class QueueSummaryAction extends AbstractManagerAction implements EventGe * Creates a new QueueSummaryAction that retrieves the summary for all * queues. */ - public QueueSummaryAction() - { + public QueueSummaryAction() { } /** * Creates a new QueueSummaryAction that retrieves the summary for the given * queue. - * + * * @param queue name of the queue to retrieve the summary for. */ - public QueueSummaryAction(String queue) - { + public QueueSummaryAction(String queue) { this.queue = queue; } @Override - public String getAction() - { + public String getAction() { return "QueueSummary"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return QueueSummaryCompleteEvent.class; } /** * Returns the name of the queue to retrieve the summary for. - * + * * @return the name of the queue to retrieve the summary for or - * null to retrieve the summary for all queues. + * null to retrieve the summary for all queues. */ - public String getQueue() - { + public String getQueue() { return queue; } /** * Sets the name of the queue to retrieve the summary for. - * + * * @param queue the name of the queue to retrieve the summary for or - * null to retrieve the summary for all queues. + * null to retrieve the summary for all queues. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } } diff --git a/src/main/java/org/asteriskjava/manager/action/RedirectAction.java b/src/main/java/org/asteriskjava/manager/action/RedirectAction.java index ea2cc5ebe..0632ed4ec 100644 --- a/src/main/java/org/asteriskjava/manager/action/RedirectAction.java +++ b/src/main/java/org/asteriskjava/manager/action/RedirectAction.java @@ -18,21 +18,22 @@ /** * Redirects a given channel (and an optional additional channel) to a new - * extension.

      + * extension. + *

      * The additional channel is usually used when redirecting two bridged channel - * for example to a MeetMe room.

      - * Note that BRIstuffed versions of Asterisk behave slightly different: - * While the standard version only allows redirecting the two channels to the same - * context, extension, priority the BRIstuffed version uses context, extension, - * priority only for the first channel and extraContext, extraExtension, - * extraPriority for the second channel. The standard version ignores the - * extraContext, extraExtension, extraPriority properties. - * + * for example to a MeetMe room. + *

      + * Note that BRIstuffed versions of Asterisk behave slightly different: While + * the standard version only allows redirecting the two channels to the same + * context, extension, priority the BRIstuffed version uses context, extension, + * priority only for the first channel and extraContext, extraExtension, + * extraPriority for the second channel. The standard version ignores the + * extraContext, extraExtension, extraPriority properties. + * * @author srt * @version $Id$ */ -public class RedirectAction extends AbstractManagerAction -{ +public class RedirectAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -50,24 +51,21 @@ public class RedirectAction extends AbstractManagerAction /** * Creates a new empty RedirectAction. */ - public RedirectAction() - { + public RedirectAction() { } /** * Creates a new RedirectAction that redirects the given channel to the * given context, extension, priority triple. - * - * @param channel the name of the channel to redirect - * @param context the destination context - * @param exten the destination extension + * + * @param channel the name of the channel to redirect + * @param context the destination context + * @param exten the destination extension * @param priority the destination priority * @since 0.2 */ - public RedirectAction(String channel, String context, String exten, - Integer priority) - { + public RedirectAction(String channel, String context, String exten, Integer priority) { this.channel = channel; this.context = context; this.exten = exten; @@ -76,22 +74,21 @@ public RedirectAction(String channel, String context, String exten, /** * Creates a new RedirectAction that redirects the given channels to the - * given context, extension, priority triple.

      - * This constructor only works standard versions of Asterisk, i.e. non-BRIstuffed - * versions. - * When used with a BRIstuffed version (and not setting extraContext, extraExten and - * extraPriority) the second channel is just hung up. - * - * @param channel the name of the first channel to redirect + * given context, extension, priority triple. + *

      + * This constructor only works standard versions of Asterisk, i.e. + * non-BRIstuffed versions. When used with a BRIstuffed version (and not + * setting extraContext, extraExten and extraPriority) the second channel is + * just hung up. + * + * @param channel the name of the first channel to redirect * @param extraChannel the name of the second channel to redirect - * @param context the destination context - * @param exten the destination extension - * @param priority the destination priority + * @param context the destination context + * @param exten the destination extension + * @param priority the destination priority * @since 0.2 */ - public RedirectAction(String channel, String extraChannel, String context, - String exten, Integer priority) - { + public RedirectAction(String channel, String extraChannel, String context, String exten, Integer priority) { this.channel = channel; this.extraChannel = extraChannel; this.context = context; @@ -101,25 +98,24 @@ public RedirectAction(String channel, String extraChannel, String context, /** * Creates a new RedirectAction that redirects the given channels to the - * given context, extension, priority triples.

      - * This constructor works for BRIstuffed versions of Asterisk, if used - * with a standard version the extraContext, extraExten and - * extraPriroity attributes are ignored. - * - * @param channel the name of the first channel to redirect - * @param extraChannel the name of the second channel to redirect - * @param context the destination context for the first channel - * @param exten the destination extension for the first channel - * @param priority the destination priority for the first channel - * @param extraContext the destination context for the second channel - * @param extraExten the destination extension for the second channel + * given context, extension, priority triples. + *

      + * This constructor works for BRIstuffed versions of Asterisk, if used with + * a standard version the extraContext, extraExten and extraPriroity + * attributes are ignored. + * + * @param channel the name of the first channel to redirect + * @param extraChannel the name of the second channel to redirect + * @param context the destination context for the first channel + * @param exten the destination extension for the first channel + * @param priority the destination priority for the first channel + * @param extraContext the destination context for the second channel + * @param extraExten the destination extension for the second channel * @param extraPriority the destination priority for the second channel * @since 0.3 */ - public RedirectAction(String channel, String extraChannel, String context, - String exten, Integer priority, String extraContext, - String extraExten, Integer extraPriority) - { + public RedirectAction(String channel, String extraChannel, String context, String exten, Integer priority, + String extraContext, String extraExten, Integer extraPriority) { this.channel = channel; this.extraChannel = extraChannel; this.context = context; @@ -128,180 +124,175 @@ public RedirectAction(String channel, String extraChannel, String context, this.extraContext = extraContext; this.extraExten = extraExten; this.extraPriority = extraPriority; + if (channel.equalsIgnoreCase(extraChannel)) { + throw new RuntimeException("ExtraChannel = channel ... bad things will happen to asterisk"); + } } /** * Returns the name of this action, i.e. "Redirect". */ @Override - public String getAction() - { + public String getAction() { return "Redirect"; } /** * Returns name of the channel to redirect. - * + * * @return the name of the channel to redirect */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel to redirect. - * + * * @param channel the name of the channel to redirect */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the name of the additional channel to redirect. - * + * * @return the name of the additional channel to redirect */ - public String getExtraChannel() - { + public String getExtraChannel() { return extraChannel; } /** * Sets the name of the additional channel to redirect. - * + * * @param extraChannel the name of the additional channel to redirect */ - public void setExtraChannel(String extraChannel) - { + public void setExtraChannel(String extraChannel) { this.extraChannel = extraChannel; + if (channel.equalsIgnoreCase(extraChannel)) { + throw new RuntimeException("ExtraChannel = channel ... bad things will happen to asterisk"); + } } /** * Returns the destination context. - * + * * @return the destination context */ - public String getContext() - { + public String getContext() { return context; } /** * Sets the destination context. - * + * * @param context the destination context */ - public void setContext(String context) - { + public void setContext(String context) { this.context = context; } /** * Returns the destination extension. - * + * * @return the destination extension */ - public String getExten() - { + public String getExten() { return exten; } /** * Sets the destination extension. - * + * * @param exten the destination extension */ - public void setExten(String exten) - { + public void setExten(String exten) { this.exten = exten; } /** * Returns the destination priority. - * + * * @return the destination priority */ - public Integer getPriority() - { + public Integer getPriority() { return priority; } /** * Sets the destination priority. - * + * * @param priority the destination priority */ - public void setPriority(Integer priority) - { + public void setPriority(Integer priority) { this.priority = priority; } /** - * Returns the destination context for the additional channel.

      + * Returns the destination context for the additional channel. + *

      * This property is only used by BRIstuffed Asterisk servers. - * + * * @return the destination context for the additional channel. */ - public String getExtraContext() - { + public String getExtraContext() { return extraContext; } /** - * Sets the destination context for the additional channel.

      + * Sets the destination context for the additional channel. + *

      * This property is only used by BRIstuffed Asterisk servers. - * + * * @param extraContext the destination context for the additional channel. */ - public void setExtraContext(String extraContext) - { + public void setExtraContext(String extraContext) { this.extraContext = extraContext; } /** - * Sets the destination extension for the additional channel.

      + * Sets the destination extension for the additional channel. + *

      * This property is only used by BRIstuffed Asterisk servers. - * + * * @return the destination extension for the additional channel. */ - public String getExtraExten() - { + public String getExtraExten() { return extraExten; } /** - * Sets the destination extension for the additional channel.

      + * Sets the destination extension for the additional channel. + *

      * This property is only used by BRIstuffed Asterisk servers. - * + * * @param extraExten the destination extension for the additional channel. */ - public void setExtraExten(String extraExten) - { + public void setExtraExten(String extraExten) { this.extraExten = extraExten; } /** - * Returns the destination priority for the additional channel.

      + * Returns the destination priority for the additional channel. + *

      * This property is only used by BRIstuffed Asterisk servers. - * + * * @return the destination priority for the additional channel. */ - public Integer getExtraPriority() - { + public Integer getExtraPriority() { return extraPriority; } /** - * Sets the destination priority for the additional channel.

      + * Sets the destination priority for the additional channel. + *

      * This property is only used by BRIstuffed Asterisk servers. - * + * * @param extraPriority the destination priority for the additional channel. */ - public void setExtraPriority(Integer extraPriority) - { + public void setExtraPriority(Integer extraPriority) { this.extraPriority = extraPriority; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SendTextAction.java b/src/main/java/org/asteriskjava/manager/action/SendTextAction.java index c2545e71b..8d9ea69d4 100644 --- a/src/main/java/org/asteriskjava/manager/action/SendTextAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SendTextAction.java @@ -26,8 +26,7 @@ * @version $Id$ * @since 1.0.0 */ -public class SendTextAction extends AbstractManagerAction -{ +public class SendTextAction extends AbstractManagerAction { private static final long serialVersionUID = 1L; private String channel; @@ -36,8 +35,7 @@ public class SendTextAction extends AbstractManagerAction /** * Creates a new empty SendTextAction. */ - public SendTextAction() - { + public SendTextAction() { super(); } @@ -47,8 +45,7 @@ public SendTextAction() * @param channel the name of the channel to send the message to. * @param message the message to send. */ - public SendTextAction(String channel, String message) - { + public SendTextAction(String channel, String message) { super(); this.channel = channel; this.message = message; @@ -58,8 +55,7 @@ public SendTextAction(String channel, String message) * Returns the name of this action, i.e. "SendText". */ @Override - public String getAction() - { + public String getAction() { return "SendText"; } @@ -68,8 +64,7 @@ public String getAction() * * @return the name of the channel to send the message to. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -78,8 +73,7 @@ public String getChannel() * * @param channel the name of the channel to send the message to. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -88,8 +82,7 @@ public void setChannel(String channel) * * @return the message to send. */ - public String getMessage() - { + public String getMessage() { return message; } @@ -98,8 +91,7 @@ public String getMessage() * * @param message the message to send. */ - public void setMessage(String message) - { + public void setMessage(String message) { this.message = message; - } + } } diff --git a/src/main/java/org/asteriskjava/manager/action/SetCdrUserFieldAction.java b/src/main/java/org/asteriskjava/manager/action/SetCdrUserFieldAction.java index 503393557..d9ffcb5e3 100644 --- a/src/main/java/org/asteriskjava/manager/action/SetCdrUserFieldAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SetCdrUserFieldAction.java @@ -23,12 +23,11 @@ * overwritten.

      * The SetCDRUserFieldAction is implemented in * apps/app_setcdruserfield.c - * + * * @author srt * @version $Id$ */ -public class SetCdrUserFieldAction extends AbstractManagerAction -{ +public class SetCdrUserFieldAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -40,21 +39,19 @@ public class SetCdrUserFieldAction extends AbstractManagerAction /** * Creates a new empty SetCdrUserFieldAction. */ - public SetCdrUserFieldAction() - { + public SetCdrUserFieldAction() { } /** * Creates a new SetCdrUserFieldAction that sets the user field of the call * detail record for the given channel to the given value. - * - * @param channel the name of the channel + * + * @param channel the name of the channel * @param userField the new value of the userfield * @since 0.2 */ - public SetCdrUserFieldAction(String channel, String userField) - { + public SetCdrUserFieldAction(String channel, String userField) { this.channel = channel; this.userField = userField; } @@ -62,16 +59,15 @@ public SetCdrUserFieldAction(String channel, String userField) /** * Creates a new SetCDRUserFieldAction that sets the user field of the call * detail record for the given channel to the given value. - * - * @param channel the name of the channel + * + * @param channel the name of the channel * @param userField the new value of the userfield - * @param append true to append the value to the cdr user field or false to - * overwrite + * @param append true to append the value to the cdr user field or false to + * overwrite * @since 0.2 */ public SetCdrUserFieldAction(String channel, String userField, - Boolean append) - { + Boolean append) { this.channel = channel; this.userField = userField; this.append = append; @@ -81,16 +77,14 @@ public SetCdrUserFieldAction(String channel, String userField, * Returns the name of the action, i.e. "SetCDRUserField". */ @Override - public String getAction() - { + public String getAction() { return "SetCDRUserField"; } /** * Returns the name of the channel to set the cdr user field on. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -98,16 +92,14 @@ public String getChannel() * Sets the name of the channel to set the cdr user field on.

      * This property is mandatory. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the value of the cdr user field to set or append. */ - public String getUserField() - { + public String getUserField() { return userField; } @@ -115,16 +107,14 @@ public String getUserField() * Sets the value of the cdr user field to set or append.

      * This property is mandatory. */ - public void setUserField(String userField) - { + public void setUserField(String userField) { this.userField = userField; } /** * Returns if the value of the cdr user field is appended or overwritten. */ - public Boolean getAppend() - { + public Boolean getAppend() { return append; } @@ -132,8 +122,7 @@ public Boolean getAppend() * Set to true to append the value to the cdr user field or false to * overwrite. */ - public void setAppend(Boolean append) - { + public void setAppend(Boolean append) { this.append = append; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SetVarAction.java b/src/main/java/org/asteriskjava/manager/action/SetVarAction.java index 515cac093..120e996ac 100644 --- a/src/main/java/org/asteriskjava/manager/action/SetVarAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SetVarAction.java @@ -19,13 +19,12 @@ /** * The SetVarAction sets the value of a global or local channel variable.

      * Setting global variables is supported since Asterisk 1.2. - * - * @author Asteria Solutions Group, Inc. + * + * @author Asteria Solutions Group, Inc. http://www.asteriasgi.com * @author srt * @version $Id$ */ -public class SetVarAction extends AbstractManagerAction -{ +public class SetVarAction extends AbstractManagerAction { /** * Serial version identifier */ @@ -34,50 +33,47 @@ public class SetVarAction extends AbstractManagerAction /** * The channel on which to set the variable. */ - public String channel; + private String channel; /** * The name of the variable to set. */ - public String variable; + private String variable; /** * The value to store. */ - public String value; + private String value; /** * Creates a new empty SetVarAction. */ - public SetVarAction() - { + public SetVarAction() { } /** * Creates a new SetVarAction that sets the given global variable to a new value. - * + * * @param variable the name of the global variable to set - * @param value the new value + * @param value the new value * @since 0.2 */ - public SetVarAction(String variable, String value) - { + public SetVarAction(String variable, String value) { this.variable = variable; this.value = value; } - + /** * Creates a new SetVarAction that sets the given channel variable of the * given channel to a new value. - * - * @param channel the name of the channel to set the variable on + * + * @param channel the name of the channel to set the variable on * @param variable the name of the channel variable - * @param value the new value + * @param value the new value * @since 0.2 */ - public SetVarAction(String channel, String variable, String value) - { + public SetVarAction(String channel, String variable, String value) { this.channel = channel; this.variable = variable; this.value = value; @@ -85,72 +81,65 @@ public SetVarAction(String channel, String variable, String value) /** * Returns the name of this action, i.e. "SetVar". - * + * * @return the name of this action */ @Override - public String getAction() - { + public String getAction() { return "SetVar"; } /** * Returns the name of the channel. - * + * * @return the name of channel. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel. - * + * * @param channel the name of the channel to set. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the name of the variable to set. - * + * * @return the name of the variable to set. */ - public String getVariable() - { + public String getVariable() { return variable; } /** * Sets the name of the variable to set. - * + * * @param variable the name of the variable to set. */ - public void setVariable(String variable) - { + public void setVariable(String variable) { this.variable = variable; } /** * Returns the value to store. - * + * * @return the value to store. */ - public String getValue() - { + public String getValue() { return value; } /** * Sets the value to store. - * + * * @param value the value to set. */ - public void setValue(String value) - { + public void setValue(String value) { this.value = value; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ShowDialplanAction.java b/src/main/java/org/asteriskjava/manager/action/ShowDialplanAction.java index 276c987f1..d7b96f85b 100644 --- a/src/main/java/org/asteriskjava/manager/action/ShowDialplanAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ShowDialplanAction.java @@ -32,26 +32,22 @@ * @see org.asteriskjava.manager.event.ShowDialplanCompleteEvent * @since 1.0.0 */ -public class ShowDialplanAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class ShowDialplanAction extends AbstractManagerAction implements EventGeneratingAction { private static final long serialVersionUID = 1L; /** * Creates a new ShowDialplanAction. */ - public ShowDialplanAction() - { + public ShowDialplanAction() { } @Override - public String getAction() - { + public String getAction() { return "ShowDialplan"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return ShowDialplanCompleteEvent.class; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/SipNotifyAction.java b/src/main/java/org/asteriskjava/manager/action/SipNotifyAction.java index 3584a15f0..13cef02dc 100644 --- a/src/main/java/org/asteriskjava/manager/action/SipNotifyAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SipNotifyAction.java @@ -13,8 +13,7 @@ * @version $Id$ * @since 1.0.0 */ -public class SipNotifyAction extends AbstractManagerAction -{ +public class SipNotifyAction extends AbstractManagerAction { /** * Serializable version identifier. */ @@ -26,8 +25,7 @@ public class SipNotifyAction extends AbstractManagerAction /** * Creates a new SipNotifyAction. */ - public SipNotifyAction() - { + public SipNotifyAction() { super(); } @@ -36,8 +34,7 @@ public SipNotifyAction() * * @param channel the peer to send the notify to either "SIP/peer" or just "peer". */ - public SipNotifyAction(String channel) - { + public SipNotifyAction(String channel) { super(); this.channel = channel; } @@ -46,8 +43,7 @@ public SipNotifyAction(String channel) * Returns the name of this action, i.e. "SipNotify". */ @Override - public String getAction() - { + public String getAction() { return "SipNotify"; } @@ -56,8 +52,7 @@ public String getAction() * * @param channel peer to receive the notify to either "SIP/peer" or just "peer". */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -66,8 +61,7 @@ public void setChannel(String channel) * * @return peer */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -75,11 +69,10 @@ public String getChannel() * Returns the variables to set on the originated call. * * @return a Map containing the variable names as key and their - * values as value. + * values as value. * @since 1.0.0 */ - public Map getVariables() - { + public Map getVariables() { return variables; } @@ -90,11 +83,9 @@ public Map getVariables() * @param value the value of the variable to set. * @since 1.0.0 */ - public void setVariable(String name, String value) - { - if (variables == null) - { - variables = new LinkedHashMap(); + public void setVariable(String name, String value) { + if (variables == null) { + variables = new LinkedHashMap<>(); } variables.put(name, value); @@ -107,8 +98,7 @@ public void setVariable(String name, String value) * values as value. * @since 1.0.0 */ - public void setVariables(Map variables) - { + public void setVariables(Map variables) { this.variables = variables; } diff --git a/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java b/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java index 11de4f2af..212ea7e89 100644 --- a/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java @@ -25,6 +25,8 @@ * the details. When all peers have been reported a PeerlistCompleteEvent is * sent.

      * Available since Asterisk 1.2 + *

      + * Permission required: write=system * * @author srt * @version $Id$ @@ -32,8 +34,7 @@ * @see org.asteriskjava.manager.event.PeerlistCompleteEvent * @since 0.2 */ -public class SipPeersAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class SipPeersAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serial version identifier. */ @@ -42,19 +43,16 @@ public class SipPeersAction extends AbstractManagerAction implements EventGenera /** * Creates a new SipPeersAction. */ - public SipPeersAction() - { + public SipPeersAction() { } @Override - public String getAction() - { + public String getAction() { return "SIPPeers"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return PeerlistCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SipShowPeerAction.java b/src/main/java/org/asteriskjava/manager/action/SipShowPeerAction.java index 2551937d0..6c6428c3f 100644 --- a/src/main/java/org/asteriskjava/manager/action/SipShowPeerAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SipShowPeerAction.java @@ -26,16 +26,15 @@ * to retrieve the properties. Consider using {@link org.asteriskjava.manager.action.SipPeersAction} * instead.

      * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ - * @since 0.2 * @see org.asteriskjava.manager.action.SipPeersAction * @see org.asteriskjava.manager.response.SipShowPeerResponse + * @since 0.2 */ @ExpectedResponse(SipShowPeerResponse.class) -public class SipShowPeerAction extends AbstractManagerAction -{ +public class SipShowPeerAction extends AbstractManagerAction { /** * Serial version identifier. */ @@ -45,8 +44,7 @@ public class SipShowPeerAction extends AbstractManagerAction /** * Creates a new empty SipShowPeerAction. */ - public SipShowPeerAction() - { + public SipShowPeerAction() { } @@ -56,29 +54,26 @@ public SipShowPeerAction() *

      * This is just the peer name without the channel type prefix. For example * if your channel is called "SIP/john", the peer name is just "john". - * + * * @param peer the name of the SIP peer to retrieve details for. * @since 0.2 */ - public SipShowPeerAction(String peer) - { + public SipShowPeerAction(String peer) { this.peer = peer; } @Override - public String getAction() - { + public String getAction() { return "SIPShowPeer"; } /** * Returns the name of the peer to retrieve.

      * This parameter is mandatory. - * + * * @return the name of the peer to retrieve without the channel type prefix. */ - public String getPeer() - { + public String getPeer() { return peer; } @@ -89,11 +84,10 @@ public String getPeer() * if your channel is called "SIP/john", the peer name is just "john". *

      * This parameter is mandatory. - * + * * @param peer the name of the peer to retrieve without the channel type prefix. */ - public void setPeer(String peer) - { + public void setPeer(String peer) { this.peer = peer; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SipShowRegistryAction.java b/src/main/java/org/asteriskjava/manager/action/SipShowRegistryAction.java index 19ad7fa73..2809e83d4 100644 --- a/src/main/java/org/asteriskjava/manager/action/SipShowRegistryAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SipShowRegistryAction.java @@ -33,28 +33,24 @@ * @see RegistryEntryEvent * @since 1.0.0 */ -public class SipShowRegistryAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class SipShowRegistryAction extends AbstractManagerAction implements EventGeneratingAction { /** - * - */ - private static final long serialVersionUID = -4501597578392156556L; + * + */ + private static final long serialVersionUID = -4501597578392156556L; - /** + /** * Creates a new SipShowRegistryAction. */ - public SipShowRegistryAction() - { + public SipShowRegistryAction() { } @Override - public String getAction() - { + public String getAction() { return "SipShowRegistry"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return RegistrationsCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SkypeAccountPropertyAction.java b/src/main/java/org/asteriskjava/manager/action/SkypeAccountPropertyAction.java index 334d89b07..e3367485e 100644 --- a/src/main/java/org/asteriskjava/manager/action/SkypeAccountPropertyAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SkypeAccountPropertyAction.java @@ -25,14 +25,13 @@ * * @since 1.0.0 */ -public class SkypeAccountPropertyAction extends AbstractManagerAction -{ +public class SkypeAccountPropertyAction extends AbstractManagerAction { /** * Serializable version identifier */ static final long serialVersionUID = 1L; private String user; - private Map variables = new HashMap(); + private Map variables = new HashMap<>(); public static final String PROPERTY_SKYPENAME = "skypename"; public static final String PROPERTY_TIMEZONE = "timezone"; @@ -48,8 +47,7 @@ public class SkypeAccountPropertyAction extends AbstractManagerAction /** * Creates a new SkypeAccountPropertyAction. */ - public SkypeAccountPropertyAction() - { + public SkypeAccountPropertyAction() { } @@ -60,8 +58,7 @@ public SkypeAccountPropertyAction() * @param user the Skype username of the user to add the buddy to. * @param variables the properties to set. Must not be null */ - public SkypeAccountPropertyAction(String user, Map variables) - { + public SkypeAccountPropertyAction(String user, Map variables) { this.user = user; setVariables(variables); } @@ -72,8 +69,7 @@ public SkypeAccountPropertyAction(String user, Map variables) * * @return the Skype username of the Skype for Asterisk user. */ - public String getUser() - { + public String getUser() { return user; } @@ -82,42 +78,34 @@ public String getUser() * * @param user the Skype username of the Skype for Asterisk user. */ - public void setUser(String user) - { + public void setUser(String user) { this.user = user; } - public Map getVariables() - { - return new HashMap(variables); + public Map getVariables() { + return new HashMap<>(variables); } - public void setVariables(Map variables) - { - if (variables == null) - { + public void setVariables(Map variables) { + if (variables == null) { throw new IllegalArgumentException("Variables cannot be null"); } - this.variables = new HashMap(variables); + this.variables = new HashMap<>(variables); } - public void setTimezone(String timezone) - { + public void setTimezone(String timezone) { variables.put(PROPERTY_TIMEZONE, timezone); } - public void setSkypename(String skypename) - { + public void setSkypename(String skypename) { variables.put(PROPERTY_SKYPENAME, skypename); } - public void setAvailability(String availability) - { + public void setAvailability(String availability) { variables.put(PROPERTY_AVAILABILITY, availability); } - public void setFullname(String fullname) - { + public void setFullname(String fullname) { variables.put(PROPERTY_FULLNAME, fullname); } @@ -126,8 +114,7 @@ public void setFullname(String fullname) * * @param language the ISO language code. */ - public void setLanguage(String language) - { + public void setLanguage(String language) { variables.put(PROPERTY_LANGUAGE, language); } @@ -136,28 +123,23 @@ public void setLanguage(String language) * * @param country the country code. */ - public void setCountry(String country) - { + public void setCountry(String country) { variables.put(PROPERTY_COUNTRY, country); } - public void setPhoneHome(String phoneHome) - { + public void setPhoneHome(String phoneHome) { variables.put(PROPERTY_PHONE_HOME, phoneHome); } - public void setPhoneOffice(String phoneOffice) - { + public void setPhoneOffice(String phoneOffice) { variables.put(PROPERTY_PHONE_OFFICE, phoneOffice); } - public void setPhoneMobile(String phoneMobile) - { + public void setPhoneMobile(String phoneMobile) { variables.put(PROPERTY_PHONE_MOBILE, phoneMobile); } - public void setAbout(String about) - { + public void setAbout(String about) { variables.put(PROPERTY_ABOUT, about); } @@ -165,8 +147,7 @@ public void setAbout(String about) * Returns the name of this action, i.e. "SkypeAccountProperty". */ @Override - public String getAction() - { + public String getAction() { return "SkypeAccountProperty"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SkypeAddBuddyAction.java b/src/main/java/org/asteriskjava/manager/action/SkypeAddBuddyAction.java index 5a9490323..dacea3a9f 100644 --- a/src/main/java/org/asteriskjava/manager/action/SkypeAddBuddyAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SkypeAddBuddyAction.java @@ -22,8 +22,7 @@ * * @since 1.0.0 */ -public class SkypeAddBuddyAction extends AbstractManagerAction -{ +public class SkypeAddBuddyAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -35,8 +34,7 @@ public class SkypeAddBuddyAction extends AbstractManagerAction /** * Creates a new SkypeAddBuddyAction. */ - public SkypeAddBuddyAction() - { + public SkypeAddBuddyAction() { } @@ -47,8 +45,7 @@ public SkypeAddBuddyAction() * @param user the Skype username of the user to add the buddy to. * @param buddy the Skype username of the buddy. */ - public SkypeAddBuddyAction(String user, String buddy) - { + public SkypeAddBuddyAction(String user, String buddy) { this.user = user; this.buddy = buddy; } @@ -61,8 +58,7 @@ public SkypeAddBuddyAction(String user, String buddy) * @param buddy the Skype username of the buddy. * @param authMsg the auth message. */ - public SkypeAddBuddyAction(String user, String buddy, String authMsg) - { + public SkypeAddBuddyAction(String user, String buddy, String authMsg) { this.user = user; this.buddy = buddy; this.authMsg = authMsg; @@ -74,8 +70,7 @@ public SkypeAddBuddyAction(String user, String buddy, String authMsg) * * @return the Skype username of the Skype for Asterisk user. */ - public String getUser() - { + public String getUser() { return user; } @@ -84,8 +79,7 @@ public String getUser() * * @param user the Skype username of the Skype for Asterisk user. */ - public void setUser(String user) - { + public void setUser(String user) { this.user = user; } @@ -94,8 +88,7 @@ public void setUser(String user) * * @return the Skype username of the buddy. */ - public String getBuddy() - { + public String getBuddy() { return buddy; } @@ -105,8 +98,7 @@ public String getBuddy() * * @param buddy the Skype username of the buddy. */ - public void setBuddy(String buddy) - { + public void setBuddy(String buddy) { this.buddy = buddy; } @@ -115,8 +107,7 @@ public void setBuddy(String buddy) * * @return the auth message. */ - public String getAuthMsg() - { + public String getAuthMsg() { return authMsg; } @@ -125,8 +116,7 @@ public String getAuthMsg() * * @param authMsg the auth message. */ - public void setAuthMsg(String authMsg) - { + public void setAuthMsg(String authMsg) { this.authMsg = authMsg; } @@ -134,8 +124,7 @@ public void setAuthMsg(String authMsg) * Returns the name of this action, i.e. "SkypeAddBuddy". */ @Override - public String getAction() - { + public String getAction() { return "SkypeAddBuddy"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SkypeBuddiesAction.java b/src/main/java/org/asteriskjava/manager/action/SkypeBuddiesAction.java index 60946992a..f7610ba07 100644 --- a/src/main/java/org/asteriskjava/manager/action/SkypeBuddiesAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SkypeBuddiesAction.java @@ -30,8 +30,7 @@ * @see org.asteriskjava.manager.event.SkypeBuddyListCompleteEvent * @since 1.0.0 */ -public class SkypeBuddiesAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class SkypeBuddiesAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serializable version identifier */ @@ -41,8 +40,7 @@ public class SkypeBuddiesAction extends AbstractManagerAction implements EventGe /** * Creates a new SkypeBuddiesAction. */ - public SkypeBuddiesAction() - { + public SkypeBuddiesAction() { } @@ -51,8 +49,7 @@ public SkypeBuddiesAction() * * @param user the Skype username of the user to retrieve the buddy list for. */ - public SkypeBuddiesAction(String user) - { + public SkypeBuddiesAction(String user) { this.user = user; } @@ -62,8 +59,7 @@ public SkypeBuddiesAction(String user) * * @return the Skype username of the user to retrieve the buddy list for. */ - public String getUser() - { + public String getUser() { return user; } @@ -72,8 +68,7 @@ public String getUser() * * @param user the Skype username of the user to retrieve the buddy list for. */ - public void setUser(String user) - { + public void setUser(String user) { this.user = user; } @@ -81,13 +76,11 @@ public void setUser(String user) * Returns the name of this action, i.e. "SkypeBuddies". */ @Override - public String getAction() - { + public String getAction() { return "SkypeBuddies"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return SkypeBuddyListCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SkypeBuddyAction.java b/src/main/java/org/asteriskjava/manager/action/SkypeBuddyAction.java index 738fc9019..a45acc1f2 100644 --- a/src/main/java/org/asteriskjava/manager/action/SkypeBuddyAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SkypeBuddyAction.java @@ -26,8 +26,7 @@ * @since 1.0.0 */ @ExpectedResponse(SkypeBuddyResponse.class) -public class SkypeBuddyAction extends AbstractManagerAction -{ +public class SkypeBuddyAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -38,8 +37,7 @@ public class SkypeBuddyAction extends AbstractManagerAction /** * Creates a new SkypeBuddiesAction. */ - public SkypeBuddyAction() - { + public SkypeBuddyAction() { } @@ -49,8 +47,7 @@ public SkypeBuddyAction() * @param user the Skype username of the user to retrieve the buddy details for. * @param buddy the Skype username of the buddy. */ - public SkypeBuddyAction(String user, String buddy) - { + public SkypeBuddyAction(String user, String buddy) { this.user = user; this.buddy = buddy; } @@ -61,8 +58,7 @@ public SkypeBuddyAction(String user, String buddy) * * @return the Skype username of the Skype for Asterisk user. */ - public String getUser() - { + public String getUser() { return user; } @@ -71,8 +67,7 @@ public String getUser() * * @param user the Skype username of the Skype for Asterisk user. */ - public void setUser(String user) - { + public void setUser(String user) { this.user = user; } @@ -81,8 +76,7 @@ public void setUser(String user) * * @return the Skype username of the buddy. */ - public String getBuddy() - { + public String getBuddy() { return buddy; } @@ -92,8 +86,7 @@ public String getBuddy() * * @param buddy the Skype username of the buddy. */ - public void setBuddy(String buddy) - { + public void setBuddy(String buddy) { this.buddy = buddy; } @@ -101,8 +94,7 @@ public void setBuddy(String buddy) * Returns the name of this action, i.e. "SkypeBuddy". */ @Override - public String getAction() - { + public String getAction() { return "SkypeBuddy"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SkypeChatSendAction.java b/src/main/java/org/asteriskjava/manager/action/SkypeChatSendAction.java index 956b6bdd8..76a961bd0 100644 --- a/src/main/java/org/asteriskjava/manager/action/SkypeChatSendAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SkypeChatSendAction.java @@ -22,8 +22,7 @@ * * @since 1.0.0 */ -public class SkypeChatSendAction extends AbstractManagerAction -{ +public class SkypeChatSendAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -35,20 +34,18 @@ public class SkypeChatSendAction extends AbstractManagerAction /** * Creates a new SkypeAddBuddyAction. */ - public SkypeChatSendAction() - { + public SkypeChatSendAction() { } /** * Creates a new SkypeChatSendAction with the given parameters. * - * @param user the Skype username of the sender of this chat message. + * @param user the Skype username of the sender of this chat message. * @param skypename the Skype username of the recipient of this chat message. - * @param message the message to send. Must not contain newlines but you can use "\r". + * @param message the message to send. Must not contain newlines but you can use "\r". */ - public SkypeChatSendAction(String user, String skypename, String message) - { + public SkypeChatSendAction(String user, String skypename, String message) { this.user = user; this.skypename = skypename; this.message = message; @@ -59,8 +56,7 @@ public SkypeChatSendAction(String user, String skypename, String message) * * @return the Skype username of the recipient of this chat message. */ - public String getSkypename() - { + public String getSkypename() { return skypename; } @@ -69,8 +65,7 @@ public String getSkypename() * * @param skypename the Skype username of the recipient of this chat message. */ - public void setSkypename(String skypename) - { + public void setSkypename(String skypename) { this.skypename = skypename; } @@ -79,8 +74,7 @@ public void setSkypename(String skypename) * * @return the Skype username of the sender of this chat message. */ - public String getUser() - { + public String getUser() { return user; } @@ -89,8 +83,7 @@ public String getUser() * * @param user the Skype username of the sender of this chat message. */ - public void setUser(String user) - { + public void setUser(String user) { this.user = user; } @@ -99,8 +92,7 @@ public void setUser(String user) * * @return the message to send. */ - public String getMessage() - { + public String getMessage() { return message; } @@ -109,8 +101,7 @@ public String getMessage() * * @param message the message to send. */ - public void setMessage(String message) - { + public void setMessage(String message) { this.message = message; } @@ -118,8 +109,7 @@ public void setMessage(String message) * Returns the name of this action, i.e. "SkypeChatSend". */ @Override - public String getAction() - { + public String getAction() { return "SkypeChatSend"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SkypeLicenseListAction.java b/src/main/java/org/asteriskjava/manager/action/SkypeLicenseListAction.java index a81fca4b1..c8787a7e3 100644 --- a/src/main/java/org/asteriskjava/manager/action/SkypeLicenseListAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SkypeLicenseListAction.java @@ -30,8 +30,7 @@ * @see org.asteriskjava.manager.event.SkypeLicenseListCompleteEvent * @since 1.0.0 */ -public class SkypeLicenseListAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class SkypeLicenseListAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serializable version identifier */ @@ -40,8 +39,7 @@ public class SkypeLicenseListAction extends AbstractManagerAction implements Eve /** * Creates a new SkypeLicenseListAction. */ - public SkypeLicenseListAction() - { + public SkypeLicenseListAction() { } @@ -49,13 +47,11 @@ public SkypeLicenseListAction() * Returns the name of this action, i.e. "SkypeLicenseList". */ @Override - public String getAction() - { + public String getAction() { return "SkypeLicenseList"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return SkypeBuddyListCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SkypeLicenseStatusAction.java b/src/main/java/org/asteriskjava/manager/action/SkypeLicenseStatusAction.java index 476d02948..87aff086c 100644 --- a/src/main/java/org/asteriskjava/manager/action/SkypeLicenseStatusAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SkypeLicenseStatusAction.java @@ -26,8 +26,7 @@ * @since 1.0.0 */ @ExpectedResponse(SkypeLicenseStatusResponse.class) -public class SkypeLicenseStatusAction extends AbstractManagerAction -{ +public class SkypeLicenseStatusAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -36,8 +35,7 @@ public class SkypeLicenseStatusAction extends AbstractManagerAction /** * Creates a new SkypeLicenseStatusAction. */ - public SkypeLicenseStatusAction() - { + public SkypeLicenseStatusAction() { } @@ -45,8 +43,7 @@ public SkypeLicenseStatusAction() * Returns the name of this action, i.e. "SkypeLicenseStatus". */ @Override - public String getAction() - { + public String getAction() { return "SkypeLicenseStatus"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/SkypeRemoveBuddyAction.java b/src/main/java/org/asteriskjava/manager/action/SkypeRemoveBuddyAction.java index 94e15d2b0..80fce7212 100644 --- a/src/main/java/org/asteriskjava/manager/action/SkypeRemoveBuddyAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SkypeRemoveBuddyAction.java @@ -22,8 +22,7 @@ * * @since 1.0.0 */ -public class SkypeRemoveBuddyAction extends AbstractManagerAction -{ +public class SkypeRemoveBuddyAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -34,8 +33,7 @@ public class SkypeRemoveBuddyAction extends AbstractManagerAction /** * Creates a new SkypeRemoveBuddyAction. */ - public SkypeRemoveBuddyAction() - { + public SkypeRemoveBuddyAction() { } @@ -46,8 +44,7 @@ public SkypeRemoveBuddyAction() * @param user the Skype username of the user to add the buddy to. * @param buddy the Skype username of the buddy. */ - public SkypeRemoveBuddyAction(String user, String buddy) - { + public SkypeRemoveBuddyAction(String user, String buddy) { this.user = user; this.buddy = buddy; } @@ -58,8 +55,7 @@ public SkypeRemoveBuddyAction(String user, String buddy) * * @return the Skype username of the Skype for Asterisk user. */ - public String getUser() - { + public String getUser() { return user; } @@ -68,8 +64,7 @@ public String getUser() * * @param user the Skype username of the Skype for Asterisk user. */ - public void setUser(String user) - { + public void setUser(String user) { this.user = user; } @@ -78,8 +73,7 @@ public void setUser(String user) * * @return the Skype username of the buddy. */ - public String getBuddy() - { + public String getBuddy() { return buddy; } @@ -89,8 +83,7 @@ public String getBuddy() * * @param buddy the Skype username of the buddy. */ - public void setBuddy(String buddy) - { + public void setBuddy(String buddy) { this.buddy = buddy; } @@ -98,8 +91,7 @@ public void setBuddy(String buddy) * Returns the name of this action, i.e. "SkypeRemoveBuddy". */ @Override - public String getAction() - { + public String getAction() { return "SkypeRemoveBuddy"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/StatusAction.java b/src/main/java/org/asteriskjava/manager/action/StatusAction.java index be38dc963..a3e728d58 100644 --- a/src/main/java/org/asteriskjava/manager/action/StatusAction.java +++ b/src/main/java/org/asteriskjava/manager/action/StatusAction.java @@ -16,11 +16,11 @@ */ package org.asteriskjava.manager.action; -import org.asteriskjava.manager.event.StatusCompleteEvent; import org.asteriskjava.manager.event.ResponseEvent; +import org.asteriskjava.manager.event.StatusCompleteEvent; -import java.util.List; import java.util.Iterator; +import java.util.List; /** * The StatusAction requests the state of all active channels. Alternativly (as of Asterisk 1.6) @@ -33,8 +33,7 @@ * @see org.asteriskjava.manager.event.StatusEvent * @see org.asteriskjava.manager.event.StatusCompleteEvent */ -public class StatusAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class StatusAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serializable version identifier. */ @@ -46,8 +45,7 @@ public class StatusAction extends AbstractManagerAction implements EventGenerati /** * Creates a new StatusAction that retrieves the status of all channels. */ - public StatusAction() - { + public StatusAction() { } @@ -58,8 +56,7 @@ public StatusAction() * @param channel name of the channel. * @since 1.0.0 */ - public StatusAction(String channel) - { + public StatusAction(String channel) { this.channel = channel; } @@ -67,13 +64,11 @@ public StatusAction(String channel) * Returns the name of this action, i.e. "Status". */ @Override - public String getAction() - { + public String getAction() { return "Status"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return StatusCompleteEvent.class; } @@ -84,8 +79,7 @@ public Class getActionCompleteEventClass() * @return the name of the channel or null for all channels. * @since 1.0.0 */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -96,13 +90,11 @@ public String getChannel() * @param channel the name of the channel or null for all channels. * @since 1.0.0 */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - public String getVariables() - { + public String getVariables() { return variables; } @@ -111,11 +103,10 @@ public String getVariables() * Available since Asterisk 1.6. * * @param variables comma separated list of variables to return for each reported channel. - * @see org.asteriskjava.manager.event.StatusEvent#getVariables() + * @see org.asteriskjava.manager.event.StatusEvent#getVariables() * @since 1.0.0 */ - public void setVariables(String variables) - { + public void setVariables(String variables) { this.variables = variables; } @@ -127,18 +118,15 @@ public void setVariables(String variables) * @see org.asteriskjava.manager.event.StatusEvent#getVariables() * @since 1.0.0 */ - public void setVariables(List variables) - { - if (variables == null || variables.isEmpty()) - { + public void setVariables(List variables) { + if (variables == null || variables.isEmpty()) { this.variables = null; return; } Iterator iter = variables.iterator(); - StringBuffer buffer = new StringBuffer(iter.next()); - while (iter.hasNext()) - { + StringBuilder buffer = new StringBuilder(iter.next()); + while (iter.hasNext()) { buffer.append(",").append(iter.next()); } this.variables = buffer.toString(); diff --git a/src/main/java/org/asteriskjava/manager/action/StopMixMonitorAction.java b/src/main/java/org/asteriskjava/manager/action/StopMixMonitorAction.java new file mode 100644 index 000000000..5e5047f19 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/StopMixMonitorAction.java @@ -0,0 +1,107 @@ +/* + * Copyright 2018 CallShaper, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.action; + +/** + * Stop the specified MixMonitor on the specified channel. + *

      + * Available since Asterisk 11 + * + * @see MixMonitorAction + * @see PauseMixMonitorAction + * @see MixMonitorMuteAction + */ +public class StopMixMonitorAction extends AbstractManagerAction { + private static final long serialVersionUID = 1L; + private String channel; + private String mixMonitorId; + + /** + * Creates a new empty StopMixMonitorAction + */ + public StopMixMonitorAction() { + super(); + } + + /** + * Creates a StopMixMonitorAction that stops all MixMonitors on the + * specified channel. + * + * @param channel the name of the channel + */ + public StopMixMonitorAction(String channel) { + this(channel, null); + } + + /** + * Creates a StopMixMonitorAction that stops the specified MixMonitor on + * the specified channel. + * + * @param channel the name of the channel + * @param mixMonitorId the ID of the MixMonitor to stop + */ + public StopMixMonitorAction(String channel, String mixMonitorId) { + this.channel = channel; + this.mixMonitorId = mixMonitorId; + } + + /** + * Returns the name of this action, i.e. "StopMixMonitor" + * + * @return the name of the AMI action that this class implements + */ + @Override + public String getAction() { + return "StopMixMonitor"; + } + + /** + * Returns the name of the Asterisk channel to monitor. + * + * @return the Asterisk channel name + */ + public String getChannel() { + return channel; + } + + /** + * Sets the name of the Asterisk channel to the given value. + * + * @param channel the Asterisk channel name + */ + public void setChannel(String channel) { + this.channel = channel; + } + + /** + * Returns the ID of the MixMonitor to stop. + * + * @return the MixMonitor ID + */ + public String getMixMonitorId() { + return mixMonitorId; + } + + /** + * Sets the ID of the MixMonitor so stop. + * + * @param mixMonitorId the MixMonitor ID + */ + public void setMixMonitorId(String mixMonitorId) { + this.mixMonitorId = mixMonitorId; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/StopMonitorAction.java b/src/main/java/org/asteriskjava/manager/action/StopMonitorAction.java index cca664936..5e5ca8c37 100644 --- a/src/main/java/org/asteriskjava/manager/action/StopMonitorAction.java +++ b/src/main/java/org/asteriskjava/manager/action/StopMonitorAction.java @@ -19,12 +19,11 @@ /** * The StopMonitorAction ends monitoring (recording) a channel.

      * It is implemented in res/res_monitor.c - * + * * @author srt * @version $Id$ */ -public class StopMonitorAction extends AbstractManagerAction -{ +public class StopMonitorAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -38,52 +37,47 @@ public class StopMonitorAction extends AbstractManagerAction /** * Creates a new empty StopMonitorAction. */ - public StopMonitorAction() - { + public StopMonitorAction() { } /** * Creates a new StopMonitorAction that ends monitoring of the given * channel. - * + * * @param channel the name of the channel to stop monitoring. * @since 0.2 */ - public StopMonitorAction(String channel) - { + public StopMonitorAction(String channel) { this.channel = channel; } /** * Returns the name of this action, i.e. "StopMonitor". - * + * * @return the name of this action. */ @Override - public String getAction() - { + public String getAction() { return "StopMonitor"; } /** * Returns the name of the channel to end monitoring. - * + * * @return the name of the channel to end monitoring. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel to end monitoring.

      * This property is mandatory. - * + * * @param channel the name of the channel to end monitoring. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } } diff --git a/src/main/java/org/asteriskjava/manager/action/UnpauseMonitorAction.java b/src/main/java/org/asteriskjava/manager/action/UnpauseMonitorAction.java index 964d1bf76..62821291d 100644 --- a/src/main/java/org/asteriskjava/manager/action/UnpauseMonitorAction.java +++ b/src/main/java/org/asteriskjava/manager/action/UnpauseMonitorAction.java @@ -23,14 +23,13 @@ * It is implemented in res/res_monitor.c *

      * Available since Asterisk 1.4. - * - * @see PauseMonitorAction + * * @author srt - * @since 0.3 * @version $Id$ + * @see PauseMonitorAction + * @since 0.3 */ -public class UnpauseMonitorAction extends AbstractManagerAction -{ +public class UnpauseMonitorAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -44,40 +43,36 @@ public class UnpauseMonitorAction extends AbstractManagerAction /** * Creates a new empty UnpauseMonitorAction. */ - public UnpauseMonitorAction() - { + public UnpauseMonitorAction() { } /** * Creates a new UnpauseMonitorAction that re-enables monitoring the given * channel. - * + * * @param channel the name of the channel re-enable monitoring. */ - public UnpauseMonitorAction(String channel) - { + public UnpauseMonitorAction(String channel) { this.channel = channel; } /** * Returns the name of this action, i.e. "UnpauseMonitor". - * + * * @return the name of this action. */ @Override - public String getAction() - { + public String getAction() { return "UnpauseMonitor"; } /** * Returns the name of the channel to re-enable monitoring. - * + * * @return the name of the channel to re-enable monitoring. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -85,11 +80,10 @@ public String getChannel() * Sets the name of the channel to re-enable monitoring. *

      * This property is mandatory. - * + * * @param channel the name of the channel to re-enable monitoring. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } } diff --git a/src/main/java/org/asteriskjava/manager/action/UpdateConfigAction.java b/src/main/java/org/asteriskjava/manager/action/UpdateConfigAction.java index a27412c21..f3fd0ad43 100644 --- a/src/main/java/org/asteriskjava/manager/action/UpdateConfigAction.java +++ b/src/main/java/org/asteriskjava/manager/action/UpdateConfigAction.java @@ -16,8 +16,8 @@ */ package org.asteriskjava.manager.action; -import java.util.Map; import java.util.HashMap; +import java.util.Map; /** * The UpdateConfigAction sends an UpdateConfig command to the asterisk server. @@ -35,14 +35,13 @@ * Cat-XXXXXX: Category to operate on Var-XXXXXX: Variable to work on * Value-XXXXXX: Value to work on Match-XXXXXX: Extra match required to match * line - * + * + * @author martins * @see org.asteriskjava.manager.response.GetConfigResponse * @see org.asteriskjava.manager.action.UpdateConfigAction#addCommand - * @author martins * @since 0.3 */ -public class UpdateConfigAction extends AbstractManagerAction -{ +public class UpdateConfigAction extends AbstractManagerAction { /** * Serializable version identifier. */ @@ -58,7 +57,7 @@ public class UpdateConfigAction extends AbstractManagerAction public static final String ACTION_UPDATE = "Update"; public static final String ACTION_DELETE = "Delete"; public static final String ACTION_APPEND = "Append"; - + protected String srcFilename; protected String dstFilename; protected String reload; @@ -69,24 +68,22 @@ public class UpdateConfigAction extends AbstractManagerAction /** * Creates a new UpdateConfigAction. */ - public UpdateConfigAction() - { + public UpdateConfigAction() { this.actionCounter = 0; - actions = new HashMap(); + actions = new HashMap<>(); } /** * Creates a new UpdateConfigAction with the given parameters. - * + * * @param srcFilename the name of the file to get. */ - public UpdateConfigAction(String srcFilename, String dstFilename, boolean reload) - { + public UpdateConfigAction(String srcFilename, String dstFilename, boolean reload) { this.actionCounter = 0; this.srcFilename = srcFilename; this.dstFilename = dstFilename; setReload(reload); - actions = new HashMap(); + actions = new HashMap<>(); } /** @@ -95,42 +92,36 @@ public UpdateConfigAction(String srcFilename, String dstFilename, boolean reload * sections, provide a null value to this method. The command index will be * incremented even if you supply a null for all parameters, though the map * will be unaffected. - * + * * @param action Action to Take - * (NewCat,RenameCat,DelCat,Update,Delete,Append), see static - * fields - * @param cat Category to operate on - * @param var Variable to work on - * @param value Value to work on - * @param match Extra match required to match line + * (NewCat,RenameCat,DelCat,Update,Delete,Append), see static + * fields + * @param cat Category to operate on + * @param var Variable to work on + * @param value Value to work on + * @param match Extra match required to match line */ - public void addCommand(String action, String cat, String var, String value, String match) - { + public void addCommand(String action, String cat, String var, String value, String match) { // for convienence of reference, shorter! final String stringCounter = String.format("%06d", this.actionCounter); - if (action != null) - { + if (action != null) { actions.put("Action-" + stringCounter, action); } - if (cat != null) - { + if (cat != null) { actions.put("Cat-" + stringCounter, cat); } - if (var != null) - { + if (var != null) { actions.put("Var-" + stringCounter, var); } - if (value != null) - { + if (value != null) { actions.put("Value-" + stringCounter, value); } - if (match != null) - { + if (match != null) { actions.put("Match-" + stringCounter, match); } @@ -141,73 +132,65 @@ public void addCommand(String action, String cat, String var, String value, Stri * Returns the name of this action, i.e. "UpdateConfig". */ @Override - public String getAction() - { + public String getAction() { return "UpdateConfig"; } /** * Returns the source filename. */ - public String getSrcFilename() - { + public String getSrcFilename() { return srcFilename; } /** * Sets the source filename. */ - public void setSrcFilename(String filename) - { + public void setSrcFilename(String filename) { this.srcFilename = filename; } /** * Returns the destination filename. */ - public String getDstFilename() - { + public String getDstFilename() { return dstFilename; } /** * Sets the source filename. */ - public void setDstFilename(String filename) - { + public void setDstFilename(String filename) { this.dstFilename = filename; } /** * @return should Asterisk reload, or the name of a specific module to - * reload + * reload */ - public String getReload() - { + public String getReload() { return reload; } /** * Sets the reload behavior of this action, or sets a specific module to be * reloaded - * + * * @param reload the reload parameter to set * @see org.asteriskjava.manager.action.UpdateConfigAction#setReload(boolean) */ - public void setReload(String reload) - { + public void setReload(String reload) { this.reload = reload; } /** * Sets the reload behavior of this action. If you don't know what string to * feed Asterisk, this method will provide the appropriate one. - * + * * @param reload the reload parameter to set * @see org.asteriskjava.manager.action.UpdateConfigAction#setReload(String) */ - public void setReload(boolean reload) - { + public void setReload(boolean reload) { this.reload = reload ? UpdateConfigAction.RELOAD_STRING_YES : UpdateConfigAction.RELOAD_STRING_NO; } @@ -217,12 +200,11 @@ public void setReload(boolean reload) * contain the values for those keys. This method will typically only be * used by the ActionBuilder to generate the actual strings to be sent to * the manager interface. - * - * @see org.asteriskjava.manager.action.UpdateConfigAction#addCommand + * * @return a Map of the actions that should be taken + * @see org.asteriskjava.manager.action.UpdateConfigAction#addCommand */ - public Map getAttributes() - { + public Map getAttributes() { return actions; } @@ -231,12 +213,11 @@ public Map getAttributes() * key,value pairs that you would like to send for this command. Setting * your own map will reset the command index to the number of keys in the * Map - * - * @see org.asteriskjava.manager.action.UpdateConfigAction#addCommand + * * @param actions the actions to set + * @see org.asteriskjava.manager.action.UpdateConfigAction#addCommand */ - public void setAttributes(Map actions) - { + public void setAttributes(Map actions) { this.actions = actions; this.actionCounter = actions.keySet().size(); } diff --git a/src/main/java/org/asteriskjava/manager/action/UserEventAction.java b/src/main/java/org/asteriskjava/manager/action/UserEventAction.java index 52167a7fb..f9131a5f7 100644 --- a/src/main/java/org/asteriskjava/manager/action/UserEventAction.java +++ b/src/main/java/org/asteriskjava/manager/action/UserEventAction.java @@ -7,13 +7,12 @@ * This is equivalent to using the UserEvent application in your * dial plan. Before you send this event, you must register your * event class with the registerUserEventClass method of the ManagerConnection. - * + * + * @author Martin * @see org.asteriskjava.manager.event.UserEvent * @see org.asteriskjava.manager.ManagerConnection#registerUserEventClass(Class) - * @author Martin */ -public class UserEventAction extends AbstractManagerAction -{ +public class UserEventAction extends AbstractManagerAction { /** * Serial version identifier */ @@ -24,18 +23,16 @@ public class UserEventAction extends AbstractManagerAction */ private UserEvent userEvent; - public UserEventAction() - { + public UserEventAction() { super(); } /** * Create the userevent action with userEvent as the event it will send - * + * * @param userEvent the subclass representing a custom event */ - public UserEventAction(UserEvent userEvent) - { + public UserEventAction(UserEvent userEvent) { this.userEvent = userEvent; } @@ -43,16 +40,14 @@ public UserEventAction(UserEvent userEvent) * Get the name of this action */ @Override - public String getAction() - { + public String getAction() { return "UserEvent"; } /** * @return the userEvent */ - public UserEvent getUserEvent() - { + public UserEvent getUserEvent() { return userEvent; } @@ -60,8 +55,7 @@ public UserEvent getUserEvent() * @param userEvent the userEvent to set * @see org.asteriskjava.manager.event.UserEvent */ - public void setUserEvent(UserEvent userEvent) - { + public void setUserEvent(UserEvent userEvent) { this.userEvent = userEvent; } } diff --git a/src/main/java/org/asteriskjava/manager/action/VariableInheritance.java b/src/main/java/org/asteriskjava/manager/action/VariableInheritance.java new file mode 100644 index 000000000..27c233b86 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/action/VariableInheritance.java @@ -0,0 +1,15 @@ +package org.asteriskjava.manager.action; + +public enum VariableInheritance { + NONE(""), SINGLE("_"), DOUBLE("__"); + + private String prefix; + + VariableInheritance(String prefix) { + this.prefix = prefix; + } + + String getPrefix() { + return prefix; + } +} diff --git a/src/main/java/org/asteriskjava/manager/action/VoicemailUsersListAction.java b/src/main/java/org/asteriskjava/manager/action/VoicemailUsersListAction.java index 3dac9c935..247c97350 100644 --- a/src/main/java/org/asteriskjava/manager/action/VoicemailUsersListAction.java +++ b/src/main/java/org/asteriskjava/manager/action/VoicemailUsersListAction.java @@ -16,8 +16,8 @@ */ package org.asteriskjava.manager.action; -import org.asteriskjava.manager.event.VoicemailUserEntryCompleteEvent; import org.asteriskjava.manager.event.ResponseEvent; +import org.asteriskjava.manager.event.VoicemailUserEntryCompleteEvent; /** * Retrieves a list of all defined voicemail users.

      @@ -25,7 +25,7 @@ * the details. When all peers have been reported a VoicemailUserEntryCompleteEvent is * sent.

      * It is implemented in apps/app_voicemail.c - *

      + *
      * Available since Asterisk 1.6 * * @author srt @@ -34,8 +34,7 @@ * @see org.asteriskjava.manager.event.VoicemailUserEntryCompleteEvent * @since 1.0.0 */ -public class VoicemailUsersListAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class VoicemailUsersListAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serial version identifier. */ @@ -44,19 +43,16 @@ public class VoicemailUsersListAction extends AbstractManagerAction implements E /** * Creates a new VoicemailUsersListAction. */ - public VoicemailUsersListAction() - { + public VoicemailUsersListAction() { } @Override - public String getAction() - { + public String getAction() { return "VoicemailUsersList"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return VoicemailUserEntryCompleteEvent.class; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/action/ZapDialOffhookAction.java b/src/main/java/org/asteriskjava/manager/action/ZapDialOffhookAction.java index 961d54de3..d561a0a3c 100644 --- a/src/main/java/org/asteriskjava/manager/action/ZapDialOffhookAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ZapDialOffhookAction.java @@ -18,12 +18,11 @@ /** * The ZapDialOffhookAction dials a number on a zap channel while offhook. - * + * * @author srt * @version $Id$ */ -public class ZapDialOffhookAction extends AbstractManagerAction -{ +public class ZapDialOffhookAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -34,21 +33,19 @@ public class ZapDialOffhookAction extends AbstractManagerAction /** * Creates a new empty ZapDialOffhookAction. */ - public ZapDialOffhookAction() - { + public ZapDialOffhookAction() { } /** * Creates a new ZapDialOffhookAction that dials the given number on the * given zap channel. - * + * * @param zapChannel the number of the zap channel - * @param number the number to dial + * @param number the number to dial * @since 0.2 */ - public ZapDialOffhookAction(Integer zapChannel, String number) - { + public ZapDialOffhookAction(Integer zapChannel, String number) { this.zapChannel = zapChannel; this.number = number; } @@ -57,16 +54,14 @@ public ZapDialOffhookAction(Integer zapChannel, String number) * Returns the name of this action, i.e. "ZapDialOffhook". */ @Override - public String getAction() - { + public String getAction() { return "ZapDialOffhook"; } /** * Returns the number of the zap channel. */ - public Integer getZapChannel() - { + public Integer getZapChannel() { return zapChannel; } @@ -74,16 +69,14 @@ public Integer getZapChannel() * Sets the number of the zap channel.

      * This property is mandatory. */ - public void setZapChannel(Integer channel) - { + public void setZapChannel(Integer channel) { this.zapChannel = channel; } /** * Returns the number to dial. */ - public String getNumber() - { + public String getNumber() { return number; } @@ -91,8 +84,7 @@ public String getNumber() * Sets the number to dial.

      * This property is mandatory. */ - public void setNumber(String number) - { + public void setNumber(String number) { this.number = number; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ZapDndOffAction.java b/src/main/java/org/asteriskjava/manager/action/ZapDndOffAction.java index 18e320f9c..4cfb4f386 100644 --- a/src/main/java/org/asteriskjava/manager/action/ZapDndOffAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ZapDndOffAction.java @@ -18,12 +18,11 @@ /** * The ZapDNDOnAction switches a zap channel "Do Not Disturb" status off. - * + * * @author srt * @version $Id$ */ -public class ZapDndOffAction extends AbstractManagerAction -{ +public class ZapDndOffAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -33,20 +32,18 @@ public class ZapDndOffAction extends AbstractManagerAction /** * Creates a new empty ZapDndOffAction. */ - public ZapDndOffAction() - { + public ZapDndOffAction() { } /** * Creates a new ZapDndOffAction that disables "Do Not Disturb" status for * the given zap channel. - * + * * @param zapChannel the number of the zap channel * @since 0.2 */ - public ZapDndOffAction(Integer zapChannel) - { + public ZapDndOffAction(Integer zapChannel) { this.zapChannel = zapChannel; } @@ -54,16 +51,14 @@ public ZapDndOffAction(Integer zapChannel) * Returns the name of this action, i.e. "ZapDNDOff". */ @Override - public String getAction() - { + public String getAction() { return "ZapDNDOff"; } /** * Returns the number of the zap channel to switch to dnd off. */ - public Integer getZapChannel() - { + public Integer getZapChannel() { return zapChannel; } @@ -71,8 +66,7 @@ public Integer getZapChannel() * Sets the number of the zap channel to switch to dnd off.

      * This property is mandatory. */ - public void setZapChannel(Integer channel) - { + public void setZapChannel(Integer channel) { this.zapChannel = channel; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ZapDndOnAction.java b/src/main/java/org/asteriskjava/manager/action/ZapDndOnAction.java index f18beba34..f1c87c33b 100644 --- a/src/main/java/org/asteriskjava/manager/action/ZapDndOnAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ZapDndOnAction.java @@ -18,12 +18,11 @@ /** * The ZapDNDOnAction switches a zap channel "Do Not Disturb" status on. - * + * * @author srt * @version $Id$ */ -public class ZapDndOnAction extends AbstractManagerAction -{ +public class ZapDndOnAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -33,37 +32,33 @@ public class ZapDndOnAction extends AbstractManagerAction /** * Creates a new empty ZapDndOnAction. */ - public ZapDndOnAction() - { + public ZapDndOnAction() { } /** * Creates a new ZapDndOnAction that enables "Do Not Disturb" status for * the given zap channel. - * + * * @param zapChannel the number of the zap channel * @since 0.2 */ - public ZapDndOnAction(Integer zapChannel) - { + public ZapDndOnAction(Integer zapChannel) { this.zapChannel = zapChannel; } - + /** * Returns the name of this action, i.e. "ZapDNDOn". */ @Override - public String getAction() - { + public String getAction() { return "ZapDNDOn"; } /** * Returns the number of the zap channel to switch to dnd on. */ - public Integer getZapChannel() - { + public Integer getZapChannel() { return zapChannel; } @@ -71,8 +66,7 @@ public Integer getZapChannel() * Sets the number of the zap channel to switch to dnd on.

      * This property is mandatory. */ - public void setZapChannel(Integer channel) - { + public void setZapChannel(Integer channel) { this.zapChannel = channel; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ZapHangupAction.java b/src/main/java/org/asteriskjava/manager/action/ZapHangupAction.java index 0d1484f5e..ee1a4a15f 100644 --- a/src/main/java/org/asteriskjava/manager/action/ZapHangupAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ZapHangupAction.java @@ -18,12 +18,11 @@ /** * The ZapHangupAction hangs up a zap channel. - * + * * @author srt * @version $Id$ */ -public class ZapHangupAction extends AbstractManagerAction -{ +public class ZapHangupAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -33,19 +32,17 @@ public class ZapHangupAction extends AbstractManagerAction /** * Creates a new empty ZapHangupAction. */ - public ZapHangupAction() - { + public ZapHangupAction() { } /** * Creates a new ZapHangupAction that hangs up the given zap channel. - * + * * @param zapChannel the number of the zap channel to hang up * @since 0.2 */ - public ZapHangupAction(Integer zapChannel) - { + public ZapHangupAction(Integer zapChannel) { this.zapChannel = zapChannel; } @@ -53,16 +50,14 @@ public ZapHangupAction(Integer zapChannel) * Returns the name of this action, i.e. "ZapHangup". */ @Override - public String getAction() - { + public String getAction() { return "ZapHangup"; } /** * Returns the number of the zap channel to hangup. */ - public Integer getZapChannel() - { + public Integer getZapChannel() { return zapChannel; } @@ -70,8 +65,7 @@ public Integer getZapChannel() * Sets the number of the zap channel to hangup.

      * This property is mandatory. */ - public void setZapChannel(Integer channel) - { + public void setZapChannel(Integer channel) { this.zapChannel = channel; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ZapRestartAction.java b/src/main/java/org/asteriskjava/manager/action/ZapRestartAction.java index 395b88c6c..30c3ee96a 100644 --- a/src/main/java/org/asteriskjava/manager/action/ZapRestartAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ZapRestartAction.java @@ -5,13 +5,12 @@ * interfaces. *

      * Available since Asterisk 1.4. - * + * * @author srt - * @since 0.3 * @version $Id$ + * @since 0.3 */ -public class ZapRestartAction extends AbstractManagerAction -{ +public class ZapRestartAction extends AbstractManagerAction { /** * Serial version identifier. */ @@ -20,14 +19,12 @@ public class ZapRestartAction extends AbstractManagerAction /** * Creates a new ZapRestartAction. */ - public ZapRestartAction() - { + public ZapRestartAction() { } @Override - public String getAction() - { + public String getAction() { return "ZapRestart"; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ZapShowChannelsAction.java b/src/main/java/org/asteriskjava/manager/action/ZapShowChannelsAction.java index e51c0b1b3..9ba259fc9 100644 --- a/src/main/java/org/asteriskjava/manager/action/ZapShowChannelsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ZapShowChannelsAction.java @@ -16,23 +16,22 @@ */ package org.asteriskjava.manager.action; -import org.asteriskjava.manager.event.ZapShowChannelsCompleteEvent; import org.asteriskjava.manager.event.ResponseEvent; +import org.asteriskjava.manager.event.ZapShowChannelsCompleteEvent; /** * The ZapShowChannelsAction requests the state of all zap channels.

      * For each zap channel a ZapShowChannelsEvent is generated. After all zap * channels have been listed a ZapShowChannelsCompleteEvent is generated. - * - * @see org.asteriskjava.manager.event.ZapShowChannelsEvent - * @see org.asteriskjava.manager.event.ZapShowChannelsCompleteEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.ZapShowChannelsEvent + * @see org.asteriskjava.manager.event.ZapShowChannelsCompleteEvent */ public class ZapShowChannelsAction extends AbstractManagerAction implements - EventGeneratingAction -{ + EventGeneratingAction { /** * Serializable version identifier */ @@ -41,8 +40,7 @@ public class ZapShowChannelsAction extends AbstractManagerAction /** * Creates a new ZapShowChannelsAction. */ - public ZapShowChannelsAction() - { + public ZapShowChannelsAction() { } @@ -50,13 +48,11 @@ public ZapShowChannelsAction() * Returns the name of this action, i.e. "ZapShowChannels". */ @Override - public String getAction() - { + public String getAction() { return "ZapShowChannels"; } - public Class getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return ZapShowChannelsCompleteEvent.class; } } diff --git a/src/main/java/org/asteriskjava/manager/action/ZapTransferAction.java b/src/main/java/org/asteriskjava/manager/action/ZapTransferAction.java index 7286a0dd7..e34ceb3dd 100644 --- a/src/main/java/org/asteriskjava/manager/action/ZapTransferAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ZapTransferAction.java @@ -18,12 +18,11 @@ /** * The ZapTransferAction transfers a zap channel. - * + * * @author srt * @version $Id$ */ -public class ZapTransferAction extends AbstractManagerAction -{ +public class ZapTransferAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -34,16 +33,14 @@ public class ZapTransferAction extends AbstractManagerAction * Returns the name of this action, i.e. "ZapTransfer". */ @Override - public String getAction() - { + public String getAction() { return "ZapTransfer"; } /** * Returns the number of the zap channel to transfer. */ - public Integer getZapChannel() - { + public Integer getZapChannel() { return zapChannel; } @@ -51,8 +48,7 @@ public Integer getZapChannel() * Sets the number of the zap channel to transfer.

      * This property is mandatory. */ - public void setZapChannel(Integer channel) - { + public void setZapChannel(Integer channel) { this.zapChannel = channel; } } diff --git a/src/main/java/org/asteriskjava/manager/action/package.html b/src/main/java/org/asteriskjava/manager/action/package.html index fcaac1bb6..7ec28a0e6 100644 --- a/src/main/java/org/asteriskjava/manager/action/package.html +++ b/src/main/java/org/asteriskjava/manager/action/package.html @@ -1,28 +1,28 @@ - +

      Provides classes that represent the standard actions that can be sent - to an Asterisk server via the Manager API.

      + to an Asterisk server via the Manager API.

      - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractAgentEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractAgentEvent.java index f0d346667..e6519e4a3 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractAgentEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractAgentEvent.java @@ -26,8 +26,7 @@ * @version $Id$ * @since 0.2 */ -public abstract class AbstractAgentEvent extends ManagerEvent -{ +public abstract class AbstractAgentEvent extends ManagerEvent { private static final long serialVersionUID = 1L; private String channel; private String uniqueId; @@ -36,8 +35,7 @@ public abstract class AbstractAgentEvent extends ManagerEvent private String memberName; private Map variables; - protected AbstractAgentEvent(Object source) - { + protected AbstractAgentEvent(Object source) { super(source); } @@ -46,13 +44,11 @@ protected AbstractAgentEvent(Object source) * * @return the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -61,13 +57,11 @@ public void setChannel(String channel) * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -76,13 +70,11 @@ public void setUniqueId(String uniqueId) * * @return the name of the queue. */ - public String getQueue() - { + public String getQueue() { return queue; } - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } @@ -91,30 +83,26 @@ public void setQueue(String queue) * * @return the name of the member's interface. */ - public String getMember() - { + public String getMember() { return member; } - public void setMember(String member) - { + public void setMember(String member) { this.member = member; } /** * Returns the member name supplied for logging when the member is added. - *

      + *
      * Available since Asterisk 1.4. * * @return the member name supplied for logging when the member is added. */ - public String getMemberName() - { + public String getMemberName() { return memberName; } - public void setMemberName(String memberName) - { + public void setMemberName(String memberName) { this.memberName = memberName; } @@ -126,8 +114,7 @@ public void setMemberName(String memberName) * @return the channel variables. * @since 1.0.0 */ - public Map getVariables() - { + public Map getVariables() { return variables; } @@ -138,8 +125,7 @@ public Map getVariables() * @param variables the channel variables. * @since 1.0.0 */ - public void setVariables(Map variables) - { + public void setVariables(Map variables) { this.variables = variables; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractBridgeEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractBridgeEvent.java new file mode 100644 index 000000000..9a1353405 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AbstractBridgeEvent.java @@ -0,0 +1,96 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public abstract class AbstractBridgeEvent extends ManagerEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + private String bridgeUniqueId; + private String bridgeType; + private Integer bridgeNumChannels; + private String bridgeCreator; + private String bridgeName; + private String bridgeTechnology; + private String accountCode; + private String bridgeVideoSource; + private String bridgeVideoSourceMode; + + AbstractBridgeEvent(Object source) { + super(source); + } + + public String getBridgeUniqueId() { + return bridgeUniqueId; + } + + public void setBridgeUniqueId(String bridgeUniqueId) { + this.bridgeUniqueId = bridgeUniqueId; + } + + public String getBridgeType() { + return bridgeType; + } + + public void setBridgeType(String bridgeType) { + this.bridgeType = bridgeType; + } + + public Integer getBridgeNumChannels() { + return bridgeNumChannels; + } + + public void setBridgeNumChannels(Integer bridgeNumChannels) { + this.bridgeNumChannels = bridgeNumChannels; + } + + public String getBridgeCreator() { + return bridgeCreator; + } + + public void setBridgeCreator(String bridgeCreator) { + this.bridgeCreator = bridgeCreator; + } + + public String getBridgeName() { + return bridgeName; + } + + public void setBridgeName(String bridgeName) { + this.bridgeName = bridgeName; + } + + public String getBridgeTechnology() { + return bridgeTechnology; + } + + public void setBridgeTechnology(String bridgeTechnology) { + this.bridgeTechnology = bridgeTechnology; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getBridgeVideoSource() { + return bridgeVideoSource; + } + + public void setBridgeVideoSource(String bridgeVideoSource) { + this.bridgeVideoSource = bridgeVideoSource; + } + + public String getBridgevideosourcemode() { + return bridgeVideoSourceMode; + } + + public void setBridgevideosourcemode(String bridgeVideoSourceMode) { + this.bridgeVideoSourceMode = bridgeVideoSourceMode; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractChannelEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractChannelEvent.java index 3f43b0023..198991978 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractChannelEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractChannelEvent.java @@ -18,123 +18,116 @@ /** * Abstract base class providing common properties channel related events. - * + * * @author srt * @version $Id$ */ -public abstract class AbstractChannelEvent extends ManagerEvent -{ +public abstract class AbstractChannelEvent extends ManagerEvent { /** * Serializable version identifier. */ static final long serialVersionUID = 5906599407896179295L; + protected String accountCode; + /** * The name of the channel. */ private String channel; - /** - * This Caller*ID Number of the channel. - */ - private String callerIdNum; - - /** - * The Caller*ID Name of the channel. - */ - private String callerIdName; - /** * The unique id of the channel. */ - private String uniqueId; + protected String uniqueId; - protected AbstractChannelEvent(Object source) - { + protected AbstractChannelEvent(Object source) { super(source); } /** * Returns the name of the channel. - * + * * @return the name of the channel. */ - public final String getChannel() - { + public final String getChannel() { return channel; } - public final void setChannel(String channel) - { + public final void setChannel(String channel) { this.channel = channel; } /** * Returns the unique id of the channel. - * + * * @return the unique id of the channel. */ - public final String getUniqueId() - { + public final String getUniqueId() { return uniqueId; } - public final void setUniqueId(String uniqueId) - { + public final void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } /** - * Returns the Caller*ID of the channel if set or null if none has been set. + * Returns the Caller*ID of the channel if set or null if none + * has been set. * * @return the Caller*ID - * @deprecated * @see #getCallerIdNum() + * @deprecated */ - @Deprecated public final String getCallerId() - { - return callerIdNum; + @Deprecated + public final String getCallerId() { + return getCallerIdNum(); } /** * Sets the Caller*ID of the channel. - * + * * @param callerId the Caller*ID of the channel. * @deprecated */ - @Deprecated public final void setCallerId(String callerId) - { - this.callerIdNum = callerId; + @Deprecated + public final void setCallerId(String callerId) { + setCallerIdNum(callerId); } /** - * Returns the Caller*ID number of the channel if set or null if none has been set. + * Returns the Caller*ID number of the channel if set or null + * if none has been set. * * @return the Caller*ID number * @since 0.3 */ - public final String getCallerIdNum() - { + public final String getCallerIdNum() { return callerIdNum; } - public final void setCallerIdNum(String callerIdNum) - { + public final void setCallerIdNum(String callerIdNum) { this.callerIdNum = callerIdNum; } /** - * Returns the Caller*ID Name of the channel if set or null if none has been set. - * + * Returns the Caller*ID Name of the channel if set or null if + * none has been set. + * * @return the Caller*ID Name of the channel. */ - public final String getCallerIdName() - { + public final String getCallerIdName() { return callerIdName; } - public final void setCallerIdName(String callerIdName) - { + public final void setCallerIdName(String callerIdName) { this.callerIdName = callerIdName; } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractChannelStateEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractChannelStateEvent.java index 66b099ff0..b441be2f5 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractChannelStateEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractChannelStateEvent.java @@ -16,110 +16,45 @@ */ package org.asteriskjava.manager.event; -import org.asteriskjava.util.AstState; - /** - * Abstract base class providing common properties for HangupEvent, NewChannelEvent and - * NewStateEvent. + * Abstract base class providing common properties for HangupEvent, + * NewChannelEvent and NewStateEvent. * * @author srt * @version $Id$ */ -public abstract class AbstractChannelStateEvent extends AbstractChannelEvent -{ +public abstract class AbstractChannelStateEvent extends AbstractChannelEvent { /** * Serializable version identifier. */ static final long serialVersionUID = 0L; - private Integer channelState; - private String channelStateDesc; - - protected AbstractChannelStateEvent(Object source) - { + protected AbstractChannelStateEvent(Object source) { super(source); } /** - * Returns the new state of the channel.

      - * For Asterisk versions prior to 1.6 (that do not send the numeric value) it is derived - * from the descriptive text. - * - * @return the new state of the channel. - * @since 1.0.0 - */ - public Integer getChannelState() - { - return channelState == null ? AstState.str2state(channelStateDesc) : channelState; - } - - /** - * Sets the new state of the channel. - * - * @param channelState the new state of the channel. - * @since 1.0.0 - */ - public void setChannelState(Integer channelState) - { - this.channelState = channelState; - } - - /** - * Returns the new state of the channel as a descriptive text.

      - * The following states are used:

      - *

        - *
      • Down
      • - *
      • Rsrvd
      • - *
      • OffHook
      • - *
      • Dialing
      • - *
      • Ring
      • - *
      • Ringing
      • - *
      • Up
      • - *
      • Busy
      • - *
      • Dialing Offhook (since Asterik 1.6)
      • - *
      • Pre-ring (since Asterik 1.6)
      • - *
          + * Returns the new state of the channel as a descriptive text.
          + * This is an alias for {@link #getChannelStateDesc()}. * * @return the new state of the channel as a descriptive text. - * @since 1.0.0 + * @deprecated as of 1.0.0, use {@link #getChannelStateDesc()} instead or + * even better switch to numeric values as returned by + * {@link #getChannelState()}. */ - public String getChannelStateDesc() - { - return channelStateDesc; + @Deprecated + public String getState() { + return getChannelStateDesc(); } /** * Sets the new state of the channel as a descriptive text. - * - * @param channelStateDesc the new state of the channel as a descriptive text. - * @since 1.0.0 - */ - public void setChannelStateDesc(String channelStateDesc) - { - this.channelStateDesc = channelStateDesc; - } - - /** - * Returns the new state of the channel as a descriptive text.

          - * This is an alias for {@link @getChannelStateDesc}. - * - * @return the new state of the channel as a descriptive text. - * @deprecated as of 1.0.0, use {@link #getChannelStateDesc()} instead or even better switch to numeric - * values as returned by {@link #getChannelState()}. - */ - @Deprecated public String getState() - { - return channelStateDesc; - } - - /** - * Sets the new state of the channel as a descriptive text.

          + *

          * The state property is used by Asterisk versions prior to 1.6. * * @param state the new state of the channel as a descriptive text. */ - public void setState(String state) - { - this.channelStateDesc = state; + public void setState(String state) { + setChannelStateDesc(state); } } diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractChannelTalkingEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractChannelTalkingEvent.java new file mode 100644 index 000000000..e2a278ab6 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AbstractChannelTalkingEvent.java @@ -0,0 +1,59 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +public abstract class AbstractChannelTalkingEvent extends ManagerEvent { + private String language; + private String accountCode; + private String uniqueId; + private String linkedId; + + public AbstractChannelTalkingEvent(Object source) { + super(source); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractConfbridgeEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractConfbridgeEvent.java new file mode 100644 index 000000000..c9a3c82f8 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AbstractConfbridgeEvent.java @@ -0,0 +1,162 @@ +package org.asteriskjava.manager.event; + +public abstract class AbstractConfbridgeEvent extends AbstractChannelEvent { + private static final long serialVersionUID = 3893862793876858636L; + private String bridgeType; + private String bridgeNumChannels; + private String bridgeUniqueId; + private String bridgeTechnology; + private String bridgeName; + private String bridgeCreator; + private String conference; + private String bridgeVideoSourceMode; + private String language; + private String linkedId; + + String admin; + + public AbstractConfbridgeEvent(Object source) { + super(source); + } + + /** + * @return the admin + */ + public String getAdmin() { + return admin; + } + + /** + * @param admin the admin to set + */ + public void setAdmin(String admin) { + this.admin = admin; + } + + /** + * @return the bridgeType + */ + public String getBridgeType() { + return bridgeType; + } + + /** + * @param bridgeType the bridgeType to set + */ + public void setBridgeType(String bridgeType) { + this.bridgeType = bridgeType; + } + + /** + * @return the bridgeNumChannels + */ + public String getBridgeNumChannels() { + return bridgeNumChannels; + } + + /** + * @param bridgeNumChannels the bridgeNumChannels to set + */ + public void setBridgeNumChannels(String bridgeNumChannels) { + this.bridgeNumChannels = bridgeNumChannels; + } + + /** + * @return the bridgeUniqueId + */ + public String getBridgeUniqueId() { + return bridgeUniqueId; + } + + /** + * @param bridgeUniqueId the bridgeUniqueId to set + */ + public void setBridgeUniqueId(String bridgeUniqueId) { + this.bridgeUniqueId = bridgeUniqueId; + } + + /** + * @return the bridgeTechnology + */ + public String getBridgeTechnology() { + return bridgeTechnology; + } + + /** + * @param bridgeTechnology the bridgeTechnology to set + */ + public void setBridgeTechnology(String bridgeTechnology) { + this.bridgeTechnology = bridgeTechnology; + } + + /** + * @return the bridgeName + */ + public String getBridgeName() { + return bridgeName; + } + + /** + * @param bridgeName the bridgeName to set + */ + public void setBridgeName(String bridgeName) { + this.bridgeName = bridgeName; + } + + /** + * @return the bridgeCreator + */ + public String getBridgeCreator() { + return bridgeCreator; + } + + /** + * @param bridgeCreator the bridgeCreator to set + */ + public void setBridgeCreator(String bridgeCreator) { + this.bridgeCreator = bridgeCreator; + } + + /** + * Sets the id of the conference the participant left. + * + * @param conference the id of the conference the participant left. + */ + public final void setConference(String conference) { + this.conference = conference; + } + + /** + * Returns the id of the conference the participant left. + * + * @return the id of the conference the participant left. + */ + public final String getConference() { + return conference; + } + + public String getBridgeVideoSourceMode() { + return bridgeVideoSourceMode; + } + + public void setBridgeVideoSourceMode(String bridgeVideoSourceMode) { + this.bridgeVideoSourceMode = bridgeVideoSourceMode; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractFaxEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractFaxEvent.java index df89296ce..0e33dff41 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractFaxEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractFaxEvent.java @@ -19,8 +19,7 @@ /** * An AbstractFaxEvent is a base class for fax related events */ -public class AbstractFaxEvent extends ManagerEvent -{ +public class AbstractFaxEvent extends ManagerEvent { /** * Serial version identifier. */ @@ -28,8 +27,7 @@ public class AbstractFaxEvent extends ManagerEvent private String channel; private Integer faxSession; - public AbstractFaxEvent(Object source) - { + public AbstractFaxEvent(Object source) { super(source); } @@ -37,8 +35,7 @@ public AbstractFaxEvent(Object source) /** * @return the channel */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -46,8 +43,7 @@ public String getChannel() /** * @param channel the channel to set */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -55,8 +51,7 @@ public void setChannel(String channel) /** * @return the faxSession */ - public Integer getFaxSession() - { + public Integer getFaxSession() { return faxSession; } @@ -64,8 +59,7 @@ public Integer getFaxSession() /** * @param faxSession the faxSession to set */ - public void setFaxSession(Integer faxSession) - { + public void setFaxSession(Integer faxSession) { this.faxSession = faxSession; } diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractHoldEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractHoldEvent.java new file mode 100644 index 000000000..8ab2e517c --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AbstractHoldEvent.java @@ -0,0 +1,155 @@ +package org.asteriskjava.manager.event; + +/** + * A HoldEvent is triggered when a channel is put on hold (or no longer on + * hold). + *

          + * It is implemented in channels/chan_sip.c. + *

          + * Available since Asterisk 1.2 for SIP channels, as of Asterisk 1.6 this event + * is also supported for IAX2 channels. + *

          + * To receive HoldEvents for SIP channels you must set + * callevents = yes in sip.conf. + * + * @author enro + * @version $Id$ + * @since 1.0.0.10 + */ +public class AbstractHoldEvent extends ManagerEvent { + /** + * Serializable version identifier. + */ + private static final long serialVersionUID = 1L; + + /** + * The name of the channel. + */ + private String channel; + + private String accountCode; + + /** + * The unique id of the channel. + */ + private String uniqueId; + + private Boolean status; + + private String linkedId; + private String language; + + + /** + * Creates a new HoldEvent. + * + * @param source + */ + public AbstractHoldEvent(Object source) { + super(source); + } + + /** + * Returns the name of the channel. + * + * @return channel the name of the channel. + */ + public String getChannel() { + return channel; + } + + /** + * Sets the name of the channel. + * + * @param channel the name of the channel. + */ + public void setChannel(String channel) { + this.channel = channel; + } + + /** + * Returns the unique id of the channel. + * + * @return the unique id of the channel. + */ + public String getUniqueId() { + return uniqueId; + } + + /** + * Sets the unique id of the channel. + * + * @param uniqueId the unique id of the channel. + */ + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + /** + * Returns whether this is a hold or unhold event. + * + * @return true if this a hold event, false if + * it's an unhold event. + * @since 1.0.0 + */ + public Boolean getStatus() { + return status; + } + + /** + * Returns whether this is a hold or unhold event. + * + * @param status true if this a hold event, false + * if it's an unhold event. + * @since 1.0.0 + */ + public void setStatus(Boolean status) { + this.status = status; + } + + /** + * Returns whether this is a hold event. + * + * @return true if this a hold event, false if + * it's an unhold event. + * @since 1.0.0 + */ + public boolean isHold() { + return status != null && status; + } + + /** + * Returns whether this is an unhold event. + * + * @return true if this an unhold event, false if + * it's a hold event. + * @since 1.0.0 + */ + public boolean isUnhold() { + return status != null && !status; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractMeetMeEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractMeetMeEvent.java index 5f85b2d37..cc969b029 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractMeetMeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractMeetMeEvent.java @@ -17,111 +17,173 @@ package org.asteriskjava.manager.event; /** - * Abstract base class providing common properties for MeetMe - * (Asterisk's conference system) events.

          + * Abstract base class providing common properties for MeetMe (Asterisk's + * conference system) events. + *

          * MeetMe events are implemented in apps/app_meetme.c - * + * * @author srt * @version $Id$ */ -public abstract class AbstractMeetMeEvent extends ManagerEvent -{ - private static final long serialVersionUID = 1L; - private String channel; +public abstract class AbstractMeetMeEvent extends ManagerEvent { + private static final long serialVersionUID = 2L; + private String channel; private String uniqueId; private String meetMe; - private Integer userNum; + private Integer user; + private String language; + private String accountCode; + private String linkedId; /** * @param source */ - protected AbstractMeetMeEvent(Object source) - { + protected AbstractMeetMeEvent(Object source) { super(source); } /** - * Returns the name of the channel.

          + * Returns the name of the channel. + *

          * This property is available since Asterisk 1.4. - * + * * @return the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } /** - * Sets the name of the channel.

          + * Sets the name of the channel. + *

          * This property is available since Asterisk 1.4. - * + * * @param channel the name of the channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** - * Returns the unique id of the channel.

          + * Returns the unique id of the channel. + *

          * This property is available since Asterisk 1.4. - * + * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } /** - * Sets the unique id of the channel.

          + * Sets the unique id of the channel. + *

          * This property is available since Asterisk 1.4. - * + * * @param uniqueId the unique id of the channel. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } /** * Returns the conference number. - * + * * @return the conference number. */ - public String getMeetMe() - { + public String getMeetMe() { return meetMe; } /** * Sets the conference number. - * + * * @param meetMe the conference number. */ - public void setMeetMe(String meetMe) - { + public void setMeetMe(String meetMe) { this.meetMe = meetMe; } /** - * Returns the index of the user in the conference.

          + * Returns the index of the user in the conference. + *

          + * This can be used for the "meetme (mute|unmute|kick)" commands. use + * getUser() instead + * + * @return the index of the user in the conference. + */ + @Deprecated + public Integer getUserNum() { + return getUser(); + } + + /** + * Sets the index of the user in the conference. + * + * @param userNum the index of the user in the conference. + */ + @Deprecated + public void setUserNum(Integer userNum) { + this.setUser(userNum); + } + + /** + * Returns the index of the user in the conference. + *

          * This can be used for the "meetme (mute|unmute|kick)" commands. - * + * * @return the index of the user in the conference. */ - public Integer getUserNum() - { - return userNum; + public Integer getUser() { + return user; } /** * Sets the index of the user in the conference. - * + * * @param userNum the index of the user in the conference. */ - public void setUserNum(Integer userNum) - { - this.userNum = userNum; + public void setUser(Integer userNum) { + this.user = userNum; + } + + /** + * Get the account code associated with the current channel. + * + * @return the channel's account code + */ + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + /** + * Get the language associated with the current channel. + * + * @return the channel's language + */ + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + /** + * Get the linked ID of the channel, which ties this event to other related + * channel's events. + * + * @return the channel's linked ID + */ + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractMixMonitorEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractMixMonitorEvent.java new file mode 100644 index 000000000..28dca2d3c --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AbstractMixMonitorEvent.java @@ -0,0 +1,60 @@ +package org.asteriskjava.manager.event; + +/** + * Abstract base class for mix monitoring events.

          + * + * @version $Id$ + * @since 3.13.0 + */ +public abstract class AbstractMixMonitorEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + private String accountCode; + private String channel; + private String language; + private String linkedId; + private String uniqueId; + + protected AbstractMixMonitorEvent(Object source) { + super(source); + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractMonitorEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractMonitorEvent.java index cb8cf6afc..0a85054ee 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractMonitorEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractMonitorEvent.java @@ -24,17 +24,15 @@ * @version $Id$ * @since 1.0.0 */ -public abstract class AbstractMonitorEvent extends ManagerEvent -{ - private static final long serialVersionUID = 1L; - private String channel; +public abstract class AbstractMonitorEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + private String channel; private String uniqueId; /** * @param source */ - protected AbstractMonitorEvent(Object source) - { + protected AbstractMonitorEvent(Object source) { super(source); } @@ -43,13 +41,11 @@ protected AbstractMonitorEvent(Object source) * * @return the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -58,13 +54,11 @@ public void setChannel(String channel) * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractParkedCallEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractParkedCallEvent.java index f7d42d9ee..373eae815 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractParkedCallEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractParkedCallEvent.java @@ -23,60 +23,64 @@ * @version $Id$ * @since 0.2 */ -public abstract class AbstractParkedCallEvent extends ManagerEvent -{ +public abstract class AbstractParkedCallEvent extends ManagerEvent { private static final long serialVersionUID = 0L; - private String exten; - private String channel; - private String parkingLot; - private String callerIdNum; - private String callerIdName; private String uniqueId; + // Previously: Channel + private String parkeeChannel; + private Integer parkeeChannelState; + private String parkeeChannelStateDesc; + // previously CallerID + private String parkeeCallerIDNum; + // Previously CallerIDName + private String parkeeCallerIDName; + private String parkeeConnectedLineNum; + private String parkeeConnectedLineName; + private String parkeeLanguage; + private String parkeeAccountCode; + private String parkeeContext; + private String parkeeExten; + private Integer parkeePriority; + private String parkeeUniqueid; + private String parkeeLinkedid; + // Previously: From + private String parkerDialString; + private String parkingLot; + // previously Exten + private String parkingSpace; + private Long parkingTimeout; + private Long parkingDuration; - protected AbstractParkedCallEvent(Object source) - { + protected AbstractParkedCallEvent(Object source) { super(source); } /** - * Returns the extension the channel is or was parked at. - * - * @return the extension the channel is or was parked at. + * Returns the name of the channel that parked the call. use + * getParkerDialString() instead */ - public String getExten() - { - return exten; - } - - public void setExten(String exten) - { - this.exten = exten; + @Deprecated + public String getFrom() { + return getParkerDialString(); } /** - * Returns the name of the channel that is or was parked. - * - * @return the name of the channel that is or was parked. + * Sets the name of the channel that parked the call. */ - public String getChannel() - { - return channel; - } - - public void setChannel(String channel) - { - this.channel = channel; + @Deprecated + public void setFrom(String from) { + this.setParkerDialString(from); } /** - * Returns the parking lot.

          + * Returns the parking lot. + *

          * Available since Asterisk 1.6. * * @return the parking lot. * @since 1.0.0 */ - public String getParkingLot() - { + public String getParkingLot() { return parkingLot; } @@ -85,80 +89,196 @@ public String getParkingLot() * * @param parkingLot the parking lot. */ - public void setParkingLot(String parkingLot) - { + public void setParkingLot(String parkingLot) { this.parkingLot = parkingLot; } /** - * Returns the Caller*ID number of the parked channel. + * Returns the unique id of the parked channel. + *

          + * Note: This property is not set properly by all versions of Asterisk, see + * http://bugs.digium. + * com/ view.php?id=13323 and + * http://bugs.digium. + * com/view.php?id=13358 for more information. Use {@link #getChannel()} + * instead. * - * @return the Caller*ID number of the parked channel. - * @since 1.0.0 + * @return the unique id of the parked channel. */ - public String getCallerIdNum() - { - return callerIdNum; + public String getUniqueId() { + return uniqueId; } - public void setCallerIdNum(String callerIdNum) - { - this.callerIdNum = callerIdNum; + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + @Deprecated + public void setChannel(String channel) { + this.setParkeeChannel(channel); } /** - * Returns the Caller*ID number of the parked channel. + * use getParkeeChannel() instead * - * @return the Caller*ID number of the parked channel. - * @deprecated since 1.0.0. Use {@link #getCallerIdNum()} instead. + * @return */ - @Deprecated public String getCallerId() - { - return callerIdNum; + @Deprecated + public String getChannel() { + return this.getParkeeChannel(); } - public void setCallerId(String callerId) - { - this.callerIdNum = callerId; + public String getParkeeChannel() { + return parkeeChannel; } - /** - * Returns the Caller*ID name of the parked channel. - * - * @return the Caller*ID name of the parked channel. - */ - public String getCallerIdName() - { - return callerIdName; + public void setParkeeChannel(String parkeeChannel) { + this.parkeeChannel = parkeeChannel; } - /** - * Sets the Caller*ID name of the parked channel. - * - * @param callerIdName the Caller*ID name of the parked channel. - */ - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; + public Integer getParkeeChannelState() { + return parkeeChannelState; } - /** - * Returns the unique id of the parked channel.

          - * Note: This property is not set properly by all versions of Asterisk, see - * http://bugs.digium.com/view.php?id=13323 - * and - * http://bugs.digium.com/view.php?id=13358 - * for more information. Use {@link #getChannel()} instead. - * - * @return the unique id of the parked channel. - */ - public String getUniqueId() - { - return uniqueId; + public void setParkeeChannelState(Integer parkeeChannelState) { + this.parkeeChannelState = parkeeChannelState; } - public void setUniqueId(String uniqueId) - { - this.uniqueId = uniqueId; + public String getParkeeChannelStateDesc() { + return parkeeChannelStateDesc; + } + + public void setParkeeChannelStateDesc(String parkeeChannelStateDesc) { + this.parkeeChannelStateDesc = parkeeChannelStateDesc; + } + + public String getParkeeCallerIDNum() { + return parkeeCallerIDNum; + } + + public void setParkeeCallerIDNum(String parkeeCallerIDNum) { + this.parkeeCallerIDNum = parkeeCallerIDNum; + } + + public String getParkeeCallerIDName() { + return parkeeCallerIDName; + } + + public void setParkeeCallerIDName(String parkeeCallerIDName) { + this.parkeeCallerIDName = parkeeCallerIDName; + } + + public String getParkeeConnectedLineNum() { + return parkeeConnectedLineNum; + } + + public void setParkeeConnectedLineNum(String parkeeConnectedLineNum) { + this.parkeeConnectedLineNum = parkeeConnectedLineNum; + } + + public String getParkeeConnectedLineName() { + return parkeeConnectedLineName; + } + + public void setParkeeConnectedLineName(String parkeeConnectedLineName) { + this.parkeeConnectedLineName = parkeeConnectedLineName; + } + + public String getParkeeLanguage() { + return parkeeLanguage; + } + + public void setParkeeLanguage(String parkeeLanguage) { + this.parkeeLanguage = parkeeLanguage; + } + + public String getParkeeAccountCode() { + return parkeeAccountCode; + } + + public void setParkeeAccountCode(String parkeeAccountCode) { + this.parkeeAccountCode = parkeeAccountCode; + } + + public String getParkeeContext() { + return parkeeContext; + } + + public void setParkeeContext(String parkeeContext) { + this.parkeeContext = parkeeContext; + } + + public String getParkeeExten() { + return parkeeExten; + } + + public void setParkeeExten(String parkeeExten) { + this.parkeeExten = parkeeExten; + } + + public Integer getParkeePriority() { + return parkeePriority; + } + + public void setParkeePriority(Integer parkeePriority) { + this.parkeePriority = parkeePriority; + } + + public String getParkeeUniqueid() { + return parkeeUniqueid; + } + + public void setParkeeUniqueid(String parkeeUniqueid) { + this.parkeeUniqueid = parkeeUniqueid; + } + + public String getParkeeLinkedid() { + return parkeeLinkedid; + } + + public void setParkeeLinkedid(String parkeeLinkedid) { + this.parkeeLinkedid = parkeeLinkedid; + } + + public String getParkerDialString() { + return parkerDialString; + } + + public void setParkerDialString(String parkerDialString) { + this.parkerDialString = parkerDialString; + } + + public String getParkingSpace() { + return parkingSpace; + } + + public void setParkingSpace(String parkingSpace) { + this.parkingSpace = parkingSpace; + } + + public Long getParkingTimeout() { + return parkingTimeout; + } + + public void setParkingTimeout(Long parkingTimeout) { + this.parkingTimeout = parkingTimeout; + } + + public Long getParkingDuration() { + return parkingDuration; + } + + public void setParkingDuration(Long parkingDuration) { + this.parkingDuration = parkingDuration; + } + + @Deprecated + public String getCallerId() { + return getParkeeCallerIDNum(); + } + + @Deprecated + public void setCallerId(String callerId) { + setParkeeCallerIDNum(callerId); } } diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractQueueMemberEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractQueueMemberEvent.java index 1ae38cfc1..b03360fab 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractQueueMemberEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractQueueMemberEvent.java @@ -18,80 +18,100 @@ /** * Abstract base class for several queue member related events. - * + * * @author srt * @version $Id$ * @since 0.2 */ -public abstract class AbstractQueueMemberEvent extends ManagerEvent -{ +public abstract class AbstractQueueMemberEvent extends ManagerEvent { /** * Serializable version identifier */ private static final long serialVersionUID = -7437833328723536814L; private String queue; - private String location; + private String _interface; private String memberName; + private String pausedReason; + private String inCall; /** * @param source */ - protected AbstractQueueMemberEvent(Object source) - { + protected AbstractQueueMemberEvent(Object source) { super(source); } /** * Returns the name of the queue. - * + * * @return the name of the queue. */ - public String getQueue() - { + public String getQueue() { return queue; } /** * Sets the name of the queue. - * + * * @param queue the name of the queue. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } /** * Returns the name of the member's interface.

          * E.g. the channel name or agent group. - * + * + * @return the name of the member's interface. + */ + final public String getInterface() { + return _interface; + } + + /** + * Sets the name of the member's interface. + * + * @param member the name of the member's interface. + */ + final public void setInterface(String _interface) { + this._interface = _interface; + } + + /** + * Returns the name of the member's interface.

          + * E.g. the channel name or agent group. + * * @return the name of the member's interface. + * @deprecated since Asterisk 12 */ - public String getLocation() - { - return location; + @Deprecated + final public String getLocation() { + return _interface; } /** * Sets the name of the member's interface. - * + * * @param member the name of the member's interface. + * @deprecated since Asterisk 12 */ - public void setLocation(String member) - { - this.location = member; + @Deprecated + final public void setLocation(String _interface) { + if ((_interface != null) && (!"null".equals(_interface))) { // Location is not in use since asterisk 12 + this._interface = _interface; + } } /** * Retruns the name of the queue member. *

          * Available since Asterisk 1.4 - * + * * @return the name of the queue member. * @since 0.3 */ - public String getMemberName() - { + public String getMemberName() { return memberName; } @@ -99,12 +119,27 @@ public String getMemberName() * Sets the name of the queue member. *

          * Available since Asterisk 1.4 - * + * * @param memberName the name of the queue member. * @since 0.3 */ - public void setMemberName(String memberName) - { + public void setMemberName(String memberName) { this.memberName = memberName; } + + public String getPausedReason() { + return pausedReason; + } + + public void setPausedReason(String pausedReason) { + this.pausedReason = pausedReason; + } + + public String getInCall() { + return inCall; + } + + public void setInCall(String inCall) { + this.inCall = inCall; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractRtcpEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractRtcpEvent.java index b47e39dda..7e137214d 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractRtcpEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractRtcpEvent.java @@ -20,38 +20,35 @@ import java.net.UnknownHostException; /** - * Abstract base class for RTCP related events.

          + * Abstract base class for RTCP related events. + *

          * * @author srt * @version $Id$ * @since 1.0.0 */ -public abstract class AbstractRtcpEvent extends ManagerEvent -{ +public abstract class AbstractRtcpEvent extends ManagerEvent { private static final long serialVersionUID = 1L; private Long fractionLost; private Double dlSr; private Double iaJitter; - public AbstractRtcpEvent(Object source) - { + public AbstractRtcpEvent(Object source) { super(source); } /** - * Returns the short term loss ratio. This is the fraction of packets lost since the last RR - * or SR packet was sent. + * Returns the short term loss ratio. This is the fraction of packets lost + * since the last RR or SR packet was sent. * * @return the short term loss ratio. */ - public Long getFractionLost() - { + public Long getFractionLost() { return fractionLost; } - public void setFractionLost(Long fractionLost) - { + public void setFractionLost(Long fractionLost) { this.fractionLost = fractionLost; } @@ -60,13 +57,11 @@ public void setFractionLost(Long fractionLost) * * @return the interarrival jitter. */ - public Double getIaJitter() - { + public Double getIaJitter() { return iaJitter; } - public void setIaJitter(Double iaJitter) - { + public void setIaJitter(Double iaJitter) { this.iaJitter = iaJitter; } @@ -75,97 +70,75 @@ public void setIaJitter(Double iaJitter) * * @return the delay since the last SR in seconds. */ - public Double getDlSr() - { + public Double getDlSr() { return dlSr; } - public void setDlSr(String dlSrString) - { + public void setDlSr(String dlSrString) { this.dlSr = secStringToDouble(dlSrString); } - protected Long secStringToLong(String s) - { - if (s == null || s.length() == 0) - { + protected Long secStringToLong(String s) { + if (s == null || s.length() == 0) { return null; } - if (s.endsWith("(sec)")) - { - return Long.parseLong(s.substring(0, s.length() - "(sec)".length())); + //things like RTT can be float/double in the event message in newer asterisk versions + if (s.contains(".")) { + return secStringToDouble(s).longValue(); } - else - { - return Long.parseLong(s); + + if (s.endsWith("(sec)")) { + return Long.parseLong(s.substring(0, s.length() - "(sec)".length())); } + return Long.parseLong(s); } - protected Double secStringToDouble(String s) - { - if (s == null || s.length() == 0) - { + protected Double secStringToDouble(String s) { + if (s == null || s.length() == 0) { return null; } - if (s.endsWith("(sec)")) - { + if (s.endsWith("(sec)")) { return Double.parseDouble(s.substring(0, s.length() - "(sec)".length())); } - else - { - return Double.parseDouble(s); - } + return Double.parseDouble(s); } - protected InetAddress stringToAddress(String addressWithPort) - { + protected InetAddress stringToAddress(String addressWithPort) { final String address; - if (addressWithPort == null || addressWithPort.length() == 0) - { + if (addressWithPort == null || addressWithPort.length() == 0) { return null; } - if (addressWithPort.lastIndexOf(':') > 0) - { + if (addressWithPort.lastIndexOf(':') > 0) { address = addressWithPort.substring(0, addressWithPort.lastIndexOf(':')); - } - else - { + } else { address = addressWithPort; } - try - { + try { return InetAddress.getByName(address); - } - catch (UnknownHostException e) - { + } catch (UnknownHostException e) { // should not happen as we supply a textual IP address throw new IllegalArgumentException("Unable to convert " + addressWithPort + " to InetAddress", e); } } - protected Integer stringToPort(String addressWithPort) - { + protected Integer stringToPort(String addressWithPort) { final String port; - if (addressWithPort == null || addressWithPort.length() == 0) - { + if (addressWithPort == null || addressWithPort.length() == 0) { return null; } - if (addressWithPort.lastIndexOf(':') > 0) - { + if (addressWithPort.lastIndexOf(':') > 0) { port = addressWithPort.substring(addressWithPort.lastIndexOf(':') + 1); - } - else - { + } else { return null; } return Integer.parseInt(port); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractRtpStatEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractRtpStatEvent.java index 8987c3324..a98746143 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractRtpStatEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractRtpStatEvent.java @@ -23,16 +23,14 @@ * @version $Id$ * @since 1.0.0 */ -public abstract class AbstractRtpStatEvent extends ManagerEvent -{ +public abstract class AbstractRtpStatEvent extends ManagerEvent { private static final long serialVersionUID = 1L; private Long ssrc; private Long lostPackets; private Double jitter; - public AbstractRtpStatEvent(Object source) - { + public AbstractRtpStatEvent(Object source) { super(source); } @@ -41,13 +39,11 @@ public AbstractRtpStatEvent(Object source) * * @return the synchronization source identifier. */ - public Long getSsrc() - { + public Long getSsrc() { return ssrc; } - public void setSsrc(Long ssrc) - { + public void setSsrc(Long ssrc) { this.ssrc = ssrc; } @@ -56,23 +52,19 @@ public void setSsrc(Long ssrc) * * @return the number of lost packets. */ - public Long getLostPackets() - { + public Long getLostPackets() { return lostPackets; } - public void setLostPackets(Long lostPackets) - { + public void setLostPackets(Long lostPackets) { this.lostPackets = lostPackets; } - public Double getJitter() - { + public Double getJitter() { return jitter; } - public void setJitter(Double jitter) - { + public void setJitter(Double jitter) { this.jitter = jitter; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractSecurityEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractSecurityEvent.java new file mode 100644 index 000000000..c08a8329e --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AbstractSecurityEvent.java @@ -0,0 +1,98 @@ +package org.asteriskjava.manager.event; + +public abstract class AbstractSecurityEvent extends ManagerEvent { + private String eventTv; + private String severity; + private String service; + private Integer eventVersion; + private String accountId; + private String sessionId; + private String localAddress; + private String remoteAddress; + private String module; + private String sessionTv; + + protected AbstractSecurityEvent(Object source) { + super(source); + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getEventTv() { + return eventTv; + } + + public void setEventTv(String eventTimestamp) { + this.eventTv = eventTimestamp; + } + + public Integer getEventVersion() { + return eventVersion; + } + + public void setEventVersion(Integer eventVersion) { + this.eventVersion = eventVersion; + } + + public String getLocalAddress() { + return localAddress; + } + + public void setLocalAddress(String localAddress) { + this.localAddress = localAddress; + } + + public String getModule() { + return module; + } + + public void setModule(String module) { + this.module = module; + } + + public String getRemoteAddress() { + return remoteAddress; + } + + public void setRemoteAddress(String remoteAddress) { + this.remoteAddress = remoteAddress; + } + + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getSessionTv() { + return sessionTv; + } + + public void setSessionTv(String sessionTimestamp) { + this.sessionTv = sessionTimestamp; + } + + public String getSeverity() { + return severity; + } + + public void setSeverity(String severity) { + this.severity = severity; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractUnParkedEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractUnParkedEvent.java new file mode 100644 index 000000000..73097dd9d --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AbstractUnParkedEvent.java @@ -0,0 +1,161 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * Enro 2015-03: Asterisk 13 Support + */ +public class AbstractUnParkedEvent extends AbstractParkedCallEvent { + /** + * Serializable version identifier + */ + private static final long serialVersionUID = -7437833328723536814L; + + private String parkerChannel; + private Integer parkerChannelState; + private String parkerChannelStateDesc; + private String parkerCallerIDNum; + private String parkerCallerIDName; + private String parkerConnectedLineNum; + private String parkerConnectedLineName; + private String parkerAccountCode; + private String parkerContext; + private String parkerExten; + private String parkerPriority; + private String parkerUniqueid; + private String parkerLinkedid; + private String parkerLanguage; + + /** + * @param source + */ + public AbstractUnParkedEvent(Object source) { + super(source); + } + + public String getParkerChannel() { + return parkerChannel; + } + + public void setParkerChannel(String parkerChannel) { + this.parkerChannel = parkerChannel; + } + + public Integer getParkerChannelState() { + return parkerChannelState; + } + + public void setParkerChannelState(Integer parkerChannelState) { + this.parkerChannelState = parkerChannelState; + } + + public String getParkerChannelStateDesc() { + return parkerChannelStateDesc; + } + + public void setParkerChannelStateDesc(String parkerChannelStateDesc) { + this.parkerChannelStateDesc = parkerChannelStateDesc; + } + + public String getParkerCallerIDNum() { + return parkerCallerIDNum; + } + + public void setParkerCallerIDNum(String parkerCallerIDNum) { + this.parkerCallerIDNum = parkerCallerIDNum; + } + + public String getParkerCallerIDName() { + return parkerCallerIDName; + } + + public void setParkerCallerIDName(String parkerCallerIDName) { + this.parkerCallerIDName = parkerCallerIDName; + } + + public String getParkerConnectedLineNum() { + return parkerConnectedLineNum; + } + + public void setParkerConnectedLineNum(String parkerConnectedLineNum) { + this.parkerConnectedLineNum = parkerConnectedLineNum; + } + + public String getParkerConnectedLineName() { + return parkerConnectedLineName; + } + + public void setParkerConnectedLineName(String parkerConnectedLineName) { + this.parkerConnectedLineName = parkerConnectedLineName; + } + + public String getParkerAccountCode() { + return parkerAccountCode; + } + + public void setParkerAccountCode(String parkerAccountCode) { + this.parkerAccountCode = parkerAccountCode; + } + + public String getParkerContext() { + return parkerContext; + } + + public void setParkerContext(String parkerContext) { + this.parkerContext = parkerContext; + } + + public String getParkerExten() { + return parkerExten; + } + + public void setParkerExten(String parkerExten) { + this.parkerExten = parkerExten; + } + + public String getParkerPriority() { + return parkerPriority; + } + + public void setParkerPriority(String parkerPriority) { + this.parkerPriority = parkerPriority; + } + + public String getParkerUniqueid() { + return parkerUniqueid; + } + + public void setParkerUniqueid(String parkerUniqueid) { + this.parkerUniqueid = parkerUniqueid; + } + + public String getParkerLinkedid() { + return parkerLinkedid; + } + + public void setParkerLinkedid(String parkerLinkedid) { + this.parkerLinkedid = parkerLinkedid; + } + + public String getParkerLanguage() { + return parkerLanguage; + } + + public void setParkerLanguage(String parkerLanguage) { + this.parkerLanguage = parkerLanguage; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AgentCallbackLoginEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentCallbackLoginEvent.java index 08a27f6ec..578a9e047 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentCallbackLoginEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentCallbackLoginEvent.java @@ -20,13 +20,12 @@ * An AgentCallbackLoginEvent is triggered when an agent is successfully logged in using * AgentCallbackLogin.

          * It is implemented in channels/chan_agent.c - * - * @see org.asteriskjava.manager.event.AgentCallbackLogoffEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.AgentCallbackLogoffEvent */ -public class AgentCallbackLoginEvent extends ManagerEvent -{ +public class AgentCallbackLoginEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -38,44 +37,37 @@ public class AgentCallbackLoginEvent extends ManagerEvent /** * @param source */ - public AgentCallbackLoginEvent(Object source) - { + public AgentCallbackLoginEvent(Object source) { super(source); } /** * Returns the name of the agent that logged in. */ - public String getAgent() - { + public String getAgent() { return agent; } /** * Sets the name of the agent that logged in. */ - public void setAgent(String agent) - { + public void setAgent(String agent) { this.agent = agent; } - public String getLoginChan() - { + public String getLoginChan() { return loginChan; } - public void setLoginChan(String loginChan) - { + public void setLoginChan(String loginChan) { this.loginChan = loginChan; } - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgentCallbackLogoffEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentCallbackLogoffEvent.java index e95189a83..ab67d0835 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentCallbackLogoffEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentCallbackLogoffEvent.java @@ -21,13 +21,12 @@ * AgentCallbackLogin is logged of. *

          * It is implemented in channels/chan_agent.c - * - * @see org.asteriskjava.manager.event.AgentCallbackLoginEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.AgentCallbackLoginEvent */ -public class AgentCallbackLogoffEvent extends ManagerEvent -{ +public class AgentCallbackLogoffEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -41,44 +40,37 @@ public class AgentCallbackLogoffEvent extends ManagerEvent /** * @param source */ - public AgentCallbackLogoffEvent(Object source) - { + public AgentCallbackLogoffEvent(Object source) { super(source); } /** * Returns the name of the agent that logged off. */ - public String getAgent() - { + public String getAgent() { return agent; } /** * Sets the name of the agent that logged off. */ - public void setAgent(String agent) - { + public void setAgent(String agent) { this.agent = agent; } - public String getLoginChan() - { + public String getLoginChan() { return loginChan; } - public void setLoginChan(String loginChan) - { + public void setLoginChan(String loginChan) { this.loginChan = loginChan; } - public Long getLoginTime() - { + public Long getLoginTime() { return loginTime; } - public void setLoginTime(Long loginTime) - { + public void setLoginTime(Long loginTime) { this.loginTime = loginTime; } @@ -87,26 +79,22 @@ public void setLoginTime(Long loginTime) * logged off due to not answering the phone in time. Autologoff is configured by setting * autologoff to the appropriate number of seconds in agents.conf. */ - public String getReason() - { + public String getReason() { return reason; } /** * Sets the reason for the logoff. */ - public void setReason(String reason) - { + public void setReason(String reason) { this.reason = reason; } - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgentCalledEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentCalledEvent.java index 43ff9e108..29b863d29 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentCalledEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentCalledEvent.java @@ -19,57 +19,72 @@ import java.util.Map; /** - * An AgentCalledEvent is triggered when an agent is rung. - *

          + * An AgentCalledEvent is triggered when an agent is rung.
          * To enable AgentCalledEvents you have to set - * eventwhencalled = yes in queues.conf. - *

          + * eventwhencalled = yes in queues.conf.
          * This event is implemented in apps/app_queue.c * * @author srt * @version $Id$ */ -public class AgentCalledEvent extends ManagerEvent -{ +public class AgentCalledEvent extends ManagerEvent { /** * Serializable version identifier. */ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 2L; + private String queue; private String agentCalled; - private String agentName; private String channelCalling; private String destinationChannel; - private String callerIdNum; - private String callerIdName; - private String context; - private String extension; - private String priority; private String uniqueId; + private String memberName; + private Map variables; + private String destExten; + private String destChannelStateDesc; + private String destUniqueId; + private String destConnectedLineNum; + private String destConnectedLineName; + private String destCallerIdName; + private String destCallerIdNum; + private String destContext; + private String destPriority; + private String destChannel; + private String destChannelState; + private String iface; + private String channel; + + private String destAccountCode; + private String language; + private String destLanguage; + private String linkedId; + private String destLinkedId; + + private String accountcode; + + /** * @param source */ - public AgentCalledEvent(Object source) - { + public AgentCalledEvent(Object source) { super(source); } /** - * Returns the name of the queue.

          + * Returns the name of the queue. + *

          * Available since Asterisk 1.6. * * @return the name of the queue. * @since 1.0.0 */ - public String getQueue() - { + public String getQueue() { return queue; } - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } @@ -79,8 +94,7 @@ public void setQueue(String queue) * @return the member interface of the agent that has been called. * @see QueueMemberEvent#getLocation() */ - public String getAgentCalled() - { + public String getAgentCalled() { return agentCalled; } @@ -90,26 +104,27 @@ public String getAgentCalled() * @param agentCalled the member interface of the agent that has been * called. */ - public void setAgentCalled(String agentCalled) - { + public void setAgentCalled(String agentCalled) { this.agentCalled = agentCalled; } /** - * Returns the name of the agent that has been called.

          + * Returns the name of the agent that has been called. + *

          * Available since Asterisk 1.6. * * @return the name of the agent that has been called. * @since 1.0.0 + * @deprecated use {@lkink #getMemberName()} instead (asterisk 13) */ - public String getAgentName() - { - return agentName; + @Deprecated + public String getAgentName() { + return memberName; } - public void setAgentName(String agentName) - { - this.agentName = agentName; + @Deprecated + public void setAgentName(String agentName) { + this.memberName = agentName; } /** @@ -118,8 +133,7 @@ public void setAgentName(String agentName) * * @return the name of the caller's channel. */ - public String getChannelCalling() - { + public String getChannelCalling() { return channelCalling; } @@ -128,157 +142,337 @@ public String getChannelCalling() * * @param channelCalling the name of the caller's channel. */ - public void setChannelCalling(String channelCalling) - { + public void setChannelCalling(String channelCalling) { this.channelCalling = channelCalling; } /** - * Returns the name of the channel calling the agent.

          + * Returns the name of the channel calling the agent. + *

          * Available since Asterisk 1.6 * * @return the name of the channel calling the agent. * @since 1.0.0 */ - public String getDestinationChannel() - { + public String getDestinationChannel() { return destinationChannel; } - public void setDestinationChannel(String destinationChannel) - { + public void setDestinationChannel(String destinationChannel) { this.destinationChannel = destinationChannel; } /** * Returns the Caller ID number of the caller's channel. * - * @return the Caller ID number of the caller's channel or "unknown" of none has been set. - * @since 1.0.0 + * @return the Caller ID number of the caller's channel. + * @deprecated as of 1.0.0, use {@link #getCallerIdNum()} instead. */ - public String getCallerIdNum() - { + @Deprecated + public String getCallerId() { return callerIdNum; } - public void setCallerIdNum(String callerIdNum) - { - this.callerIdNum = callerIdNum; + /** + * Sets the Caller ID number of the caller's channel. + * + * @param callerId the Caller ID number of the caller's channel. + */ + public void setCallerId(String callerId) { + this.callerIdNum = callerId; + } + + public String getExtension() { + return exten; + } + + public void setExtension(String extension) { + this.exten = extension; } /** - * Returns the Caller ID number of the caller's channel. + * Returns the unique id of the caller's channel that is about to be handled + * by the agent. This corresponds to {@link #getChannelCalling()}. + *

          + * Available since Asterisk 1.6 * - * @return the Caller ID number of the caller's channel. - * @deprecated as of 1.0.0, use {@link #getCallerIdNum()} instead. + * @return the unique id of the caller's channel. + * @since 1.0.0 */ - @Deprecated public String getCallerId() - { - return callerIdNum; + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; } /** - * Sets the Caller ID number of the caller's channel. - * - * @param callerId the Caller ID number of the caller's channel. + * Returns the Queue Member name. + *

          + * Available since Asterisk 13 replace agentName + *

          */ - public void setCallerId(String callerId) - { - this.callerIdNum = callerId; + public String getMemberName() { + return memberName; + } + + public void setMemberName(String memberName) { + this.memberName = memberName; } /** - * Returns the Caller ID name of the caller's channel. + * Returns the channel variables if eventwhencalled is set to + * vars in queues.conf. + *

          + * Available since Asterisk 1.6 * - * @return the Caller ID name of the caller's channel or "unknown" if none has been set. - * @since 0.2 + * @return the channel variables. + * @since 1.0.0 */ - public String getCallerIdName() - { - return callerIdName; + public Map getVariables() { + return variables; } /** - * Sets the Caller ID name of the caller's channel. + * Sets the channel variables. + *

          + * Available since Asterisk 1.6 * - * @param callerIdName the Caller ID name of the caller's channel. - * @since 0.2 + * @param variables the channel variables. + * @since 1.0.0 */ - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; + public void setVariables(Map variables) { + this.variables = variables; } - public String getContext() - { - return context; + /** + * @return the destExten + */ + public String getDestExten() { + return destExten; } - public void setContext(String context) - { - this.context = context; + /** + * @param destExten the destExten to set + */ + public void setDestExten(String destExten) { + this.destExten = destExten; } - public String getExtension() - { - return extension; + /** + * @return the destChannelStateDesc + */ + public String getDestChannelStateDesc() { + return destChannelStateDesc; } - public void setExtension(String extension) - { - this.extension = extension; + /** + * @param destChannelStateDesc the destChannelStateDesc to set + */ + public void setDestChannelStateDesc(String destChannelStateDesc) { + this.destChannelStateDesc = destChannelStateDesc; } - public String getPriority() - { - return priority; + /** + * @return the destUniqueId + */ + public String getDestUniqueId() { + return destUniqueId; } - public void setPriority(String priority) - { - this.priority = priority; + /** + * @param destUniqueId the destUniqueId to set + */ + public void setDestUniqueId(String destUniqueId) { + this.destUniqueId = destUniqueId; } /** - * Returns the unique id of the caller's channel that is about to be handled by - * the agent. This corresponds to {@link #getChannelCalling()}.

          - * Available since Asterisk 1.6 - * - * @return the unique id of the caller's channel. - * @since 1.0.0 + * @return the destConnectedLineNum */ - public String getUniqueId() - { - return uniqueId; + public String getDestConnectedLineNum() { + return destConnectedLineNum; } - public void setUniqueId(String uniqueId) - { - this.uniqueId = uniqueId; + /** + * @param destConnectedLineNum the destConnectedLineNum to set + */ + public void setDestConnectedLineNum(String destConnectedLineNum) { + this.destConnectedLineNum = destConnectedLineNum; } /** - * Returns the channel variables if eventwhencalled is set to vars - * in queues.conf.

          - * Available since Asterisk 1.6 - * - * @return the channel variables. - * @since 1.0.0 + * @return the destCallerIdName */ - public Map getVariables() - { - return variables; + public String getDestCallerIdName() { + return destCallerIdName; } /** - * Sets the channel variables.

          - * Available since Asterisk 1.6 - * - * @param variables the channel variables. - * @since 1.0.0 + * @param destCallerIdName the destCallerIdName to set */ - public void setVariables(Map variables) - { - this.variables = variables; + public void setDestCallerIdName(String destCallerIdName) { + this.destCallerIdName = destCallerIdName; + } + + /** + * @return the destCallerIdNum + */ + public String getDestCallerIdNum() { + return destCallerIdNum; + } + + /** + * @param destCallerIdNum the destCallerIdNum to set + */ + public void setDestCallerIdNum(String destCallerIdNum) { + this.destCallerIdNum = destCallerIdNum; + } + + /** + * @return the destContext + */ + public String getDestContext() { + return destContext; + } + + /** + * @param destContext the destContext to set + */ + public void setDestContext(String destContext) { + this.destContext = destContext; + } + + /** + * @return the destPriority + */ + public String getDestPriority() { + return destPriority; + } + + /** + * @param destPriority the destPriority to set + */ + public void setDestPriority(String destPriority) { + this.destPriority = destPriority; + } + + /** + * @return the destChannel + */ + public String getDestChannel() { + return destChannel; + } + + /** + * @param destChannel the destChannel to set + */ + public void setDestChannel(String destChannel) { + this.destChannel = destChannel; + } + + /** + * @return the destChannelState + */ + public String getDestChannelState() { + return destChannelState; + } + + /** + * @param destChannelState the destChannelState to set + */ + public void setDestChannelState(String destChannelState) { + this.destChannelState = destChannelState; + } + + /** + * @return the iface + */ + public String getInterface() { + return iface; + } + + /** + * @param iface the iface to set + */ + public void setInterface(String iface) { + this.iface = iface; + } + + /** + * @return the channel + */ + public String getChannel() { + return channel; + } + + /** + * @param channel the channel to set + */ + public void setChannel(String channel) { + this.channel = channel; + } + + /** + * @return the destConnectedLineName + */ + public String getDestConnectedLineName() { + return destConnectedLineName; + } + + /** + * @param destConnectedLineName the destConnectedLineName to set + */ + public void setDestConnectedLineName(String destConnectedLineName) { + this.destConnectedLineName = destConnectedLineName; + } + + public String getDestAccountCode() { + return destAccountCode; + } + + public void setDestAccountCode(String destAccountCode) { + this.destAccountCode = destAccountCode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getDestLanguage() { + return destLanguage; + } + + public void setDestLanguage(String destLanguage) { + this.destLanguage = destLanguage; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getDestLinkedId() { + return destLinkedId; + } + + public void setDestLinkedId(String destLinkedId) { + this.destLinkedId = destLinkedId; + } + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgentCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentCompleteEvent.java index 52640275c..77521f8e6 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentCompleteEvent.java @@ -18,16 +18,17 @@ /** * An AgentCompleteEvent is triggered when at the end of a call if the caller - * was connected to an agent.

          - * It is implemented in apps/app_queue.c.

          + * was connected to an agent. + *

          + * It is implemented in apps/app_queue.c. + *

          * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class AgentCompleteEvent extends AbstractAgentEvent -{ +public class AgentCompleteEvent extends AbstractAgentEvent { /** * Serial version identifier. */ @@ -37,71 +38,300 @@ public class AgentCompleteEvent extends AbstractAgentEvent private Long talkTime; private String reason; - public AgentCompleteEvent(Object source) - { + private String destExten; + private String destChannelStateDesc; + private String destUniqueId; + private String destConnectedLineNum; + private String destConnectedLineName; + private String destCallerIdName; + private String destCallerIdNum; + private String destContext; + private String destPriority; + private String destChannel; + private String destChannelState; + private String iface; + + private String destAccountCode; + private String language; + private String destLanguage; + private String linkedId; + private String destLinkedId; + private String accountCode; + + public AgentCompleteEvent(Object source) { super(source); } /** * Returns the amount of time the caller was on hold. - * + * * @return the amount of time the caller was on hold in seconds. */ - public Long getHoldTime() - { + public Long getHoldTime() { return holdTime; } /** * Sets the amount of time the caller was on hold. - * + * * @param holdtime the amount of time the caller was on hold in seconds. */ - public void setHoldTime(Long holdtime) - { + public void setHoldTime(Long holdtime) { this.holdTime = holdtime; } /** * Returns the amount of time the caller talked to the agent. - * + * * @return the amount of time the caller talked to the agent in seconds. */ - public Long getTalkTime() - { + public Long getTalkTime() { return talkTime; } /** * Sets the amount of time the caller talked to the agent. - * + * * @param talkTime the amount of time the caller talked to the agent in - * seconds. + * seconds. */ - public void setTalkTime(Long talkTime) - { + public void setTalkTime(Long talkTime) { this.talkTime = talkTime; } /** * Returns if the agent or the caller terminated the call. - * + * * @return "agent" if the agent terminated the call, "caller" if the caller - * terminated the call. + * terminated the call. */ - public String getReason() - { + public String getReason() { return reason; } /** * Sets if the agent or the caller terminated the call. - * + * * @param reason "agent" if the agent terminated the call, "caller" if the - * caller terminated the call. + * caller terminated the call. */ - public void setReason(String reason) - { + public void setReason(String reason) { this.reason = reason; } + + /** + * @return the destExten + */ + public String getDestExten() { + return destExten; + } + + /** + * @param destExten the destExten to set + */ + public void setDestExten(String destExten) { + this.destExten = destExten; + } + + /** + * @return the destChannelStateDesc + */ + public String getDestChannelStateDesc() { + return destChannelStateDesc; + } + + /** + * @param destChannelStateDesc the destChannelStateDesc to set + */ + public void setDestChannelStateDesc(String destChannelStateDesc) { + this.destChannelStateDesc = destChannelStateDesc; + } + + /** + * @return the destUniqueId + */ + public String getDestUniqueId() { + return destUniqueId; + } + + /** + * @param destUniqueId the destUniqueId to set + */ + public void setDestUniqueId(String destUniqueId) { + this.destUniqueId = destUniqueId; + } + + /** + * @return the destConnectedLineNum + */ + public String getDestConnectedLineNum() { + return destConnectedLineNum; + } + + /** + * @param destConnectedLineNum the destConnectedLineNum to set + */ + public void setDestConnectedLineNum(String destConnectedLineNum) { + this.destConnectedLineNum = destConnectedLineNum; + } + + /** + * @return the destConnectedLineName + */ + public String getDestConnectedLineName() { + return destConnectedLineName; + } + + /** + * @param destConnectedLineName the destConnectedLineName to set + */ + public void setDestConnectedLineName(String destConnectedLineName) { + this.destConnectedLineName = destConnectedLineName; + } + + /** + * @return the destCallerIdName + */ + public String getDestCallerIdName() { + return destCallerIdName; + } + + /** + * @param destCallerIdName the destCallerIdName to set + */ + public void setDestCallerIdName(String destCallerIdName) { + this.destCallerIdName = destCallerIdName; + } + + /** + * @return the destCallerIdNum + */ + public String getDestCallerIdNum() { + return destCallerIdNum; + } + + /** + * @param destCallerIdNum the destCallerIdNum to set + */ + public void setDestCallerIdNum(String destCallerIdNum) { + this.destCallerIdNum = destCallerIdNum; + } + + /** + * @return the destContext + */ + public String getDestContext() { + return destContext; + } + + /** + * @param destContext the destContext to set + */ + public void setDestContext(String destContext) { + this.destContext = destContext; + } + + /** + * @return the destPriority + */ + public String getDestPriority() { + return destPriority; + } + + /** + * @param destPriority the destPriority to set + */ + public void setDestPriority(String destPriority) { + this.destPriority = destPriority; + } + + /** + * @return the destChannel + */ + public String getDestChannel() { + return destChannel; + } + + /** + * @param destChannel the destChannel to set + */ + public void setDestChannel(String destChannel) { + this.destChannel = destChannel; + } + + /** + * @return the destChannelState + */ + public String getDestChannelState() { + return destChannelState; + } + + /** + * @param destChannelState the destChannelState to set + */ + public void setDestChannelState(String destChannelState) { + this.destChannelState = destChannelState; + } + + /** + * @return the iface + */ + public String getInterface() { + return iface; + } + + /** + * @param iface the iface to set + */ + public void setInterface(String iface) { + this.iface = iface; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getDestAccountCode() { + return destAccountCode; + } + + public void setDestAccountCode(String destAccountCode) { + this.destAccountCode = destAccountCode; + } + + public String getDestLanguage() { + return destLanguage; + } + + public void setDestLanguage(String destLanguage) { + this.destLanguage = destLanguage; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getDestLinkedId() { + return destLinkedId; + } + + public void setDestLinkedId(String destLinkedId) { + this.destLinkedId = destLinkedId; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgentConnectEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentConnectEvent.java index ef6b29135..1611041b6 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentConnectEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentConnectEvent.java @@ -17,16 +17,17 @@ package org.asteriskjava.manager.event; /** - * An AgentConnectEvent is triggered when a caller is connected to an agent.

          - * It is implemented in apps/app_queue.c.

          + * An AgentConnectEvent is triggered when a caller is connected to an agent. + *

          + * It is implemented in apps/app_queue.c. + *

          * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class AgentConnectEvent extends AbstractAgentEvent -{ +public class AgentConnectEvent extends AbstractAgentEvent { /** * Serial version identifier. */ @@ -36,70 +37,303 @@ public class AgentConnectEvent extends AbstractAgentEvent private String bridgedChannel; private Long ringtime; - public AgentConnectEvent(Object source) - { + private String destExten; + private String destChannelStateDesc; + private String destUniqueId; + private String destConnectedLineNum; + private String destConnectedLineName; + private String destCallerIdName; + private String destCallerIdNum; + private String destContext; + private String destPriority; + private String destChannel; + private String destChannelState; + private String iface; + private String destAccountCode; + private String linkedId; + private String destLinkedId; + private String destLanguage; + private String language; + + private String accountcode; + + public AgentConnectEvent(Object source) { super(source); } /** * Returns the amount of time the caller was on hold. - * + * * @return the amount of time the caller was on hold in seconds. */ - public Long getHoldTime() - { + public Long getHoldTime() { return holdTime; } /** * Sets the amount of time the caller was on hold. - * + * * @param holdtime the amount of time the caller was on hold in seconds. */ - public void setHoldTime(Long holdtime) - { + public void setHoldTime(Long holdtime) { this.holdTime = holdtime; } /** * Returns the unique ID of the queue member channel that is taking the * call. This is useful when trying to link recording filenames back to a - * particular call from the queue.

          + * particular call from the queue. + *

          * Available since Asterisk 1.4. - * + * * @return the unique ID of the queue member channel that is taking the - * call. + * call. */ - public String getBridgedChannel() - { + public String getBridgedChannel() { return bridgedChannel; } /** * Sets the unique ID of the queue member channel that is taking the call. - * + * * @param bridgedChannel the unique ID of the queue member channel that is - * taking the call. + * taking the call. */ - public void setBridgedChannel(String bridgedChannel) - { + public void setBridgedChannel(String bridgedChannel) { this.bridgedChannel = bridgedChannel; } /** - * Returns the amount of time the agent's channel was ringing before answered.

          + * Returns the amount of time the agent's channel was ringing before + * answered. + *

          * Available since Asterisk 1.6. * - * @return the amount of time the agent's channel was ringing before answered in seconds. + * @return the amount of time the agent's channel was ringing before + * answered in seconds. * @since 1.0.0 */ - public Long getRingtime() - { + public Long getRingtime() { return ringtime; } - public void setRingtime(Long ringtime) - { + public void setRingtime(Long ringtime) { this.ringtime = ringtime; } + + /** + * @return the destExten + */ + public String getDestExten() { + return destExten; + } + + /** + * @param destExten the destExten to set + */ + public void setDestExten(String destExten) { + this.destExten = destExten; + } + + /** + * @return the destChannelStateDesc + */ + public String getDestChannelStateDesc() { + return destChannelStateDesc; + } + + /** + * @param destChannelStateDesc the destChannelStateDesc to set + */ + public void setDestChannelStateDesc(String destChannelStateDesc) { + this.destChannelStateDesc = destChannelStateDesc; + } + + /** + * @return the destUniqueId + */ + public String getDestUniqueId() { + return destUniqueId; + } + + /** + * @param destUniqueId the destUniqueId to set + */ + public void setDestUniqueId(String destUniqueId) { + this.destUniqueId = destUniqueId; + } + + /** + * @return the destConnectedLineNum + */ + public String getDestConnectedLineNum() { + return destConnectedLineNum; + } + + /** + * @param destConnectedLineNum the destConnectedLineNum to set + */ + public void setDestConnectedLineNum(String destConnectedLineNum) { + this.destConnectedLineNum = destConnectedLineNum; + } + + /** + * @return the destConnectedLineName + */ + public String getDestConnectedLineName() { + return destConnectedLineName; + } + + /** + * @param destConnectedLineName the destConnectedLineName to set + */ + public void setDestConnectedLineName(String destConnectedLineName) { + this.destConnectedLineName = destConnectedLineName; + } + + /** + * @return the destCallerIdName + */ + public String getDestCallerIdName() { + return destCallerIdName; + } + + /** + * @param destCallerIdName the destCallerIdName to set + */ + public void setDestCallerIdName(String destCallerIdName) { + this.destCallerIdName = destCallerIdName; + } + + /** + * @return the destCallerIdNum + */ + public String getDestCallerIdNum() { + return destCallerIdNum; + } + + /** + * @param destCallerIdNum the destCallerIdNum to set + */ + public void setDestCallerIdNum(String destCallerIdNum) { + this.destCallerIdNum = destCallerIdNum; + } + + /** + * @return the destContext + */ + public String getDestContext() { + return destContext; + } + + /** + * @param destContext the destContext to set + */ + public void setDestContext(String destContext) { + this.destContext = destContext; + } + + /** + * @return the destPriority + */ + public String getDestPriority() { + return destPriority; + } + + /** + * @param destPriority the destPriority to set + */ + public void setDestPriority(String destPriority) { + this.destPriority = destPriority; + } + + /** + * @return the destChannel + */ + public String getDestChannel() { + return destChannel; + } + + /** + * @param destChannel the destChannel to set + */ + public void setDestChannel(String destChannel) { + this.destChannel = destChannel; + } + + /** + * @return the destChannelState + */ + public String getDestChannelState() { + return destChannelState; + } + + /** + * @param destChannelState the destChannelState to set + */ + public void setDestChannelState(String destChannelState) { + this.destChannelState = destChannelState; + } + + /** + * @return the iface + */ + public String getInterface() { + return iface; + } + + /** + * @param iface the iface to set + */ + public void setInterface(String iface) { + this.iface = iface; + } + + public String getDestAccountCode() { + return destAccountCode; + } + + public void setDestAccountCode(String destAccountCode) { + this.destAccountCode = destAccountCode; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getDestLinkedId() { + return destLinkedId; + } + + public void setDestLinkedId(String destLinkedId) { + this.destLinkedId = destLinkedId; + } + + public String getDestLanguage() { + return destLanguage; + } + + public void setDestLanguage(String destLanguage) { + this.destLanguage = destLanguage; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgentDumpEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentDumpEvent.java index 11b075879..f44301988 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentDumpEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentDumpEvent.java @@ -21,20 +21,18 @@ * to the queue announcement.

          * It is implemented in apps/app_queue.c.

          * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class AgentDumpEvent extends AbstractAgentEvent -{ +public class AgentDumpEvent extends AbstractAgentEvent { /** * Serial version identifier. */ private static final long serialVersionUID = 2108033737226142194L; - public AgentDumpEvent(Object source) - { + public AgentDumpEvent(Object source) { super(source); } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgentLoginEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentLoginEvent.java index bbedc1e5e..08dfcf3ce 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentLoginEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentLoginEvent.java @@ -19,13 +19,12 @@ /** * An AgentLoginEvent is triggered when an agent is successfully logged in using AgentLogin.

          * It is implemented in channels/chan_agent.c - * - * @see org.asteriskjava.manager.event.AgentLogoffEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.AgentLogoffEvent */ -public class AgentLoginEvent extends ManagerEvent -{ +public class AgentLoginEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -37,76 +36,69 @@ public class AgentLoginEvent extends ManagerEvent /** * @param source */ - public AgentLoginEvent(Object source) - { + public AgentLoginEvent(Object source) { super(source); } /** * Returns the name of the agent that logged in. */ - public String getAgent() - { + public String getAgent() { return agent; } /** * Sets the name of the agent that logged in. */ - public void setAgent(String agent) - { + public void setAgent(String agent) { this.agent = agent; } /** * Returns the name of the channel associated with the logged in agent. - * + * * @deprecated use {@link #getChannel()} instead. */ - @Deprecated public String getLoginChan() - { + @Deprecated + public String getLoginChan() { return channel; } /** * Returns the name of the channel associated with the logged in agent. - * + * * @return the name of the channel associated with the logged in agent. * @since 0.3 */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel associated with the logged in agent. - * + * * @param channel the name of the channel associated with the logged in agent. * @since 0.3 */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the unique id of the channel associated with the logged in agent. - * + * * @return the unique id of the channel associated with the logged in agent. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } /** * Sets the unique id of the channel associated with the logged in agent. - * + * * @param uniqueId the unique id of the channel associated with the logged in agent. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgentLogoffEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentLogoffEvent.java index 2c4b8dc8d..e5e699a83 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentLogoffEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentLogoffEvent.java @@ -20,13 +20,12 @@ * An AgentCallbackLogoffEvent is triggered when an agent that previously logged in using AgentLogin * is logged of.

          * It is implemented in channels/chan_agent.c - * - * @see org.asteriskjava.manager.event.AgentLoginEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.AgentLoginEvent */ -public class AgentLogoffEvent extends ManagerEvent -{ +public class AgentLogoffEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -42,48 +41,41 @@ public class AgentLogoffEvent extends ManagerEvent /** * @param source */ - public AgentLogoffEvent(Object source) - { + public AgentLogoffEvent(Object source) { super(source); } /** * Returns the name of the agent that logged off. - * + * * @return the name of the agent that logged off. */ - public String getAgent() - { + public String getAgent() { return agent; } /** * Sets the name of the agent that logged off. - * + * * @param agent the name of the agent that logged off. */ - public void setAgent(String agent) - { + public void setAgent(String agent) { this.agent = agent; } - public String getLoginTime() - { + public String getLoginTime() { return loginTime; } - public void setLoginTime(String loginTime) - { + public void setLoginTime(String loginTime) { this.loginTime = loginTime; } - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgentRingNoAnswerEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentRingNoAnswerEvent.java index bcb296c72..d34f4c3a7 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentRingNoAnswerEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentRingNoAnswerEvent.java @@ -17,23 +17,44 @@ package org.asteriskjava.manager.event; /** - * An AgentRingNoAnswerEvent is triggered when a call is routed to an agent but the agent - * does not answer the call.

          - * It is implemented in apps/app_queue.c.

          + * An AgentRingNoAnswerEvent is triggered when a call is routed to an agent but + * the agent does not answer the call. + *

          + * It is implemented in apps/app_queue.c. + *

          * Available since Asterisk 1.6 * * @author srt * @version $Id$ * @since 1.0.0 */ -public class AgentRingNoAnswerEvent extends AbstractAgentEvent -{ - private static final long serialVersionUID = 1L; +public class AgentRingNoAnswerEvent extends AbstractAgentEvent { + private static final long serialVersionUID = 2L; private Long ringtime; - public AgentRingNoAnswerEvent(Object source) - { + private String destExten; + private String destChannelStateDesc; + private String destUniqueId; + private String destConnectedLineNum; + private String destConnectedLineName; + private String destCallerIdName; + private String destCallerIdNum; + private String destContext; + private String destPriority; + private String destChannel; + private String destChannelState; + private String iface; + + private String destAccountCode; + private String language; + private String destLanguage; + private String linkedId; + private String destLinkedId; + + private String accountcode; + + public AgentRingNoAnswerEvent(Object source) { super(source); } @@ -42,13 +63,229 @@ public AgentRingNoAnswerEvent(Object source) * * @return the amount of time the agent's channel was ringing in seconds. */ - public Long getRingtime() - { + public Long getRingtime() { return ringtime; } - public void setRingtime(Long ringtime) - { + public void setRingtime(Long ringtime) { this.ringtime = ringtime; } -} \ No newline at end of file + + /** + * @return the destExten + */ + public String getDestExten() { + return destExten; + } + + /** + * @param destExten the destExten to set + */ + public void setDestExten(String destExten) { + this.destExten = destExten; + } + + /** + * @return the destChannelStateDesc + */ + public String getDestChannelStateDesc() { + return destChannelStateDesc; + } + + /** + * @param destChannelStateDesc the destChannelStateDesc to set + */ + public void setDestChannelStateDesc(String destChannelStateDesc) { + this.destChannelStateDesc = destChannelStateDesc; + } + + /** + * @return the destUniqueId + */ + public String getDestUniqueId() { + return destUniqueId; + } + + /** + * @param destUniqueId the destUniqueId to set + */ + public void setDestUniqueId(String destUniqueId) { + this.destUniqueId = destUniqueId; + } + + /** + * @return the destConnectedLineNum + */ + public String getDestConnectedLineNum() { + return destConnectedLineNum; + } + + /** + * @param destConnectedLineNum the destConnectedLineNum to set + */ + public void setDestConnectedLineNum(String destConnectedLineNum) { + this.destConnectedLineNum = destConnectedLineNum; + } + + /** + * @return the destConnectedLineName + */ + public String getDestConnectedLineName() { + return destConnectedLineName; + } + + /** + * @param destConnectedLineName the destConnectedLineName to set + */ + public void setDestConnectedLineName(String destConnectedLineName) { + this.destConnectedLineName = destConnectedLineName; + } + + /** + * @return the destCallerIdName + */ + public String getDestCallerIdName() { + return destCallerIdName; + } + + /** + * @param destCallerIdName the destCallerIdName to set + */ + public void setDestCallerIdName(String destCallerIdName) { + this.destCallerIdName = destCallerIdName; + } + + /** + * @return the destCallerIdNum + */ + public String getDestCallerIdNum() { + return destCallerIdNum; + } + + /** + * @param destCallerIdNum the destCallerIdNum to set + */ + public void setDestCallerIdNum(String destCallerIdNum) { + this.destCallerIdNum = destCallerIdNum; + } + + /** + * @return the destContext + */ + public String getDestContext() { + return destContext; + } + + /** + * @param destContext the destContext to set + */ + public void setDestContext(String destContext) { + this.destContext = destContext; + } + + /** + * @return the destPriority + */ + public String getDestPriority() { + return destPriority; + } + + /** + * @param destPriority the destPriority to set + */ + public void setDestPriority(String destPriority) { + this.destPriority = destPriority; + } + + /** + * @return the destChannel + */ + public String getDestChannel() { + return destChannel; + } + + /** + * @param destChannel the destChannel to set + */ + public void setDestChannel(String destChannel) { + this.destChannel = destChannel; + } + + /** + * @return the destChannelState + */ + public String getDestChannelState() { + return destChannelState; + } + + /** + * @param destChannelState the destChannelState to set + */ + public void setDestChannelState(String destChannelState) { + this.destChannelState = destChannelState; + } + + /** + * @return the iface + */ + public String getInterface() { + return iface; + } + + /** + * @param iface the iface to set + */ + public void setInterface(String iface) { + this.iface = iface; + } + + public String getDestAccountCode() { + return destAccountCode; + } + + public void setDestAccountCode(String destAccountCode) { + this.destAccountCode = destAccountCode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getDestLanguage() { + return destLanguage; + } + + public void setDestLanguage(String destLanguage) { + this.destLanguage = destLanguage; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getDestLinkedId() { + return destLinkedId; + } + + public void setDestLinkedId(String destLinkedId) { + this.destLinkedId = destLinkedId; + } + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/AgentsCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentsCompleteEvent.java index 9182fcd6f..c4ab8553b 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentsCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentsCompleteEvent.java @@ -20,24 +20,42 @@ * An AgentsCompleteEvent is triggered after the state of all agents has been * reported in response to an AgentsAction.

          * Available since Asterisk 1.2 - * - * @see org.asteriskjava.manager.action.AgentsAction + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.AgentsAction * @since 0.2 */ -public class AgentsCompleteEvent extends ResponseEvent -{ +public class AgentsCompleteEvent extends ResponseEvent { /** * Serial version identifier */ private static final long serialVersionUID = -1177773673509373296L; + private Integer listItems; + private String eventList; + /** * @param source */ - public AgentsCompleteEvent(Object source) - { + public AgentsCompleteEvent(Object source) { super(source); } + + public Integer getListItems() { + return listItems; + } + + public void setListItems(Integer listItems) { + this.listItems = listItems; + } + + public String getEventList() { + return eventList; + } + + public void setEventList(String eventList) { + this.eventList = eventList; + } + } diff --git a/src/main/java/org/asteriskjava/manager/event/AgentsEvent.java b/src/main/java/org/asteriskjava/manager/event/AgentsEvent.java index 1447be3ee..cbb2b0379 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentsEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentsEvent.java @@ -20,14 +20,13 @@ * An AgentsEvent is triggered for each agent in response to an AgentsAction. *

          * Available since Asterisk 1.2 - * - * @see org.asteriskjava.manager.action.AgentsAction + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.AgentsAction * @since 0.2 */ -public class AgentsEvent extends ResponseEvent -{ +public class AgentsEvent extends ResponseEvent { /** * Serial version identifier */ @@ -64,44 +63,39 @@ public class AgentsEvent extends ResponseEvent /** * @param source */ - public AgentsEvent(Object source) - { + public AgentsEvent(Object source) { super(source); } /** * Returns the agentid. */ - public String getAgent() - { + public String getAgent() { return agent; } /** * Sets the agentid. */ - public void setAgent(String agent) - { + public void setAgent(String agent) { this.agent = agent; } /** * Returns the name of this agent. - * + * * @return the name of this agent */ - public String getName() - { + public String getName() { return name; } /** * Sets the name of this agent. - * + * * @param name the name of this agent */ - public void setName(String name) - { + public void setName(String name) { this.name = name; } @@ -119,106 +113,96 @@ public void setName(String name) *

          "AGENT_UNKNOWN"
          *
          Don't know anything about agent. Shouldn't ever get this.
          * - * + * * @return the status of this agent * @see #AGENT_STATUS_LOGGEDOFF * @see #AGENT_STATUS_IDLE * @see #AGENT_STATUS_ONCALL * @see #AGENT_STATUS_UNKNOWN */ - public String getStatus() - { + public String getStatus() { return status; } /** * Sets the status of this agent. - * + * * @param status the status of this agent */ - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } /** * Returns the name of channel this agent logged in from. - * + * * @return the name of the channel this agent logged in from or "n/a" if the - * agent is not logged in. + * agent is not logged in. */ - public String getLoggedInChan() - { + public String getLoggedInChan() { return loggedInChan; } /** * Sets the name of channel this agent logged in from. - * + * * @param loggedInChan the name of channel this agent logged in from */ - public void setLoggedInChan(String loggedInChan) - { + public void setLoggedInChan(String loggedInChan) { this.loggedInChan = loggedInChan; } /** * Returns the time (in seconds since 01/01/1970) when the agent logged in. - * + * * @return the time when the agent logged in or 0 if the user is not logged - * in. + * in. */ - public Long getLoggedInTime() - { + public Long getLoggedInTime() { return loggedInTime; } /** * Sets the time when the agent logged in. - * + * * @param loggedInTime the time when the agent logged in */ - public void setLoggedInTime(Long loggedInTime) - { + public void setLoggedInTime(Long loggedInTime) { this.loggedInTime = loggedInTime; } /** * Returns the numerical Caller*ID of the channel this agent is talking to. - * + * * @return the numerical Caller*ID of the channel this agent is talking to - * or "n/a" if this agent is talking to nobody. + * or "n/a" if this agent is talking to nobody. */ - public String getTalkingTo() - { + public String getTalkingTo() { return talkingTo; } /** * Sets the numerical Caller*ID of the channel this agent is talking to. - * + * * @param talkingTo the numerical Caller*ID of the channel this agent is - * talking to + * talking to */ - public void setTalkingTo(String talkingTo) - { + public void setTalkingTo(String talkingTo) { this.talkingTo = talkingTo; } /** * Returns the name of the channel this agent is talking to.

          * Available since Asterisk 1.6. - * + * * @return the name of the channel this agent is talking to. * @since 1.0.0 */ - public String getTalkingToChan() - { + public String getTalkingToChan() { return talkingToChan; } - public void setTalkingToChan(String talkingToChan) - { + public void setTalkingToChan(String talkingToChan) { this.talkingToChan = talkingToChan; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgiExecEndEvent.java b/src/main/java/org/asteriskjava/manager/event/AgiExecEndEvent.java new file mode 100644 index 000000000..5a2910883 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AgiExecEndEvent.java @@ -0,0 +1,36 @@ +package org.asteriskjava.manager.event; + +/** + * Created by plhk on 1/15/15. + */ +public class AgiExecEndEvent extends AgiExecEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + + private String linkedid; + + private String language; + + public AgiExecEndEvent(Object source) { + super(source); + setSubEvent(SUB_EVENT_END); + } + + public String getLinkedid() { + return linkedid; + } + + public void setLinkedid(String linkedid) { + this.linkedid = linkedid; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AgiExecEvent.java b/src/main/java/org/asteriskjava/manager/event/AgiExecEvent.java index 97832a28a..aa44573e3 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgiExecEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgiExecEvent.java @@ -3,22 +3,21 @@ /** * AgiExecEvents are triggered when an AGI command is executed. For each command two events are triggered: * one before excution ("Start") and one after execution ("End"). - *

          + *
          * The following sub events are reported: *

            *
          • Start: Execution of an AGI command has started.
          • *
          • End: Execution of an AGI command has finished.
          • *
          * It is implemented in res/res_agi.c. - *

          + *
          * Available since Asterisk 1.6 * * @author srt * @version $Id$ * @since 1.0.0 */ -public class AgiExecEvent extends ManagerEvent -{ +public class AgiExecEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -40,14 +39,24 @@ public class AgiExecEvent extends ManagerEvent private String command; private Integer resultCode; private String result; + private String accountCode; + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + private String uniqueId; /** * Creates a new AgiExecEvent. * * @param source */ - public AgiExecEvent(Object source) - { + public AgiExecEvent(Object source) { super(source); } @@ -56,8 +65,7 @@ public AgiExecEvent(Object source) * * @return the name of the channel this event occurred on. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -66,8 +74,7 @@ public String getChannel() * * @param channel the name of the channel this event occurred on. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -78,8 +85,7 @@ public void setChannel(String channel) * @see #SUB_EVENT_START * @see #SUB_EVENT_END */ - public String getSubEvent() - { + public String getSubEvent() { return subEvent; } @@ -88,19 +94,16 @@ public String getSubEvent() * * @param subEvent the sub event type. */ - public void setSubEvent(String subEvent) - { + public void setSubEvent(String subEvent) { this.subEvent = subEvent; } /** - * Returns the command id. The command is a random number generated by Asterisk that allows - * matching the "End" sub event with the corresponding "Start" sub event. + * Returns the command id. The command is a random number generated by Asterisk that allows matching the "End" sub event with the corresponding "Start" sub event. * * @return the command id. */ - public String getCommandId() - { + public String getCommandId() { return commandId; } @@ -109,8 +112,7 @@ public String getCommandId() * * @param commandId the command id. */ - public void setCommandId(String commandId) - { + public void setCommandId(String commandId) { this.commandId = commandId; } @@ -119,8 +121,7 @@ public void setCommandId(String commandId) * * @return the AGI command. */ - public String getCommand() - { + public String getCommand() { return command; } @@ -129,8 +130,7 @@ public String getCommand() * * @param command the AGI command. */ - public void setCommand(String command) - { + public void setCommand(String command) { this.command = command; } @@ -139,8 +139,7 @@ public void setCommand(String command) * * @return the result code. */ - public Integer getResultCode() - { + public Integer getResultCode() { return resultCode; } @@ -149,15 +148,13 @@ public Integer getResultCode() * * @param resultCode the result code. */ - public void setResultCode(Integer resultCode) - { + public void setResultCode(Integer resultCode) { this.resultCode = resultCode; } /** * Returns the result as a string.

          - * They correspond to the numeric values returned by {@link #getResultCode()}. Usually you will want to - * stick with the numeric values.

          + * They correspond to the numeric values returned by {@link #getResultCode()}. Usually you will want to stick with the numeric values.

          * Possible values are: *

            *
          • Failure (corresponds to result code -1)
          • @@ -169,8 +166,7 @@ public void setResultCode(Integer resultCode) * * @return a string respresentation of the result. */ - public String getResult() - { + public String getResult() { return result; } @@ -179,18 +175,36 @@ public String getResult() * * @param result a string respresentation of the result. */ - public void setResult(String result) - { + public void setResult(String result) { this.result = result; } + /** + * Returns the account code set for CDR. + * + * @return string + */ + public String getAccountCode() { + return accountCode; + } + + /** + * Sets the account code used for billing in the CDR. + *
            + * This will be the filename asterisk stores the billing informations in, so it should only use lowercase letters, numbers, hyphen and underscore. + * + * @param accountCode + */ + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + /** * Checks is this a start sub event. * * @return true if this is a "Start" sub event, false otherwise. */ - public boolean isStart() - { + public boolean isStart() { return isSubEvent(SUB_EVENT_START); } @@ -199,13 +213,11 @@ public boolean isStart() * * @return true if this is an "End" sub event, false otherwise. */ - public boolean isEnd() - { + public boolean isEnd() { return isSubEvent(SUB_EVENT_END); } - private boolean isSubEvent(String subEvent) - { + private boolean isSubEvent(String subEvent) { return this.subEvent != null && this.subEvent.equalsIgnoreCase(subEvent); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/AgiExecStartEvent.java b/src/main/java/org/asteriskjava/manager/event/AgiExecStartEvent.java new file mode 100644 index 000000000..6b2a4e5a9 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AgiExecStartEvent.java @@ -0,0 +1,36 @@ +package org.asteriskjava.manager.event; + +/** + * Created by plhk on 1/15/15. + */ +public class AgiExecStartEvent extends AgiExecEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + + private String linkedid; + + private String language; + + public AgiExecStartEvent(Object source) { + super(source); + setSubEvent(SUB_EVENT_START); + } + + public String getLinkedid() { + return linkedid; + } + + public void setLinkedid(String linkedid) { + this.linkedid = linkedid; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AlarmClearEvent.java b/src/main/java/org/asteriskjava/manager/event/AlarmClearEvent.java index a0be33356..2b8eee9a8 100644 --- a/src/main/java/org/asteriskjava/manager/event/AlarmClearEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AlarmClearEvent.java @@ -19,12 +19,11 @@ /** * An AlarmEvent is triggered when a Zap channel leaves alarm state.

            * It is implemented in channels/chan_zap.c - * + * * @author srt * @version $Id$ */ -public class AlarmClearEvent extends ManagerEvent -{ +public class AlarmClearEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -38,28 +37,25 @@ public class AlarmClearEvent extends ManagerEvent /** * @param source */ - public AlarmClearEvent(Object source) - { + public AlarmClearEvent(Object source) { super(source); } /** * Returns the number of the zap channel that left alarm state. - * + * * @return the number of the zap channel that left alarm state. */ - public Integer getChannel() - { + public Integer getChannel() { return channel; } /** * Sets the number of the zap channel that left alarm state. - * + * * @param channel the number of the zap channel that left alarm state. */ - public void setChannel(Integer channel) - { + public void setChannel(Integer channel) { this.channel = channel; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AlarmEvent.java b/src/main/java/org/asteriskjava/manager/event/AlarmEvent.java index 1f490e9bc..7a1c7ed6d 100644 --- a/src/main/java/org/asteriskjava/manager/event/AlarmEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AlarmEvent.java @@ -19,12 +19,11 @@ /** * An AlarmEvent is triggered when a Zap channel enters or changes alarm state.

            * It is implemented in channels/chan_zap.c - * + * * @author srt * @version $Id$ */ -public class AlarmEvent extends ManagerEvent -{ +public class AlarmEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -35,8 +34,7 @@ public class AlarmEvent extends ManagerEvent /** * @param source */ - public AlarmEvent(Object source) - { + public AlarmEvent(Object source) { super(source); } @@ -52,32 +50,28 @@ public AlarmEvent(Object source) *

          • Not Open
          • *
          */ - public String getAlarm() - { + public String getAlarm() { return alarm; } /** * Sets the kind of alarm that happened. */ - public void setAlarm(String alarm) - { + public void setAlarm(String alarm) { this.alarm = alarm; } /** * Returns the number of the channel the alarm occured on. */ - public Integer getChannel() - { + public Integer getChannel() { return channel; } /** * Sets the number of the channel the alarm occured on. */ - public void setChannel(Integer channel) - { + public void setChannel(Integer channel) { this.channel = channel; } } diff --git a/src/main/java/org/asteriskjava/manager/event/AntennaLevelEvent.java b/src/main/java/org/asteriskjava/manager/event/AntennaLevelEvent.java new file mode 100644 index 000000000..537eb4ced --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AntennaLevelEvent.java @@ -0,0 +1,24 @@ +package org.asteriskjava.manager.event; + +public class AntennaLevelEvent extends AbstractChannelEvent { + + /** + * + */ + private static final long serialVersionUID = 7687745700915865011L; + + private String signal; + + public AntennaLevelEvent(Object source) { + super(source); + } + + public String getSignal() { + return signal; + } + + public void setSignal(String signal) { + this.signal = signal; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/AorDetail.java b/src/main/java/org/asteriskjava/manager/event/AorDetail.java new file mode 100644 index 000000000..03fa0ce3c --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AorDetail.java @@ -0,0 +1,206 @@ +package org.asteriskjava.manager.event; + +/** + * A ContactStatusDetail event is triggered in response to a + * {@link org.asteriskjava.manager.action.PJSipShowEndpoint}, and contains + * information about a PJSIP Contact + *

          + * + * @author Steve Sether + * @version $Id$ + * @since 12 + */ + +public class AorDetail extends ResponseEvent { + + /** + * Serial version identifier. + */ + private static final long serialVersionUID = 2634171854313358591L; + + public AorDetail(Object source) { + super(source); + } + + private String objectType; + private String objectName; + private int minimumExpiration; + private int defaultExpiration; + private Float qualifyTimeout; + private String mailboxes; + private Boolean supportPath; + private String voicemailExtension; + private int maxContacts; + private Boolean authenticateQualify; + private String contacts; + private int maximumExpiration; + private int qualifyFrequency; + private Boolean removeExisting; + private String outboundProxy; + private int totalContacts; + private int contactsRegistered; + private String endpointName; + private Boolean removeUnavailable; + private Boolean qualify2xxOnly; + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + public String getObjectName() { + return objectName; + } + + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + public int getMinimumExpiration() { + return minimumExpiration; + } + + public void setMinimumExpiration(int minimumExpiration) { + this.minimumExpiration = minimumExpiration; + } + + public int getDefaultExpiration() { + return defaultExpiration; + } + + public void setDefaultExpiration(int defaultExpiration) { + this.defaultExpiration = defaultExpiration; + } + + public Float getQualifyTimeout() { + return qualifyTimeout; + } + + public void setQualifyTimeout(Float qualifyTimeout) { + this.qualifyTimeout = qualifyTimeout; + } + + public String getMailboxes() { + return mailboxes; + } + + public void setMailboxes(String mailboxes) { + this.mailboxes = mailboxes; + } + + public Boolean isSupportPath() { + return supportPath; + } + + public void setSupportPath(Boolean supportPath) { + this.supportPath = supportPath; + } + + public String getVoicemailExtension() { + return voicemailExtension; + } + + public void setVoicemailExtension(String voicemailExtension) { + this.voicemailExtension = voicemailExtension; + } + + public int getMaxContacts() { + return maxContacts; + } + + public void setMaxContacts(int maxContacts) { + this.maxContacts = maxContacts; + } + + public Boolean isAuthenticateQualify() { + return authenticateQualify; + } + + public void setAuthenticateQualify(Boolean authenticateQualify) { + this.authenticateQualify = authenticateQualify; + } + + public String getContacts() { + return contacts; + } + + public void setContacts(String contacts) { + this.contacts = contacts; + } + + public int getMaximumExpiration() { + return maximumExpiration; + } + + public void setMaximumExpiration(int maximumExpiration) { + this.maximumExpiration = maximumExpiration; + } + + public int getQualifyFrequency() { + return qualifyFrequency; + } + + public void setQualifyFrequency(int qualifyFrequency) { + this.qualifyFrequency = qualifyFrequency; + } + + public Boolean isRemoveExisting() { + return removeExisting; + } + + public void setRemoveExisting(Boolean removeExisting) { + this.removeExisting = removeExisting; + } + + public String getOutboundProxy() { + return outboundProxy; + } + + public void setOutboundProxy(String outboundProxy) { + this.outboundProxy = outboundProxy; + } + + public int getTotalContacts() { + return totalContacts; + } + + public void setTotalContacts(int totalContacts) { + this.totalContacts = totalContacts; + } + + public int getContactsRegistered() { + return contactsRegistered; + } + + public void setContactsRegistered(int contactsRegistered) { + this.contactsRegistered = contactsRegistered; + } + + public String getEndpointName() { + return endpointName; + } + + public void setEndpointName(String endpointName) { + this.endpointName = endpointName; + } + + public Boolean isRemoveUnavailable() { + return removeUnavailable; + } + + public void setRemoveUnavailable(Boolean removeUnavailable) { + this.removeUnavailable = removeUnavailable; + } + + public Boolean isQualify2xxOnly() { + return qualify2xxOnly; + } + + public void setQualify2xxOnly(Boolean qualify2xxOnly) { + this.qualify2xxOnly = qualify2xxOnly; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/AsyncAgiEndEvent.java b/src/main/java/org/asteriskjava/manager/event/AsyncAgiEndEvent.java new file mode 100644 index 000000000..070394dad --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AsyncAgiEndEvent.java @@ -0,0 +1,16 @@ +package org.asteriskjava.manager.event; + +/** + * Created by plhk on 1/15/15. + */ +public class AsyncAgiEndEvent extends AsyncAgiEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + + public AsyncAgiEndEvent(Object source) { + super(source); + setSubEvent(SUB_EVENT_END); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AsyncAgiEvent.java b/src/main/java/org/asteriskjava/manager/event/AsyncAgiEvent.java index 59fd4ef46..deeff2bf8 100644 --- a/src/main/java/org/asteriskjava/manager/event/AsyncAgiEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AsyncAgiEvent.java @@ -1,11 +1,12 @@ package org.asteriskjava.manager.event; -import java.net.URLDecoder; import java.io.UnsupportedEncodingException; -import java.util.*; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; /** - * * The following sub events are reported: *

            *
          • Start: A channel has started the AGI("agi:async") application and is awaiting Async AGI commands.
          • @@ -14,7 +15,7 @@ *
          • End: A channel has left the AGI("agi:async") application.
          • *
          * It is implemented in res/res_agi.c. - *

          + *
          * Available since Asterisk 1.6 * * @author srt @@ -22,8 +23,7 @@ * @see org.asteriskjava.manager.action.AgiAction * @since 1.0.0 */ -public class AsyncAgiEvent extends ResponseEvent -{ +public class AsyncAgiEvent extends ResponseEvent { /** * Serializable version identifier. */ @@ -38,14 +38,22 @@ public class AsyncAgiEvent extends ResponseEvent private String commandId; private String result; private String env; + private String uniqueId; + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } /** * Creates a new AsyncAgiEvent. * * @param source */ - public AsyncAgiEvent(Object source) - { + public AsyncAgiEvent(Object source) { super(source); } @@ -54,8 +62,7 @@ public AsyncAgiEvent(Object source) * * @return the name of the channel this event occurred on. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -64,8 +71,7 @@ public String getChannel() * * @param channel the name of the channel this event occurred on. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -74,8 +80,7 @@ public void setChannel(String channel) * * @return the sub event type. */ - public String getSubEvent() - { + public String getSubEvent() { return subEvent; } @@ -84,8 +89,7 @@ public String getSubEvent() * * @param subEvent the sub event type. */ - public void setSubEvent(String subEvent) - { + public void setSubEvent(String subEvent) { this.subEvent = subEvent; } @@ -96,8 +100,7 @@ public void setSubEvent(String subEvent) * @return the command id. * @see org.asteriskjava.manager.action.AgiAction#setCommandId(String) */ - public String getCommandId() - { + public String getCommandId() { return commandId; } @@ -106,8 +109,7 @@ public String getCommandId() * * @param commandId the command id. */ - public void setCommandId(String commandId) - { + public void setCommandId(String commandId) { this.commandId = commandId; } @@ -123,8 +125,7 @@ public void setCommandId(String commandId) * * @return the URL encoded result. */ - public String getResult() - { + public String getResult() { return result; } @@ -133,8 +134,7 @@ public String getResult() * * @return the decoded result. */ - public List decodeResult() - { + public List decodeResult() { return decode(getResult()); } @@ -143,8 +143,7 @@ public List decodeResult() * * @param result the URL encoded result. */ - public void setResult(String result) - { + public void setResult(String result) { this.result = result; } @@ -166,8 +165,7 @@ public void setResult(String result) * * @return the URL encoded AGI environment. */ - public String getEnv() - { + public String getEnv() { return env; } @@ -175,32 +173,25 @@ public String getEnv() * Decodes the AGI environment and returns a list of lines. * * @return The decoded AGI environment or an empty list if the environment is not available (that is - * if {@link #getEnv()} returns null). + * if {@link #getEnv()} returns null). * @see #getEnv() */ - public List decodeEnv() - { + public List decodeEnv() { return decode(getEnv()); } - private List decode(String s) - { - final List result = new ArrayList(); + private List decode(String s) { + final List result = new ArrayList<>(); - if (s == null) - { + if (s == null) { return result; } - try - { - final String decodedString = URLDecoder.decode(s, "ISO-8859-1"); + try { + final String decodedString = URLDecoder.decode(s, "UTF-8"); result.addAll(Arrays.asList(decodedString.split("\n"))); - } - catch (UnsupportedEncodingException e) - { - // won't happen as JDK ships with ISO-8859-1 - throw new RuntimeException("This JDK does not support ISO-8859-1 encoding", e); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("This JDK does not support UTF-8 encoding", e); } return result; @@ -211,8 +202,7 @@ private List decode(String s) * * @param env the URL encoded AGI environment. */ - public void setEnv(String env) - { + public void setEnv(String env) { this.env = env; } @@ -221,8 +211,7 @@ public void setEnv(String env) * * @return true if this is a "Start" sub event, false otherwise. */ - public boolean isStart() - { + public boolean isStart() { return isSubEvent(SUB_EVENT_START); } @@ -231,8 +220,7 @@ public boolean isStart() * * @return true if this is an "Exec" sub event, false otherwise. */ - public boolean isExec() - { + public boolean isExec() { return isSubEvent(SUB_EVENT_EXEC); } @@ -241,13 +229,11 @@ public boolean isExec() * * @return true if this is an "End" sub event, false otherwise. */ - public boolean isEnd() - { + public boolean isEnd() { return isSubEvent(SUB_EVENT_END); } - protected boolean isSubEvent(String subEvent) - { + protected boolean isSubEvent(String subEvent) { return this.subEvent != null && this.subEvent.equalsIgnoreCase(subEvent); } } diff --git a/src/main/java/org/asteriskjava/manager/event/AsyncAgiExecEvent.java b/src/main/java/org/asteriskjava/manager/event/AsyncAgiExecEvent.java new file mode 100644 index 000000000..161188d73 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AsyncAgiExecEvent.java @@ -0,0 +1,16 @@ +package org.asteriskjava.manager.event; + +/** + * Created by plhk on 1/15/15. + */ +public class AsyncAgiExecEvent extends AsyncAgiEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + + public AsyncAgiExecEvent(Object source) { + super(source); + setSubEvent(SUB_EVENT_EXEC); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AsyncAgiStartEvent.java b/src/main/java/org/asteriskjava/manager/event/AsyncAgiStartEvent.java new file mode 100644 index 000000000..fabfd4575 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AsyncAgiStartEvent.java @@ -0,0 +1,16 @@ +package org.asteriskjava.manager.event; + +/** + * Created by plhk on 1/15/15. + */ +public class AsyncAgiStartEvent extends AsyncAgiEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + + public AsyncAgiStartEvent(Object source) { + super(source); + setSubEvent(SUB_EVENT_START); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/AttendedTransferEvent.java b/src/main/java/org/asteriskjava/manager/event/AttendedTransferEvent.java new file mode 100644 index 000000000..a5a9b31ac --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AttendedTransferEvent.java @@ -0,0 +1,919 @@ +package org.asteriskjava.manager.event; + +/** + * Raised when attended transfer is complete + *

          + * https://wiki.asterisk.org/wiki/display/AST/Asterisk+13+ManagerEvent_AttendedTransfer + */ +public class AttendedTransferEvent extends AbstractBridgeEvent { + + private static final long serialVersionUID = 1L; + + private String origTransfererChannel; + private String origTransfererChannelState; + private String origTransfererChannelStateDesc; + private String origTransfererCallerIDNum; + private String origTransfererCallerIDName; + private String origTransfererConnectedLineNum; + private String origTransfererConnectedLineName; + private String origTransfererAccountCode; + private String origTransfererContext; + private String origTransfererExten; + private String origTransfererPriority; + private String origTransfererUniqueid; + private String origBridgeUniqueid; + private String origBridgeType; + private String origBridgeTechnology; + private String origBridgeCreator; + private String origBridgeName; + private String origBridgeNumChannels; + private String secondTransfererChannel; + private String secondTransfererChannelState; + private String secondTransfererChannelStateDesc; + private String secondTransfererCallerIDNum; + private String secondTransfererCallerIDName; + private String secondTransfererConnectedLineNum; + private String secondTransfererConnectedLineName; + private String secondTransfererAccountCode; + private String secondTransfererContext; + private String secondTransfererExten; + private String secondTransfererPriority; + private String secondTransfererUniqueid; + private String secondBridgeUniqueid; + private String secondBridgeType; + private String secondBridgeTechnology; + private String secondBridgeCreator; + private String secondBridgeName; + private String secondBridgeNumChannels; + private String destType; + private String destBridgeUniqueid; + private String destApp; + private String localOneChannel; + private String localOneChannelState; + private String localOneChannelStateDesc; + private String localOneCallerIDNum; + private String localOneCallerIDName; + private String localOneConnectedLineNum; + private String localOneConnectedLineName; + private String localOneAccountCode; + private String localOneContext; + private String localOneExten; + private String localOnePriority; + private String localOneUniqueid; + private String localTwoChannel; + private String localTwoChannelState; + private String localTwoChannelStateDesc; + private String localTwoCallerIDNum; + private String localTwoCallerIDName; + private String localTwoConnectedLineNum; + private String localTwoConnectedLineName; + private String localTwoAccountCode; + private String localTwoContext; + private String localTwoExten; + private String localTwoPriority; + private String localTwoUniqueid; + private String destTransfererChannel; + private String transfereeChannel; + private String transfereeChannelState; + private String transfereeChannelStateDesc; + private String transfereeCallerIDNum; + private String transfereeCallerIDName; + private String transfereeConnectedLineNum; + private String transfereeConnectedLineName; + private String transfereeAccountCode; + private String transfereeContext; + private String transfereeExten; + private String transfereePriority; + private String transfereeUniqueid; + + private String transferTargetUniqueID; + private String transferTargetCallerIDName; + private String secondBridgeVideoSourceMode; + private String transferTargetLinkedID; + private String transferTargetPriority; + private String transferTargetCallerIDNum; + private String origBridgeVideoSourceMode; + private String transferTargetConnectedLineNum; + private String transferTargetChannel; + private String transferTargetContext; + private String transferTargetConnectedLineName; + private String transferTargetExten; + private String transferTargetChannelState; + private String transferTargetLanguage; + private String transferTargetAccountCode; + private String transferTargetChannelStateDesc; + + private String transfereeLinkedId; + private String transfereeLanguage; + private String origTransfererLinkedId; + private String secondTransfererLanguage; + private String isexternal; + private String result; + private String secondTransfererLinkedId; + private String origTransfererLanguage; + + public AttendedTransferEvent(Object source) { + super(source); + } + + public String getOrigTransfererChannel() { + return origTransfererChannel; + } + + public void setOrigTransfererChannel(String origTransfererChannel) { + this.origTransfererChannel = origTransfererChannel; + } + + public String getOrigTransfererChannelState() { + return origTransfererChannelState; + } + + public void setOrigTransfererChannelState(String origTransfererChannelState) { + this.origTransfererChannelState = origTransfererChannelState; + } + + public String getOrigTransfererChannelStateDesc() { + return origTransfererChannelStateDesc; + } + + public void setOrigTransfererChannelStateDesc(String origTransfererChannelStateDesc) { + this.origTransfererChannelStateDesc = origTransfererChannelStateDesc; + } + + public String getOrigTransfererCallerIDNum() { + return origTransfererCallerIDNum; + } + + public void setOrigTransfererCallerIDNum(String origTransfererCallerIDNum) { + this.origTransfererCallerIDNum = origTransfererCallerIDNum; + } + + public String getOrigTransfererCallerIDName() { + return origTransfererCallerIDName; + } + + public void setOrigTransfererCallerIDName(String origTransfererCallerIDName) { + this.origTransfererCallerIDName = origTransfererCallerIDName; + } + + public String getOrigTransfererConnectedLineNum() { + return origTransfererConnectedLineNum; + } + + public void setOrigTransfererConnectedLineNum(String origTransfererConnectedLineNum) { + this.origTransfererConnectedLineNum = origTransfererConnectedLineNum; + } + + public String getOrigTransfererConnectedLineName() { + return origTransfererConnectedLineName; + } + + public void setOrigTransfererConnectedLineName(String origTransfererConnectedLineName) { + this.origTransfererConnectedLineName = origTransfererConnectedLineName; + } + + public String getOrigTransfererAccountCode() { + return origTransfererAccountCode; + } + + public void setOrigTransfererAccountCode(String origTransfererAccountCode) { + this.origTransfererAccountCode = origTransfererAccountCode; + } + + public String getOrigTransfererContext() { + return origTransfererContext; + } + + public void setOrigTransfererContext(String origTransfererContext) { + this.origTransfererContext = origTransfererContext; + } + + public String getOrigTransfererExten() { + return origTransfererExten; + } + + public void setOrigTransfererExten(String origTransfererExten) { + this.origTransfererExten = origTransfererExten; + } + + public String getOrigTransfererPriority() { + return origTransfererPriority; + } + + public void setOrigTransfererPriority(String origTransfererPriority) { + this.origTransfererPriority = origTransfererPriority; + } + + public String getOrigTransfererUniqueid() { + return origTransfererUniqueid; + } + + public void setOrigTransfererUniqueid(String origTransfererUniqueid) { + this.origTransfererUniqueid = origTransfererUniqueid; + } + + public String getOrigBridgeUniqueid() { + return origBridgeUniqueid; + } + + public void setOrigBridgeUniqueid(String origBridgeUniqueid) { + this.origBridgeUniqueid = origBridgeUniqueid; + } + + public String getOrigBridgeType() { + return origBridgeType; + } + + public void setOrigBridgeType(String origBridgeType) { + this.origBridgeType = origBridgeType; + } + + public String getOrigBridgeTechnology() { + return origBridgeTechnology; + } + + public void setOrigBridgeTechnology(String origBridgeTechnology) { + this.origBridgeTechnology = origBridgeTechnology; + } + + public String getOrigBridgeCreator() { + return origBridgeCreator; + } + + public void setOrigBridgeCreator(String origBridgeCreator) { + this.origBridgeCreator = origBridgeCreator; + } + + public String getOrigBridgeName() { + return origBridgeName; + } + + public void setOrigBridgeName(String origBridgeName) { + this.origBridgeName = origBridgeName; + } + + public String getOrigBridgeNumChannels() { + return origBridgeNumChannels; + } + + public void setOrigBridgeNumChannels(String origBridgeNumChannels) { + this.origBridgeNumChannels = origBridgeNumChannels; + } + + public String getSecondTransfererChannel() { + return secondTransfererChannel; + } + + public void setSecondTransfererChannel(String secondTransfererChannel) { + this.secondTransfererChannel = secondTransfererChannel; + } + + public String getSecondTransfererChannelState() { + return secondTransfererChannelState; + } + + public void setSecondTransfererChannelState(String secondTransfererChannelState) { + this.secondTransfererChannelState = secondTransfererChannelState; + } + + public String getSecondTransfererChannelStateDesc() { + return secondTransfererChannelStateDesc; + } + + public void setSecondTransfererChannelStateDesc(String secondTransfererChannelStateDesc) { + this.secondTransfererChannelStateDesc = secondTransfererChannelStateDesc; + } + + public String getSecondTransfererCallerIDNum() { + return secondTransfererCallerIDNum; + } + + public void setSecondTransfererCallerIDNum(String secondTransfererCallerIDNum) { + this.secondTransfererCallerIDNum = secondTransfererCallerIDNum; + } + + public String getSecondTransfererCallerIDName() { + return secondTransfererCallerIDName; + } + + public void setSecondTransfererCallerIDName(String secondTransfererCallerIDName) { + this.secondTransfererCallerIDName = secondTransfererCallerIDName; + } + + public String getSecondTransfererConnectedLineNum() { + return secondTransfererConnectedLineNum; + } + + public void setSecondTransfererConnectedLineNum(String secondTransfererConnectedLineNum) { + this.secondTransfererConnectedLineNum = secondTransfererConnectedLineNum; + } + + public String getSecondTransfererConnectedLineName() { + return secondTransfererConnectedLineName; + } + + public void setSecondTransfererConnectedLineName(String secondTransfererConnectedLineName) { + this.secondTransfererConnectedLineName = secondTransfererConnectedLineName; + } + + public String getSecondTransfererAccountCode() { + return secondTransfererAccountCode; + } + + public void setSecondTransfererAccountCode(String secondTransfererAccountCode) { + this.secondTransfererAccountCode = secondTransfererAccountCode; + } + + public String getSecondTransfererContext() { + return secondTransfererContext; + } + + public void setSecondTransfererContext(String secondTransfererContext) { + this.secondTransfererContext = secondTransfererContext; + } + + public String getSecondTransfererExten() { + return secondTransfererExten; + } + + public void setSecondTransfererExten(String secondTransfererExten) { + this.secondTransfererExten = secondTransfererExten; + } + + public String getSecondTransfererPriority() { + return secondTransfererPriority; + } + + public void setSecondTransfererPriority(String secondTransfererPriority) { + this.secondTransfererPriority = secondTransfererPriority; + } + + public String getSecondTransfererUniqueid() { + return secondTransfererUniqueid; + } + + public void setSecondTransfererUniqueid(String secondTransfererUniqueid) { + this.secondTransfererUniqueid = secondTransfererUniqueid; + } + + public String getSecondBridgeUniqueid() { + return secondBridgeUniqueid; + } + + public void setSecondBridgeUniqueid(String secondBridgeUniqueid) { + this.secondBridgeUniqueid = secondBridgeUniqueid; + } + + public String getSecondBridgeType() { + return secondBridgeType; + } + + public void setSecondBridgeType(String secondBridgeType) { + this.secondBridgeType = secondBridgeType; + } + + public String getSecondBridgeTechnology() { + return secondBridgeTechnology; + } + + public void setSecondBridgeTechnology(String secondBridgeTechnology) { + this.secondBridgeTechnology = secondBridgeTechnology; + } + + public String getSecondBridgeCreator() { + return secondBridgeCreator; + } + + public void setSecondBridgeCreator(String secondBridgeCreator) { + this.secondBridgeCreator = secondBridgeCreator; + } + + public String getSecondBridgeName() { + return secondBridgeName; + } + + public void setSecondBridgeName(String secondBridgeName) { + this.secondBridgeName = secondBridgeName; + } + + public String getSecondBridgeNumChannels() { + return secondBridgeNumChannels; + } + + public void setSecondBridgeNumChannels(String secondBridgeNumChannels) { + this.secondBridgeNumChannels = secondBridgeNumChannels; + } + + public String getDestType() { + return destType; + } + + public void setDestType(String destType) { + this.destType = destType; + } + + public String getDestBridgeUniqueid() { + return destBridgeUniqueid; + } + + public void setDestBridgeUniqueid(String destBridgeUniqueid) { + this.destBridgeUniqueid = destBridgeUniqueid; + } + + public String getDestApp() { + return destApp; + } + + public void setDestApp(String destApp) { + this.destApp = destApp; + } + + public String getLocalOneChannel() { + return localOneChannel; + } + + public void setLocalOneChannel(String localOneChannel) { + this.localOneChannel = localOneChannel; + } + + public String getLocalOneChannelState() { + return localOneChannelState; + } + + public void setLocalOneChannelState(String localOneChannelState) { + this.localOneChannelState = localOneChannelState; + } + + public String getLocalOneChannelStateDesc() { + return localOneChannelStateDesc; + } + + public void setLocalOneChannelStateDesc(String localOneChannelStateDesc) { + this.localOneChannelStateDesc = localOneChannelStateDesc; + } + + public String getLocalOneCallerIDNum() { + return localOneCallerIDNum; + } + + public void setLocalOneCallerIDNum(String localOneCallerIDNum) { + this.localOneCallerIDNum = localOneCallerIDNum; + } + + public String getLocalOneCallerIDName() { + return localOneCallerIDName; + } + + public void setLocalOneCallerIDName(String localOneCallerIDName) { + this.localOneCallerIDName = localOneCallerIDName; + } + + public String getLocalOneConnectedLineNum() { + return localOneConnectedLineNum; + } + + public void setLocalOneConnectedLineNum(String localOneConnectedLineNum) { + this.localOneConnectedLineNum = localOneConnectedLineNum; + } + + public String getLocalOneConnectedLineName() { + return localOneConnectedLineName; + } + + public void setLocalOneConnectedLineName(String localOneConnectedLineName) { + this.localOneConnectedLineName = localOneConnectedLineName; + } + + public String getLocalOneAccountCode() { + return localOneAccountCode; + } + + public void setLocalOneAccountCode(String localOneAccountCode) { + this.localOneAccountCode = localOneAccountCode; + } + + public String getLocalOneContext() { + return localOneContext; + } + + public void setLocalOneContext(String localOneContext) { + this.localOneContext = localOneContext; + } + + public String getLocalOneExten() { + return localOneExten; + } + + public void setLocalOneExten(String localOneExten) { + this.localOneExten = localOneExten; + } + + public String getLocalOnePriority() { + return localOnePriority; + } + + public void setLocalOnePriority(String localOnePriority) { + this.localOnePriority = localOnePriority; + } + + public String getLocalOneUniqueid() { + return localOneUniqueid; + } + + public void setLocalOneUniqueid(String localOneUniqueid) { + this.localOneUniqueid = localOneUniqueid; + } + + public String getLocalTwoChannel() { + return localTwoChannel; + } + + public void setLocalTwoChannel(String localTwoChannel) { + this.localTwoChannel = localTwoChannel; + } + + public String getLocalTwoChannelState() { + return localTwoChannelState; + } + + public void setLocalTwoChannelState(String localTwoChannelState) { + this.localTwoChannelState = localTwoChannelState; + } + + public String getLocalTwoChannelStateDesc() { + return localTwoChannelStateDesc; + } + + public void setLocalTwoChannelStateDesc(String localTwoChannelStateDesc) { + this.localTwoChannelStateDesc = localTwoChannelStateDesc; + } + + public String getLocalTwoCallerIDNum() { + return localTwoCallerIDNum; + } + + public void setLocalTwoCallerIDNum(String localTwoCallerIDNum) { + this.localTwoCallerIDNum = localTwoCallerIDNum; + } + + public String getLocalTwoCallerIDName() { + return localTwoCallerIDName; + } + + public void setLocalTwoCallerIDName(String localTwoCallerIDName) { + this.localTwoCallerIDName = localTwoCallerIDName; + } + + public String getLocalTwoConnectedLineNum() { + return localTwoConnectedLineNum; + } + + public void setLocalTwoConnectedLineNum(String localTwoConnectedLineNum) { + this.localTwoConnectedLineNum = localTwoConnectedLineNum; + } + + public String getLocalTwoConnectedLineName() { + return localTwoConnectedLineName; + } + + public void setLocalTwoConnectedLineName(String localTwoConnectedLineName) { + this.localTwoConnectedLineName = localTwoConnectedLineName; + } + + public String getLocalTwoAccountCode() { + return localTwoAccountCode; + } + + public void setLocalTwoAccountCode(String localTwoAccountCode) { + this.localTwoAccountCode = localTwoAccountCode; + } + + public String getLocalTwoContext() { + return localTwoContext; + } + + public void setLocalTwoContext(String localTwoContext) { + this.localTwoContext = localTwoContext; + } + + public String getLocalTwoExten() { + return localTwoExten; + } + + public void setLocalTwoExten(String localTwoExten) { + this.localTwoExten = localTwoExten; + } + + public String getLocalTwoPriority() { + return localTwoPriority; + } + + public void setLocalTwoPriority(String localTwoPriority) { + this.localTwoPriority = localTwoPriority; + } + + public String getLocalTwoUniqueid() { + return localTwoUniqueid; + } + + public void setLocalTwoUniqueid(String localTwoUniqueid) { + this.localTwoUniqueid = localTwoUniqueid; + } + + public String getDestTransfererChannel() { + return destTransfererChannel; + } + + public void setDestTransfererChannel(String destTransfererChannel) { + this.destTransfererChannel = destTransfererChannel; + } + + public String getTransfereeChannel() { + return transfereeChannel; + } + + public void setTransfereeChannel(String transfereeChannel) { + this.transfereeChannel = transfereeChannel; + } + + public String getTransfereeChannelState() { + return transfereeChannelState; + } + + public void setTransfereeChannelState(String transfereeChannelState) { + this.transfereeChannelState = transfereeChannelState; + } + + public String getTransfereeChannelStateDesc() { + return transfereeChannelStateDesc; + } + + public void setTransfereeChannelStateDesc(String transfereeChannelStateDesc) { + this.transfereeChannelStateDesc = transfereeChannelStateDesc; + } + + public String getTransfereeCallerIDNum() { + return transfereeCallerIDNum; + } + + public void setTransfereeCallerIDNum(String transfereeCallerIDNum) { + this.transfereeCallerIDNum = transfereeCallerIDNum; + } + + public String getTransfereeCallerIDName() { + return transfereeCallerIDName; + } + + public void setTransfereeCallerIDName(String transfereeCallerIDName) { + this.transfereeCallerIDName = transfereeCallerIDName; + } + + public String getTransfereeConnectedLineNum() { + return transfereeConnectedLineNum; + } + + public void setTransfereeConnectedLineNum(String transfereeConnectedLineNum) { + this.transfereeConnectedLineNum = transfereeConnectedLineNum; + } + + public String getTransfereeConnectedLineName() { + return transfereeConnectedLineName; + } + + public void setTransfereeConnectedLineName(String transfereeConnectedLineName) { + this.transfereeConnectedLineName = transfereeConnectedLineName; + } + + public String getTransfereeAccountCode() { + return transfereeAccountCode; + } + + public void setTransfereeAccountCode(String transfereeAccountCode) { + this.transfereeAccountCode = transfereeAccountCode; + } + + public String getTransfereeContext() { + return transfereeContext; + } + + public void setTransfereeContext(String transfereeContext) { + this.transfereeContext = transfereeContext; + } + + public String getTransfereeExten() { + return transfereeExten; + } + + public void setTransfereeExten(String transfereeExten) { + this.transfereeExten = transfereeExten; + } + + public String getTransfereePriority() { + return transfereePriority; + } + + public void setTransfereePriority(String transfereePriority) { + this.transfereePriority = transfereePriority; + } + + public String getTransfereeUniqueid() { + return transfereeUniqueid; + } + + public void setTransfereeUniqueid(String transfereeUniqueid) { + this.transfereeUniqueid = transfereeUniqueid; + } + + public String getTransfereeLinkedId() { + return transfereeLinkedId; + } + + public void setTransfereeLinkedId(String transfereeLinkedId) { + this.transfereeLinkedId = transfereeLinkedId; + } + + public String getTransfereeLanguage() { + return transfereeLanguage; + } + + public void setTransfereeLanguage(String transfereeLanguage) { + this.transfereeLanguage = transfereeLanguage; + } + + public String getOrigTransfererLinkedId() { + return origTransfererLinkedId; + } + + public void setOrigTransfererLinkedId(String origTransfererLinkedId) { + this.origTransfererLinkedId = origTransfererLinkedId; + } + + public String getSecondTransfererLanguage() { + return secondTransfererLanguage; + } + + public void setSecondTransfererLanguage(String secondTransfererLanguage) { + this.secondTransfererLanguage = secondTransfererLanguage; + } + + public String getIsexternal() { + return isexternal; + } + + public void setIsexternal(String isexternal) { + this.isexternal = isexternal; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getSecondTransfererLinkedId() { + return secondTransfererLinkedId; + } + + public void setSecondTransfererLinkedId(String secondTransfererLinkedId) { + this.secondTransfererLinkedId = secondTransfererLinkedId; + } + + public String getOrigTransfererLanguage() { + return origTransfererLanguage; + } + + public void setOrigTransfererLanguage(String origTransfererLanguage) { + this.origTransfererLanguage = origTransfererLanguage; + } + + public String getTransferTargetUniqueID() { + return transferTargetUniqueID; + } + + public void setTransferTargetUniqueID(String transferTargetUniqueID) { + this.transferTargetUniqueID = transferTargetUniqueID; + } + + public String getTransferTargetCallerIDName() { + return transferTargetCallerIDName; + } + + public void setTransferTargetCallerIDName(String transferTargetCallerIDName) { + this.transferTargetCallerIDName = transferTargetCallerIDName; + } + + public String getSecondBridgeVideoSourceMode() { + return secondBridgeVideoSourceMode; + } + + public void setSecondBridgeVideoSourceMode(String secondBridgeVideoSourceMode) { + this.secondBridgeVideoSourceMode = secondBridgeVideoSourceMode; + } + + public String getTransferTargetLinkedID() { + return transferTargetLinkedID; + } + + public void setTransferTargetLinkedID(String transferTargetLinkedID) { + this.transferTargetLinkedID = transferTargetLinkedID; + } + + public String getTransferTargetPriority() { + return transferTargetPriority; + } + + public void setTransferTargetPriority(String transferTargetPriority) { + this.transferTargetPriority = transferTargetPriority; + } + + public String getTransferTargetCallerIDNum() { + return transferTargetCallerIDNum; + } + + public void setTransferTargetCallerIDNum(String transferTargetCallerIDNum) { + this.transferTargetCallerIDNum = transferTargetCallerIDNum; + } + + public String getOrigBridgeVideoSourceMode() { + return origBridgeVideoSourceMode; + } + + public void setOrigBridgeVideoSourceMode(String origBridgeVideoSourceMode) { + this.origBridgeVideoSourceMode = origBridgeVideoSourceMode; + } + + public String getTransferTargetConnectedLineNum() { + return transferTargetConnectedLineNum; + } + + public void setTransferTargetConnectedLineNum(String transferTargetConnectedLineNum) { + this.transferTargetConnectedLineNum = transferTargetConnectedLineNum; + } + + public String getTransferTargetChannel() { + return transferTargetChannel; + } + + public void setTransferTargetChannel(String transferTargetChannel) { + this.transferTargetChannel = transferTargetChannel; + } + + public String getTransferTargetContext() { + return transferTargetContext; + } + + public void setTransferTargetContext(String transferTargetContext) { + this.transferTargetContext = transferTargetContext; + } + + public String getTransferTargetConnectedLineName() { + return transferTargetConnectedLineName; + } + + public void setTransferTargetConnectedLineName(String transferTargetConnectedLineName) { + this.transferTargetConnectedLineName = transferTargetConnectedLineName; + } + + public String getTransferTargetExten() { + return transferTargetExten; + } + + public void setTransferTargetExten(String transferTargetExten) { + this.transferTargetExten = transferTargetExten; + } + + public String getTransferTargetChannelState() { + return transferTargetChannelState; + } + + public void setTransferTargetChannelState(String transferTargetChannelState) { + this.transferTargetChannelState = transferTargetChannelState; + } + + public String getTransferTargetLanguage() { + return transferTargetLanguage; + } + + public void setTransferTargetLanguage(String transferTargetLanguage) { + this.transferTargetLanguage = transferTargetLanguage; + } + + public String getTransferTargetAccountCode() { + return transferTargetAccountCode; + } + + public void setTransferTargetAccountCode(String transferTargetAccountCode) { + this.transferTargetAccountCode = transferTargetAccountCode; + } + + public String getTransferTargetChannelStateDesc() { + return transferTargetChannelStateDesc; + } + + public void setTransferTargetChannelStateDesc(String transferTargetChannelStateDesc) { + this.transferTargetChannelStateDesc = transferTargetChannelStateDesc; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/AuthDetail.java b/src/main/java/org/asteriskjava/manager/event/AuthDetail.java new file mode 100644 index 000000000..b9cf5cb66 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AuthDetail.java @@ -0,0 +1,118 @@ +package org.asteriskjava.manager.event; + + +/** + * An AuthDetail event is triggered in response to a + * {@link org.asteriskjava.manager.action.PJSipShowEndpoint}, + * and contains information about a PJSIP Contact + *

          + * + * @author Steve Sether + * @version $Id$ + * @since 12 + */ + +public class AuthDetail extends ResponseEvent { + + /** + * Serial version identifier. + */ + private static final long serialVersionUID = -4998727723768836212L; + + private String event; + private String objectType; + private String objectName; + private String username; + private String password; + private String md5Cred; + private String realm; + private int nonceLifetime; + private String authType; + private String EndpointName; + + public AuthDetail(Object source) { + super(source); + } + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + public String getObjectName() { + return objectName; + } + + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getMd5Cred() { + return md5Cred; + } + + public void setMd5Cred(String md5Cred) { + this.md5Cred = md5Cred; + } + + public String getRealm() { + return realm; + } + + public void setRealm(String realm) { + this.realm = realm; + } + + public int getNonceLifetime() { + return nonceLifetime; + } + + public void setNonceLifetime(int nonceLifetime) { + this.nonceLifetime = nonceLifetime; + } + + public String getAuthType() { + return authType; + } + + public void setAuthType(String authType) { + this.authType = authType; + } + + public String getEndpointName() { + return EndpointName; + } + + public void setEndpointName(String endpointName) { + EndpointName = endpointName; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/AuthMethodNotAllowedEvent.java b/src/main/java/org/asteriskjava/manager/event/AuthMethodNotAllowedEvent.java new file mode 100644 index 000000000..6eaa33565 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AuthMethodNotAllowedEvent.java @@ -0,0 +1,17 @@ +package org.asteriskjava.manager.event; + +public final class AuthMethodNotAllowedEvent extends AbstractSecurityEvent { + private String authMethod; + + public AuthMethodNotAllowedEvent(Object source) { + super(source); + } + + public String getAuthMethod() { + return authMethod; + } + + public void setAuthMethod(String value) { + this.authMethod = value; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/BlindTransferEvent.java b/src/main/java/org/asteriskjava/manager/event/BlindTransferEvent.java new file mode 100644 index 000000000..2375944ed --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/BlindTransferEvent.java @@ -0,0 +1,298 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public class BlindTransferEvent extends AbstractBridgeEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + private String transfererUniqueId; + private String transfererConnectedLineNum; + private String transfererConnectedLineName; + private String transfererCallerIdName; + private String transfererCallerIdNum; + private String transfererChannel; + private String transfererChannelState; + private String transfererChannelStateDesc; + private Integer transfererPriority; + private String transfererContext; + + private String transfereeUniqueId; + private String transfereeConnectedLineNum; + private String transfereeConnectedLineName; + private String transfereeCallerIdName; + private String transfereeCallerIdNum; + private String transfereeChannel; + private String transfereeChannelState; + private String transfereeChannelStateDesc; + private Integer transfereePriority; + private String transfereeContext; + private String transfereeExten; + + private String extension; + private String isexternal; + private String result; + + private String transfereeLinkedId; + private String transfererAccountCode; + private String transfererExten; + private String transfererLanguage; + private String transfererLinkedId; + private String transfereeLanguage; + private String transfereeaccountcode; + + public BlindTransferEvent(Object source) { + super(source); + } + + public String getTransfererUniqueId() { + return transfererUniqueId; + } + + public void setTransfererUniqueId(String transfererUniqueId) { + this.transfererUniqueId = transfererUniqueId; + } + + public String getTransfererConnectedLineNum() { + return transfererConnectedLineNum; + } + + public void setTransfererConnectedLineNum(String transfererConnectedLineNum) { + this.transfererConnectedLineNum = transfererConnectedLineNum; + } + + public String getTransfererConnectedLineName() { + return transfererConnectedLineName; + } + + public void setTransfererConnectedLineName(String transfererConnectedLineName) { + this.transfererConnectedLineName = transfererConnectedLineName; + } + + public String getTransfererCallerIdName() { + return transfererCallerIdName; + } + + public void setTransfererCallerIdName(String transfererCallerIdName) { + this.transfererCallerIdName = transfererCallerIdName; + } + + public String getTransfererCallerIdNum() { + return transfererCallerIdNum; + } + + public void setTransfererCallerIdNum(String transfererCallerIdNum) { + this.transfererCallerIdNum = transfererCallerIdNum; + } + + public String getTransfererChannel() { + return transfererChannel; + } + + public void setTransfererChannel(String transfererChannel) { + this.transfererChannel = transfererChannel; + } + + public String getTransfererChannelState() { + return transfererChannelState; + } + + public void setTransfererChannelState(String transfererChannelState) { + this.transfererChannelState = transfererChannelState; + } + + public String getTransfererChannelStateDesc() { + return transfererChannelStateDesc; + } + + public void setTransfererChannelStateDesc(String transfererChannelStateDesc) { + this.transfererChannelStateDesc = transfererChannelStateDesc; + } + + public Integer getTransfererPriority() { + return transfererPriority; + } + + public void setTransfererPriority(Integer transfererPriority) { + this.transfererPriority = transfererPriority; + } + + public String getTransfererContext() { + return transfererContext; + } + + public void setTransfererContext(String transfererContext) { + this.transfererContext = transfererContext; + } + + public String getTransfereeUniqueId() { + return transfereeUniqueId; + } + + public void setTransfereeUniqueId(String transfereeUniqueId) { + this.transfereeUniqueId = transfereeUniqueId; + } + + public String getTransfereeConnectedLineNum() { + return transfereeConnectedLineNum; + } + + public void setTransfereeConnectedLineNum(String transfereeConnectedLineNum) { + this.transfereeConnectedLineNum = transfereeConnectedLineNum; + } + + public String getTransfereeConnectedLineName() { + return transfereeConnectedLineName; + } + + public void setTransfereeConnectedLineName(String transfereeConnectedLineName) { + this.transfereeConnectedLineName = transfereeConnectedLineName; + } + + public String getTransfereeCallerIdName() { + return transfereeCallerIdName; + } + + public void setTransfereeCallerIdName(String transfereeCallerIdName) { + this.transfereeCallerIdName = transfereeCallerIdName; + } + + public String getTransfereeCallerIdNum() { + return transfereeCallerIdNum; + } + + public void setTransfereeCallerIdNum(String transfereeCallerIdNum) { + this.transfereeCallerIdNum = transfereeCallerIdNum; + } + + public String getTransfereeChannel() { + return transfereeChannel; + } + + public void setTransfereeChannel(String transfereeChannel) { + this.transfereeChannel = transfereeChannel; + } + + public String getTransfereeChannelState() { + return transfereeChannelState; + } + + public void setTransfereeChannelState(String transfereeChannelState) { + this.transfereeChannelState = transfereeChannelState; + } + + public String getTransfereeChannelStateDesc() { + return transfereeChannelStateDesc; + } + + public void setTransfereeChannelStateDesc(String transfereeChannelStateDesc) { + this.transfereeChannelStateDesc = transfereeChannelStateDesc; + } + + public Integer getTransfereePriority() { + return transfereePriority; + } + + public void setTransfereePriority(Integer transfereePriority) { + this.transfereePriority = transfereePriority; + } + + public String getTransfereeContext() { + return transfereeContext; + } + + public void setTransfereeContext(String transfereeContext) { + this.transfereeContext = transfereeContext; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public String getIsexternal() { + return isexternal; + } + + public void setIsexternal(String isexternal) { + this.isexternal = isexternal; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getTransfereeExten() { + return transfereeExten; + } + + public void setTransfereeExten(String transfereeExten) { + this.transfereeExten = transfereeExten; + } + + public String getTransfereeLinkedId() { + return transfereeLinkedId; + } + + public void setTransfereeLinkedId(String transfereeLinkedId) { + this.transfereeLinkedId = transfereeLinkedId; + } + + public String getTransfererAccountCode() { + return transfererAccountCode; + } + + public void setTransfererAccountCode(String transfererAccountCode) { + this.transfererAccountCode = transfererAccountCode; + } + + public String getTransfererExten() { + return transfererExten; + } + + public void setTransfererExten(String transfererExten) { + this.transfererExten = transfererExten; + } + + public String getTransfererLanguage() { + return transfererLanguage; + } + + public void setTransfererLanguage(String transfererLanguage) { + this.transfererLanguage = transfererLanguage; + } + + public String getTransfererLinkedId() { + return transfererLinkedId; + } + + public void setTransfererLinkedId(String transfererLinkedId) { + this.transfererLinkedId = transfererLinkedId; + } + + public String getTransfereeLanguage() { + return transfereeLanguage; + } + + public void setTransfereeLanguage(String transfereeLanguage) { + this.transfereeLanguage = transfereeLanguage; + } + + public void setTransfereeaccountcode(String transfereeaccountcode) { + this.transfereeaccountcode = transfereeaccountcode; + } + + public String getTransfereeaccountcode() { + return transfereeaccountcode; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/BridgeCreateEvent.java b/src/main/java/org/asteriskjava/manager/event/BridgeCreateEvent.java new file mode 100644 index 000000000..b6ada6b54 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/BridgeCreateEvent.java @@ -0,0 +1,30 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public class BridgeCreateEvent extends AbstractBridgeEvent { + private String bridgevideosourcemode; + + /** + * @param bridgevideosourcemode the bridgevideosourcemode to set + */ + public void setBridgevideosourcemode(String bridgevideosourcemode) { + this.bridgevideosourcemode = bridgevideosourcemode; + } + + /** + * @return the bridgevideosourcemode + */ + public String getBridgevideosourcemode() { + return bridgevideosourcemode; + } + + private static final long serialVersionUID = 1L; + + public BridgeCreateEvent(Object source) { + super(source); + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/BridgeDestroyEvent.java b/src/main/java/org/asteriskjava/manager/event/BridgeDestroyEvent.java new file mode 100644 index 000000000..06c2d0a9d --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/BridgeDestroyEvent.java @@ -0,0 +1,15 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public class BridgeDestroyEvent extends AbstractBridgeEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + + public BridgeDestroyEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/BridgeEnterEvent.java b/src/main/java/org/asteriskjava/manager/event/BridgeEnterEvent.java new file mode 100644 index 000000000..6596eaae2 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/BridgeEnterEvent.java @@ -0,0 +1,62 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public class BridgeEnterEvent extends AbstractBridgeEvent { + /** + * + */ + private static final long serialVersionUID = 2L; + private String uniqueId; + private String channel; + private String language; + private String linkedId; + + private String swapuniqueid; + + public BridgeEnterEvent(Object source) { + super(source); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getSwapuniqueid() { + return swapuniqueid; + } + + public void setSwapuniqueid(String swapuniqueid) { + this.swapuniqueid = swapuniqueid; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/BridgeEvent.java b/src/main/java/org/asteriskjava/manager/event/BridgeEvent.java index 7fe2db624..c9067c4d9 100644 --- a/src/main/java/org/asteriskjava/manager/event/BridgeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/BridgeEvent.java @@ -23,14 +23,13 @@ * 1.4 report individual events: {@link org.asteriskjava.manager.event.LinkEvent} and * {@link org.asteriskjava.manager.event.UnlinkEvent}.For maximum compatibily do not use the Link and Unlink * events in your code. Just use the Bridge event and check for {@link #isLink()} and {@link #isUnlink()}. - *

          + *
          * It is implemented in channel.c * * @author srt * @version $Id$ */ -public class BridgeEvent extends ManagerEvent -{ +public class BridgeEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -68,8 +67,7 @@ public class BridgeEvent extends ManagerEvent private String callerId1; private String callerId2; - public BridgeEvent(Object source) - { + public BridgeEvent(Object source) { super(source); } @@ -81,8 +79,7 @@ public BridgeEvent(Object source) * @see #BRIDGE_STATE_UNLINK * @since 1.0.0 */ - public String getBridgeState() - { + public String getBridgeState() { return bridgeState; } @@ -92,8 +89,7 @@ public String getBridgeState() * @param bridgeState "Link" if the two channels have been linked, "Unlink" if they have been unlinked. * @since 1.0.0 */ - public void setBridgeState(String bridgeState) - { + public void setBridgeState(String bridgeState) { this.bridgeState = bridgeState; } @@ -108,8 +104,7 @@ public void setBridgeState(String bridgeState) * @see #BRIDGE_TYPE_RTP_REMOTE * @since 1.0.0 */ - public String getBridgeType() - { + public String getBridgeType() { return bridgeType; } @@ -119,8 +114,7 @@ public String getBridgeType() * @param bridgeType the bridge type. * @since 1.0.0 */ - public void setBridgeType(String bridgeType) - { + public void setBridgeType(String bridgeType) { this.bridgeType = bridgeType; } @@ -129,8 +123,7 @@ public void setBridgeType(String bridgeType) * * @return the unique id of the first channel. */ - public String getUniqueId1() - { + public String getUniqueId1() { return uniqueId1; } @@ -139,8 +132,7 @@ public String getUniqueId1() * * @param uniqueId1 the unique id of the first channel. */ - public void setUniqueId1(String uniqueId1) - { + public void setUniqueId1(String uniqueId1) { this.uniqueId1 = uniqueId1; } @@ -149,8 +141,7 @@ public void setUniqueId1(String uniqueId1) * * @return the unique id of the second channel. */ - public String getUniqueId2() - { + public String getUniqueId2() { return uniqueId2; } @@ -159,8 +150,7 @@ public String getUniqueId2() * * @param uniqueId2 the unique id of the second channel. */ - public void setUniqueId2(String uniqueId2) - { + public void setUniqueId2(String uniqueId2) { this.uniqueId2 = uniqueId2; } @@ -169,8 +159,7 @@ public void setUniqueId2(String uniqueId2) * * @return the name of the first channel. */ - public String getChannel1() - { + public String getChannel1() { return channel1; } @@ -179,8 +168,7 @@ public String getChannel1() * * @param channel1 the name of the first channel. */ - public void setChannel1(String channel1) - { + public void setChannel1(String channel1) { this.channel1 = channel1; } @@ -189,8 +177,7 @@ public void setChannel1(String channel1) * * @return the name of the second channel. */ - public String getChannel2() - { + public String getChannel2() { return channel2; } @@ -199,8 +186,7 @@ public String getChannel2() * * @param channel2 the name of the second channel. */ - public void setChannel2(String channel2) - { + public void setChannel2(String channel2) { this.channel2 = channel2; } @@ -210,8 +196,7 @@ public void setChannel2(String channel2) * @return the Caller*Id number of the first channel. * @since 0.2 */ - public String getCallerId1() - { + public String getCallerId1() { return callerId1; } @@ -221,8 +206,7 @@ public String getCallerId1() * @param callerId1 the Caller*Id number of the first channel. * @since 0.2 */ - public void setCallerId1(String callerId1) - { + public void setCallerId1(String callerId1) { this.callerId1 = callerId1; } @@ -232,8 +216,7 @@ public void setCallerId1(String callerId1) * @return the Caller*Id number of the second channel. * @since 0.2 */ - public String getCallerId2() - { + public String getCallerId2() { return callerId2; } @@ -243,8 +226,7 @@ public String getCallerId2() * @param callerId2 the Caller*Id number of the second channel. * @since 0.2 */ - public void setCallerId2(String callerId2) - { + public void setCallerId2(String callerId2) { this.callerId2 = callerId2; } @@ -254,9 +236,8 @@ public void setCallerId2(String callerId2) * @return true the two channels have been linked, false if they have been unlinked. * @since 1.0.0 */ - public boolean isLink() - { - return bridgeState != null && BRIDGE_STATE_LINK.equalsIgnoreCase(bridgeState); + public boolean isLink() { + return BRIDGE_STATE_LINK.equalsIgnoreCase(bridgeState); } /** @@ -265,8 +246,7 @@ public boolean isLink() * @return true the two channels have been unlinked, false if they have been linked. * @since 1.0.0 */ - public boolean isUnlink() - { - return bridgeState != null && BRIDGE_STATE_UNLINK.equalsIgnoreCase(bridgeState); + public boolean isUnlink() { + return BRIDGE_STATE_UNLINK.equalsIgnoreCase(bridgeState); } } diff --git a/src/main/java/org/asteriskjava/manager/event/BridgeExecEvent.java b/src/main/java/org/asteriskjava/manager/event/BridgeExecEvent.java index 2e1c1a1ba..b6b316c4d 100644 --- a/src/main/java/org/asteriskjava/manager/event/BridgeExecEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/BridgeExecEvent.java @@ -25,8 +25,7 @@ * @version $Id$ * @since 1.0.0 */ -public class BridgeExecEvent extends ManagerEvent -{ +public class BridgeExecEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -40,8 +39,7 @@ public class BridgeExecEvent extends ManagerEvent private String channel1; private String channel2; - public BridgeExecEvent(Object source) - { + public BridgeExecEvent(Object source) { super(source); } @@ -56,13 +54,11 @@ public BridgeExecEvent(Object source) * @see #RESPONSE_FAILED * @see #RESPONSE_SUCCESS */ - public String getResponse() - { + public String getResponse() { return response; } - public void setResponse(String response) - { + public void setResponse(String response) { this.response = response; } @@ -77,13 +73,11 @@ public void setResponse(String response) * * @return the reason for failure or null on success. */ - public String getReason() - { + public String getReason() { return reason; } - public void setReason(String reason) - { + public void setReason(String reason) { this.reason = reason; } @@ -92,13 +86,11 @@ public void setReason(String reason) * * @return name of the first channel. */ - public String getChannel1() - { + public String getChannel1() { return channel1; } - public void setChannel1(String channel1) - { + public void setChannel1(String channel1) { this.channel1 = channel1; } @@ -107,13 +99,11 @@ public void setChannel1(String channel1) * * @return name of the second channel. */ - public String getChannel2() - { + public String getChannel2() { return channel2; } - public void setChannel2(String channel2) - { + public void setChannel2(String channel2) { this.channel2 = channel2; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/BridgeLeaveEvent.java b/src/main/java/org/asteriskjava/manager/event/BridgeLeaveEvent.java new file mode 100644 index 000000000..62cccf771 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/BridgeLeaveEvent.java @@ -0,0 +1,53 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public class BridgeLeaveEvent extends AbstractBridgeEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + private String uniqueId; + private String channel; + private String language; + private String linkedId; + + public BridgeLeaveEvent(Object source) { + super(source); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/BridgeMergeEvent.java b/src/main/java/org/asteriskjava/manager/event/BridgeMergeEvent.java new file mode 100644 index 000000000..54c45d967 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/BridgeMergeEvent.java @@ -0,0 +1,121 @@ +package org.asteriskjava.manager.event; + +public class BridgeMergeEvent extends ManagerEvent { + + private static final long serialVersionUID = 1L; + + public BridgeMergeEvent(Object source) { + super(source); + } + + private Integer fromBridgeNumChannels; + private Integer toBridgeNumChannels; + private String fromBridgeName; + private String fromBridgeUniqueId; + private String fromBridgeCreator; + private String toBridgeName; + private String fromBridgeTechnology; + private String toBridgeUniqueId; + private String toBridgeTechnology; + private String fromBridgeType; + private String toBridgeType; + private String toBridgeCreator; + + public Integer getFromBridgeNumChannels() { + return fromBridgeNumChannels; + } + + public void setFromBridgeNumChannels(Integer fromBridgeNumChannels) { + this.fromBridgeNumChannels = fromBridgeNumChannels; + } + + public Integer getToBridgeNumChannels() { + return toBridgeNumChannels; + } + + public void setToBridgeNumChannels(Integer toBridgeNumChannels) { + this.toBridgeNumChannels = toBridgeNumChannels; + } + + public String getFromBridgeName() { + return fromBridgeName; + } + + public void setFromBridgeName(String fromBridgeName) { + this.fromBridgeName = fromBridgeName; + } + + public String getFromBridgeUniqueId() { + return fromBridgeUniqueId; + } + + public void setFromBridgeUniqueId(String fromBridgeUniqueId) { + this.fromBridgeUniqueId = fromBridgeUniqueId; + } + + public String getFromBridgeCreator() { + return fromBridgeCreator; + } + + public void setFromBridgeCreator(String fromBridgeCreator) { + this.fromBridgeCreator = fromBridgeCreator; + } + + public String getToBridgeName() { + return toBridgeName; + } + + public void setToBridgeName(String toBridgeName) { + this.toBridgeName = toBridgeName; + } + + public String getFromBridgeTechnology() { + return fromBridgeTechnology; + } + + public void setFromBridgeTechnology(String fromBridgeTechnology) { + this.fromBridgeTechnology = fromBridgeTechnology; + } + + public String getToBridgeUniqueId() { + return toBridgeUniqueId; + } + + public void setToBridgeUniqueId(String toBridgeUniqueId) { + this.toBridgeUniqueId = toBridgeUniqueId; + } + + public String getToBridgeTechnology() { + return toBridgeTechnology; + } + + public void setToBridgeTechnology(String toBridgeTechnology) { + this.toBridgeTechnology = toBridgeTechnology; + } + + public String getFromBridgeType() { + return fromBridgeType; + } + + public void setFromBridgeType(String fromBridgeType) { + this.fromBridgeType = fromBridgeType; + } + + public String getToBridgeType() { + return toBridgeType; + } + + public void setToBridgeType(String toBridgeType) { + this.toBridgeType = toBridgeType; + } + + public String getToBridgeCreator() { + return toBridgeCreator; + } + + public void setToBridgeCreator(String toBridgeCreator) { + this.toBridgeCreator = toBridgeCreator; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/BridgeVideoSourceUpdateEvent.java b/src/main/java/org/asteriskjava/manager/event/BridgeVideoSourceUpdateEvent.java new file mode 100644 index 000000000..c2495f584 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/BridgeVideoSourceUpdateEvent.java @@ -0,0 +1,41 @@ +/* + * Copyright 2023 Hector Espert + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * Raised when the channel that is the source of video in a bridge changes. + */ +public class BridgeVideoSourceUpdateEvent extends AbstractBridgeEvent { + private String bridgePreviousVideoSource; + + public BridgeVideoSourceUpdateEvent(Object source) { + super(source); + } + + /** + * Gets the unique ID of the channel that was the video source. + * + * @return the unique ID of the channel that was the video source. + */ + public String getBridgePreviousVideoSource() { + return bridgePreviousVideoSource; + } + + public void setBridgePreviousVideoSource(String bridgePreviousVideoSource) { + this.bridgePreviousVideoSource = bridgePreviousVideoSource; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/CdrEvent.java b/src/main/java/org/asteriskjava/manager/event/CdrEvent.java index 817a5aa47..fe15b41f5 100644 --- a/src/main/java/org/asteriskjava/manager/event/CdrEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/CdrEvent.java @@ -16,38 +16,39 @@ */ package org.asteriskjava.manager.event; +import org.asteriskjava.util.DateUtil; + import java.util.Date; +import java.util.HashMap; +import java.util.Map; import java.util.TimeZone; -import org.asteriskjava.util.DateUtil; - /** * A CdrEvent is triggered when a call detail record is generated, usually at the end of a call.

          * To enable CdrEvents you have to add enabled = yes to the general section in * cdr_manager.conf.

          * This event is implemented in cdr/cdr_manager.c - * + * * @author srt * @version $Id$ */ -public class CdrEvent extends ManagerEvent -{ +public class CdrEvent extends ManagerEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 2541424315212201670L; - + public static final String DISPOSITION_NO_ANSWER = "NO ANSWER"; public static final String DISPOSITION_FAILED = "FAILED"; public static final String DISPOSITION_BUSY = "BUSY"; public static final String DISPOSITION_ANSWERED = "ANSWERED"; public static final String DISPOSITION_UNKNOWN = "UNKNOWN"; - + public static final String AMA_FLAG_OMIT = "OMIT"; public static final String AMA_FLAG_BILLING = "BILLING"; public static final String AMA_FLAG_DOCUMENTATION = "DOCUMENTATION"; public static final String AMA_FLAG_UNKNOWN = "Unknown"; - + private String accountCode; private String src; private String destination; @@ -66,384 +67,352 @@ public class CdrEvent extends ManagerEvent private String amaFlags; private String uniqueId; private String userField; + private String recordfile; + private Map dynamicProperties; /** * @param source */ - public CdrEvent(Object source) - { + public CdrEvent(Object source) { super(source); + dynamicProperties = new HashMap<>(); } /** * Returns the account number that is usually used to identify the party to bill for the call.

          * Corresponds to CDR field accountcode. - * + * * @return the account number. */ - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } /** * Sets the account number. - * + * * @param accountCode the account number. */ - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } /** * Returns the Caller*ID number.

          * Corresponds to CDR field src. - * + * * @return the Caller*ID number. */ - public String getSrc() - { + public String getSrc() { return src; } /** * Sets the Caller*ID number. - * + * * @param source the Caller*ID number. */ - public void setSrc(String source) - { + public void setSrc(String source) { this.src = source; } /** * Returns the destination extension.

          * Corresponds to CDR field dst. - * + * * @return the destination extension. */ - public String getDestination() - { + public String getDestination() { return destination; } /** * Sets the destination extension. - * + * * @param destination the destination extension. */ - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } /** * Returns the destination context.

          * Corresponds to CDR field dcontext. - * + * * @return the destination context. */ - public String getDestinationContext() - { + public String getDestinationContext() { return destinationContext; } /** * Sets the destination context. - * + * * @param destinationContext the destination context. */ - public void setDestinationContext(String destinationContext) - { + public void setDestinationContext(String destinationContext) { this.destinationContext = destinationContext; } /** * Returns the Caller*ID with text.

          * Corresponds to CDR field clid. - * + * * @return the Caller*ID with text */ - public String getCallerId() - { + public String getCallerId() { return callerId; } /** * Sets the Caller*ID with text. - * + * * @param callerId the Caller*ID with text. */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } /** * Returns the name of the channel, for example "SIP/1310-asfe".

          * Corresponds to CDR field channel. - * + * * @return the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel. - * + * * @param channel the name of the channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the name of the destination channel if appropriate.

          * Corresponds to CDR field dstchannel. - * + * * @return the name of the destination channel or null if not available. */ - public String getDestinationChannel() - { + public String getDestinationChannel() { return destinationChannel; } /** * Sets the name of the destination channel. - * + * * @param destinationChannel the name of the destination channel. */ - public void setDestinationChannel(String destinationChannel) - { + public void setDestinationChannel(String destinationChannel) { this.destinationChannel = destinationChannel; } /** * Returns the last application if appropriate, for example "VoiceMail".

          * Corresponds to CDR field lastapp. - * + * * @return the last application or null if not avaialble. */ - public String getLastApplication() - { + public String getLastApplication() { return lastApplication; } /** * Sets the last application. - * + * * @param lastApplication the last application. */ - public void setLastApplication(String lastApplication) - { + public void setLastApplication(String lastApplication) { this.lastApplication = lastApplication; } /** * Returns the last application's data (arguments), for example "s1234".

          * Corresponds to CDR field lastdata. - * + * * @return the last application's data or null if not avaialble. */ - public String getLastData() - { + public String getLastData() { return lastData; } /** * Set the last application's data. - * + * * @param lastData the last application's data. */ - public void setLastData(String lastData) - { + public void setLastData(String lastData) { this.lastData = lastData; } /** * Returns when the call has started.

          * This corresponds to CDR field start. - * + * * @return A string of the format "%Y-%m-%d %T" (strftime(3)) representing the date/time the * call has started, for example "2006-05-19 11:54:48". */ - public String getStartTime() - { + public String getStartTime() { return startTime; } - + /** * Returns the start time as Date object.

          - * This method asumes that the Asterisk server's timezone equals the default + * This method asumes that the Asterisk server's timezone equals the default * timezone of your JVM. - * + * * @return the start time as Date object. * @since 0.3 */ - public Date getStartTimeAsDate() - { + public Date getStartTimeAsDate() { return DateUtil.parseDateTime(startTime); } - + /** * Returns the start time as Date object. - * + * * @param tz the timezone of the Asterisk server. * @return the start time as Date object. * @since 0.3 */ - public Date getStartTimeAsDate(TimeZone tz) - { + public Date getStartTimeAsDate(TimeZone tz) { return DateUtil.parseDateTime(startTime, tz); } /** * Sets the date/time when the call has started. - * + * * @param startTime the date/time when the call has started. */ - public void setStartTime(String startTime) - { + public void setStartTime(String startTime) { this.startTime = startTime; } /** * Returns when the call was answered.

          * This corresponds to CDR field answered. - * + * * @return A string of the format "%Y-%m-%d %T" (strftime(3)) representing the date/time the * call was answered, for example "2006-05-19 11:55:01" */ - public String getAnswerTime() - { + public String getAnswerTime() { return answerTime; } /** * Returns the answer time as Date object.

          - * This method asumes that the Asterisk server's timezone equals the default + * This method asumes that the Asterisk server's timezone equals the default * timezone of your JVM. - * + * * @return the answer time as Date object. * @since 0.3 */ - public Date getAnswerTimeAsDate() - { + public Date getAnswerTimeAsDate() { return DateUtil.parseDateTime(answerTime); } /** * Returns the answer time as Date object. - * + * * @param tz the timezone of the Asterisk server. * @return the answer time as Date object. * @since 0.3 */ - public Date getAnswerTimeAsDate(TimeZone tz) - { + public Date getAnswerTimeAsDate(TimeZone tz) { return DateUtil.parseDateTime(answerTime, tz); } /** * Sets the date/time when the call was answered. - * + * * @param answerTime the date/time when the call was answered. */ - public void setAnswerTime(String answerTime) - { + public void setAnswerTime(String answerTime) { this.answerTime = answerTime; } /** * Returns when the call has ended.

          * This corresponds to CDR field end. - * + * * @return A string of the format "%Y-%m-%d %T" (strftime(3)) representing the date/time the * call has ended, for example "2006-05-19 11:58:21" */ - public String getEndTime() - { + public String getEndTime() { return endTime; } /** * Returns the end time as Date object.

          - * This method asumes that the Asterisk server's timezone equals the default + * This method asumes that the Asterisk server's timezone equals the default * timezone of your JVM. - * + * * @return the end time as Date object. * @since 0.3 */ - public Date getEndTimeAsDate() - { + public Date getEndTimeAsDate() { return DateUtil.parseDateTime(endTime); } - + /** * Returns the end time as Date object. - * + * * @param tz the timezone of the Asterisk server. * @return the end time as Date object. * @since 0.3 */ - public Date getEndTimeAsDate(TimeZone tz) - { + public Date getEndTimeAsDate(TimeZone tz) { return DateUtil.parseDateTime(endTime, tz); } /** * Sets the date/time when the call has ended. - * + * * @param endTime the date/time when the call has ended. */ - public void setEndTime(String endTime) - { + public void setEndTime(String endTime) { this.endTime = endTime; } /** * Returns the total time (in seconds) the caller spent in the system from dial to hangup.

          * Corresponds to CDR field duration. - * + * * @return the total time in system in seconds. */ - public Integer getDuration() - { + public Integer getDuration() { return duration; } /** * Sets the total time in system. - * + * * @param duration total time in system in seconds. */ - public void setDuration(Integer duration) - { + public void setDuration(Integer duration) { this.duration = duration; } /** * Returns the total time (in seconds) the call was up from answer to hangup.

          * Corresponds to CDR field billsec. - * + * * @return the total time in call in seconds. */ - public Integer getBillableSeconds() - { + public Integer getBillableSeconds() { return billableSeconds; } /** * Sets the total time in call. - * + * * @param billableSeconds the total time in call in seconds. */ - public void setBillableSeconds(Integer billableSeconds) - { + public void setBillableSeconds(Integer billableSeconds) { this.billableSeconds = billableSeconds; } @@ -458,21 +427,19 @@ public void setBillableSeconds(Integer billableSeconds) *

        • {@link #DISPOSITION_UNKNOWN} *
        * Corresponds to CDR field disposition. - * + * * @return the disposition. */ - public String getDisposition() - { + public String getDisposition() { return disposition; } /** * Sets the disposition. - * + * * @param disposition the disposition. */ - public void setDisposition(String disposition) - { + public void setDisposition(String disposition) { this.disposition = disposition; } @@ -486,62 +453,88 @@ public void setDisposition(String disposition) *
      • {@link #AMA_FLAG_UNKNOWN} *
      * Corresponds to CDR field amaflags. - * + * * @return the AMA flags. */ - public String getAmaFlags() - { + public String getAmaFlags() { return amaFlags; } /** * Sets the AMA (Automated Message Accounting) flags. - * + * * @param amaFlags the AMA (Automated Message Accounting) flags. */ - public void setAmaFlags(String amaFlags) - { + public void setAmaFlags(String amaFlags) { this.amaFlags = amaFlags; } /** * Returns the unique id of the channel. - * + * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } /** * Sets the unique id of the channel. - * + * * @param uniqueId the unique id of the channel. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } /** * Returns the user-defined field as set by Set(CDR(userfield)=Value).

      * Corresponds to CDR field userfield. - * + * * @return the user-defined field. */ - public String getUserField() - { + public String getUserField() { return userField; } /** * Sets the user-defined field. - * + * * @param userField the user-defined field */ - public void setUserField(String userField) - { + public void setUserField(String userField) { this.userField = userField; } + + /** + * Returns record filename. + * + * @return record filename. + */ + + public String getRecordfile() { + return recordfile; + } + + /** + * Sets record filename. + * + * @param recordfile record filename. + */ + + public void setRecordfile(String recordfile) { + this.recordfile = recordfile; + } + + public Map getDynamicProperties() { + return dynamicProperties; + } + + public void setDynamicProperties(Map dynamicProperties) { + this.dynamicProperties = dynamicProperties; + } + + public void addDynamicProperties(String key, String value) { + this.dynamicProperties.put(key,value); + } } diff --git a/src/main/java/org/asteriskjava/manager/event/CelEvent.java b/src/main/java/org/asteriskjava/manager/event/CelEvent.java new file mode 100644 index 000000000..6eded008b --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/CelEvent.java @@ -0,0 +1,180 @@ +package org.asteriskjava.manager.event; + +/** + * Raised when a Channel Event Log is generated for a channel. + *

      + * Asterisk AMI Events: CEL + */ +public class CelEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + public static final String CEL_EVENT_CHAN_START = "CHAN_START"; + public static final String CEL_EVENT_CHAN_END = "CHAN_END"; + public static final String CEL_EVENT_ANSWER = "ANSWER"; + public static final String CEL_EVENT_HANGUP = "HANGUP"; + public static final String CEL_EVENT_BRIDGE_ENTER = "BRIDGE_ENTER"; + public static final String CEL_EVENT_BRIDGE_EXIT = "BRIDGE_EXIT"; + public static final String CEL_EVENT_APP_START = "APP_START"; + public static final String CEL_EVENT_APP_END = "APP_END"; + public static final String CEL_EVENT_PARK_START = "PARK_START"; + public static final String CEL_EVENT_PARK_END = "PARK_END"; + public static final String CEL_EVENT_BLINDTRANSFER = "BLINDTRANSFER"; + public static final String CEL_EVENT_ATTENDEDTRANSFER = "ATTENDEDTRANSFER"; + public static final String CEL_EVENT_PICKUP = "PICKUP"; + public static final String CEL_EVENT_FORWARD = "FORWARD"; + public static final String CEL_EVENT_LINKEDID_END = "LINKEDID_END"; + public static final String CEL_EVENT_LOCAL_OPTIMIZE = "LOCAL_OPTIMIZE"; + public static final String CEL_EVENT_LOCAL_OPTIMIZE_BEGIN = "LOCAL_OPTIMIZE_BEGIN"; + public static final String CEL_EVENT_USER_DEFINED = "USER_DEFINED"; + public static final String CEL_EVENT_STREAM_BEGIN = "STREAM_BEGIN"; + public static final String CEL_EVENT_STREAM_END = "STREAM_END"; + public static final String CEL_EVENT_DTMF = "DTMF"; + + private String eventName; + private String accountCode; + private String callerIDani; + private String callerIDrdnis; + private String callerIDdnid; + private String application; + private String appData; + private String eventTime; + private String amaFlags; + private String uniqueID; + private String linkedID; + private String userField; + private String peer; + private String peerAccount; + private String extra; + private String channel; + + public CelEvent(Object source) { + super(source); + } + + public String getEventName() { + return eventName; + } + + public void setEventName(String eventName) { + this.eventName = eventName; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getCallerIDani() { + return callerIDani; + } + + public void setCallerIDani(String callerIDani) { + this.callerIDani = callerIDani; + } + + public String getCallerIDrdnis() { + return callerIDrdnis; + } + + public void setCallerIDrdnis(String callerIDrdnis) { + this.callerIDrdnis = callerIDrdnis; + } + + public String getCallerIDdnid() { + return callerIDdnid; + } + + public void setCallerIDdnid(String callerIDdnid) { + this.callerIDdnid = callerIDdnid; + } + + public String getApplication() { + return application; + } + + public void setApplication(String application) { + this.application = application; + } + + public String getAppData() { + return appData; + } + + public void setAppData(String appData) { + this.appData = appData; + } + + public String getEventTime() { + return eventTime; + } + + public void setEventTime(String eventTime) { + this.eventTime = eventTime; + } + + public String getAmaFlags() { + return amaFlags; + } + + public void setAmaFlags(String amaFlags) { + this.amaFlags = amaFlags; + } + + public String getUniqueID() { + return uniqueID; + } + + public void setUniqueID(String uniqueID) { + this.uniqueID = uniqueID; + } + + public String getLinkedID() { + return linkedID; + } + + public void setLinkedID(String linkedID) { + this.linkedID = linkedID; + } + + public String getUserField() { + return userField; + } + + public void setUserField(String userField) { + this.userField = userField; + } + + public String getPeer() { + return peer; + } + + public void setPeer(String peer) { + this.peer = peer; + } + + public String getPeerAccount() { + return peerAccount; + } + + public void setPeerAccount(String peerAccount) { + this.peerAccount = peerAccount; + } + + public String getExtra() { + return extra; + } + + public void setExtra(String extra) { + this.extra = extra; + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ChallengeResponseFailedEvent.java b/src/main/java/org/asteriskjava/manager/event/ChallengeResponseFailedEvent.java new file mode 100644 index 000000000..877facde9 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ChallengeResponseFailedEvent.java @@ -0,0 +1,143 @@ +package org.asteriskjava.manager.event; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +public class ChallengeResponseFailedEvent extends ManagerEvent { + /** + * Serializable version identifier. + */ + private static final long serialVersionUID = -4630209124005390153L; + + private String severity; + private String eventversion; + private String service; + private String remoteaddress; + private String localaddress; + private String accountId; + private String module; + private String sessiontv; + private String sessionId; + private String challange; + private String response; + private String expectedResponse; + + /** + * @param source + */ + public ChallengeResponseFailedEvent(Object source) { + super(source); + } + + public String getSeverity() { + return severity; + } + + public void setSeverity(String severity) { + this.severity = severity; + } + + public String getEventversion() { + return eventversion; + } + + public void setEventversion(String eventversion) { + this.eventversion = eventversion; + } + + + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } + + public String getRemoteAddress() { + return remoteaddress; + } + + public void setRemoteAddress(String remoteaddress) { + this.remoteaddress = remoteaddress; + } + + public String getLocalAddress() { + return localaddress; + } + + public void setLocalAddress(String localaddress) { + this.localaddress = localaddress; + } + + public void setEventtv(String eventv) { + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH); + Long t = 0L; + try { + Date date = format.parse(eventv); + t = date.getTime(); + } catch (ParseException ex) { + } finally { + this.setTimestamp(t.doubleValue()); + } + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getModule() { + return module; + } + + public void setModule(String module) { + this.module = module; + } + + public String getSessiontv() { + return sessiontv; + } + + public void setSessiontv(String sessiontv) { + this.sessiontv = sessiontv; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getChallange() { + return challange; + } + + public void setChallange(String challange) { + this.challange = challange; + } + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } + + public String getExpectedResponse() { + return expectedResponse; + } + + public void setExpectedResponse(String expectedResponse) { + this.expectedResponse = expectedResponse; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ChallengeSentEvent.java b/src/main/java/org/asteriskjava/manager/event/ChallengeSentEvent.java new file mode 100644 index 000000000..a4e9256a8 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ChallengeSentEvent.java @@ -0,0 +1,114 @@ +package org.asteriskjava.manager.event; + +/** + * Created by plhk on 1/15/15. + */ +public class ChallengeSentEvent extends ManagerEvent { + /** + * + */ + private static final long serialVersionUID = 8219597230372769610L; + private String severity; + private Integer eventVersion; + private String accountId; + private String service; + private String eventtv; + private String remoteAddress; + private String localAddress; + private String challenge; + private String sessionId; + private String module; + private String sessiontv; + + public ChallengeSentEvent(Object source) { + super(source); + } + + public String getSeverity() { + return severity; + } + + public void setSeverity(String severity) { + this.severity = severity; + } + + public Integer getEventVersion() { + return eventVersion; + } + + public void setEventVersion(Integer eventVersion) { + this.eventVersion = eventVersion; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } + + public String getEventtv() { + return eventtv; + } + + public void setEventtv(String eventtv) { + this.eventtv = eventtv; + } + + public String getRemoteAddress() { + return remoteAddress; + } + + public void setRemoteAddress(String remoteAddress) { + this.remoteAddress = remoteAddress; + } + + public String getLocalAddress() { + return localAddress; + } + + public void setLocalAddress(String localAddress) { + this.localAddress = localAddress; + } + + public String getChallenge() { + return challenge; + } + + public void setChallenge(String challenge) { + this.challenge = challenge; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getModule() { + return module; + } + + public void setModule(String module) { + this.module = module; + } + + public String getSessiontv() { + return sessiontv; + } + + public void setSessiontv(String sessiontv) { + this.sessiontv = sessiontv; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ChanSpyStartEvent.java b/src/main/java/org/asteriskjava/manager/event/ChanSpyStartEvent.java new file mode 100644 index 000000000..bfe0bc7e8 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ChanSpyStartEvent.java @@ -0,0 +1,344 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + + +public class ChanSpyStartEvent extends ManagerEvent { + /** + * Serial version identifier + */ + private static final long serialVersionUID = 3256725065466000696L; + + private String spyeeChannel; + private String spyerChannel; + + private Integer spyeeChannelState; + private String spyeeLinkedId; + private String spyeeUniqueId; + private String spyeeCallerIdNum; + private String spyeeConnectedLineName; + private String spyeeLanguage; + private String spyeeContext; + private String spyeeConnectedLineNum; + private String spyeeChannelStateDesc; + private String spyeeExten; + private Integer spyeeChannelstate; + private String spyeeAccountCode; + private Integer spyeePriority; + private String spyeeCallerIdName; + + + private String spyerUniqueId; + private String spyerLinkedId; + private Integer spyerChannelState; + private Integer spyerPriority; + private String spyerContext; + private String spyerLanguage; + private String spyerChannelStateDesc; + private String spyerExten; + private String spyerCallerIdNum; + private String spyerConnectedLineNum; + private String spyerConnectedLineName; + private String spyerCallerIdName; + + + public ChanSpyStartEvent(Object source) { + super(source); + } + + + public String getSpyeeChannel() { + return spyeeChannel; + } + + + public void setSpyeeChannel(String spyeeChannel) { + this.spyeeChannel = spyeeChannel; + } + + + public String getSpyerChannel() { + return spyerChannel; + } + + + public void setSpyerChannel(String spyerChannel) { + this.spyerChannel = spyerChannel; + } + + + public Integer getSpyeeChannelState() { + return spyeeChannelState; + } + + + public void setSpyeeChannelState(Integer spyeeChannelState) { + this.spyeeChannelState = spyeeChannelState; + } + + + public String getSpyeeLinkedId() { + return spyeeLinkedId; + } + + + public void setSpyeeLinkedId(String spyeeLinkedId) { + this.spyeeLinkedId = spyeeLinkedId; + } + + + public String getSpyeeUniqueId() { + return spyeeUniqueId; + } + + + public void setSpyeeUniqueId(String spyeeUniqueId) { + this.spyeeUniqueId = spyeeUniqueId; + } + + + public String getSpyeeCallerIdNum() { + return spyeeCallerIdNum; + } + + + public void setSpyeeCallerIdNum(String spyeeCallerIdNum) { + this.spyeeCallerIdNum = spyeeCallerIdNum; + } + + + public String getSpyeeConnectedLineName() { + return spyeeConnectedLineName; + } + + + public void setSpyeeConnectedLineName(String spyeeConnectedLineName) { + this.spyeeConnectedLineName = spyeeConnectedLineName; + } + + + public String getSpyeeLanguage() { + return spyeeLanguage; + } + + + public void setSpyeeLanguage(String spyeeLanguage) { + this.spyeeLanguage = spyeeLanguage; + } + + + public String getSpyeeContext() { + return spyeeContext; + } + + + public void setSpyeeContext(String spyeeContext) { + this.spyeeContext = spyeeContext; + } + + + public String getSpyeeConnectedLineNum() { + return spyeeConnectedLineNum; + } + + + public void setSpyeeConnectedLineNum(String spyeeConnectedLineNum) { + this.spyeeConnectedLineNum = spyeeConnectedLineNum; + } + + + public String getSpyeeChannelStateDesc() { + return spyeeChannelStateDesc; + } + + + public void setSpyeeChannelStateDesc(String spyeeChannelStateDesc) { + this.spyeeChannelStateDesc = spyeeChannelStateDesc; + } + + + public String getSpyeeExten() { + return spyeeExten; + } + + + public void setSpyeeExten(String spyeeExten) { + this.spyeeExten = spyeeExten; + } + + + public Integer getSpyeeChannelstate() { + return spyeeChannelstate; + } + + + public void setSpyeeChannelstate(Integer spyeeChannelstate) { + this.spyeeChannelstate = spyeeChannelstate; + } + + + public String getSpyeeAccountCode() { + return spyeeAccountCode; + } + + + public void setSpyeeAccountCode(String spyeeAccountCode) { + this.spyeeAccountCode = spyeeAccountCode; + } + + + public Integer getSpyeePriority() { + return spyeePriority; + } + + + public void setSpyeePriority(Integer spyeePriority) { + this.spyeePriority = spyeePriority; + } + + + public String getSpyeeCallerIdName() { + return spyeeCallerIdName; + } + + + public void setSpyeeCallerIdName(String spyeeCallerIdName) { + this.spyeeCallerIdName = spyeeCallerIdName; + } + + + public String getSpyerUniqueId() { + return spyerUniqueId; + } + + + public void setSpyerUniqueId(String spyerUniqueId) { + this.spyerUniqueId = spyerUniqueId; + } + + + public String getSpyerLinkedId() { + return spyerLinkedId; + } + + + public void setSpyerLinkedId(String spyerLinkedId) { + this.spyerLinkedId = spyerLinkedId; + } + + + public Integer getSpyerChannelState() { + return spyerChannelState; + } + + + public void setSpyerChannelState(Integer spyerChannelState) { + this.spyerChannelState = spyerChannelState; + } + + + public Integer getSpyerPriority() { + return spyerPriority; + } + + + public void setSpyerPriority(Integer spyerPriority) { + this.spyerPriority = spyerPriority; + } + + + public String getSpyerContext() { + return spyerContext; + } + + + public void setSpyerContext(String spyerContext) { + this.spyerContext = spyerContext; + } + + + public String getSpyerLanguage() { + return spyerLanguage; + } + + + public void setSpyerLanguage(String spyerLanguage) { + this.spyerLanguage = spyerLanguage; + } + + + public String getSpyerChannelStateDesc() { + return spyerChannelStateDesc; + } + + + public void setSpyerChannelStateDesc(String spyerChannelStateDesc) { + this.spyerChannelStateDesc = spyerChannelStateDesc; + } + + + public String getSpyerExten() { + return spyerExten; + } + + + public void setSpyerExten(String spyerExten) { + this.spyerExten = spyerExten; + } + + + public String getSpyerCallerIdNum() { + return spyerCallerIdNum; + } + + + public void setSpyerCallerIdNum(String spyerCallerIdNum) { + this.spyerCallerIdNum = spyerCallerIdNum; + } + + + public String getSpyerConnectedLineNum() { + return spyerConnectedLineNum; + } + + + public void setSpyerConnectedLineNum(String spyerConnectedLineNum) { + this.spyerConnectedLineNum = spyerConnectedLineNum; + } + + + public String getSpyerConnectedLineName() { + return spyerConnectedLineName; + } + + + public void setSpyerConnectedLineName(String spyerConnectedLineName) { + this.spyerConnectedLineName = spyerConnectedLineName; + } + + + public String getSpyerCallerIdName() { + return spyerCallerIdName; + } + + + public void setSpyerCallerIdName(String spyerCallerIdName) { + this.spyerCallerIdName = spyerCallerIdName; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/ChanSpyStopEvent.java b/src/main/java/org/asteriskjava/manager/event/ChanSpyStopEvent.java new file mode 100644 index 000000000..872cb74d6 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ChanSpyStopEvent.java @@ -0,0 +1,278 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +public class ChanSpyStopEvent extends ManagerEvent { + private static final long serialVersionUID = 3256725065466000696L; + + private String spyerChannel; + private Integer spyerChannelState; + private String spyerChannelStateDesc; + private String spyerCallerIdNum; + private String spyerCallerIdName; + private String spyerConnectedLineNum; + private String spyerConnectedLineName; + private String spyerLanguage; + private String spyerAccountCode; + private String spyerContext; + private String spyerExten; + private Integer spyerPriority; + private String spyerUniqueId; + private String spyerLinkedId; + + private String spyeeChannel; + private Integer spyeeChannelState; + private String spyeeChannelStateDesc; + private String spyeeCallerIdNum; + private String spyeeCallerIdName; + private String spyeeConnectedLineNum; + private String spyeeConnectedLineName; + private String spyeeLanguage; + private String spyeeAccountCode; + private String spyeeContext; + private String spyeeExten; + private Integer spyeePriority; + private String spyeeUniqueId; + private String spyeeLinkedId; + + public ChanSpyStopEvent(Object source) { + super(source); + } + + public String getSpyerChannel() { + return spyerChannel; + } + + public void setSpyerChannel(String spyerChannel) { + this.spyerChannel = spyerChannel; + } + + public Integer getSpyerChannelState() { + return spyerChannelState; + } + + public void setSpyerChannelState(Integer spyerChannelState) { + this.spyerChannelState = spyerChannelState; + } + + public String getSpyerChannelStateDesc() { + return spyerChannelStateDesc; + } + + public void setSpyerChannelStateDesc(String spyerChannelStateDesc) { + this.spyerChannelStateDesc = spyerChannelStateDesc; + } + + public String getSpyerCallerIdNum() { + return spyerCallerIdNum; + } + + public void setSpyerCallerIdNum(String spyerCallerIdNum) { + this.spyerCallerIdNum = spyerCallerIdNum; + } + + public String getSpyerCallerIdName() { + return spyerCallerIdName; + } + + public void setSpyerCallerIdName(String spyerCallerIdName) { + this.spyerCallerIdName = spyerCallerIdName; + } + + public String getSpyerConnectedLineNum() { + return spyerConnectedLineNum; + } + + public void setSpyerConnectedLineNum(String spyerConnectedLineNum) { + this.spyerConnectedLineNum = spyerConnectedLineNum; + } + + public String getSpyerConnectedLineName() { + return spyerConnectedLineName; + } + + public void setSpyerConnectedLineName(String spyerConnectedLineName) { + this.spyerConnectedLineName = spyerConnectedLineName; + } + + public String getSpyerLanguage() { + return spyerLanguage; + } + + public void setSpyerLanguage(String spyerLanguage) { + this.spyerLanguage = spyerLanguage; + } + + public String getSpyerAccountCode() { + return spyerAccountCode; + } + + public void setSpyerAccountCode(String spyerAccountCode) { + this.spyerAccountCode = spyerAccountCode; + } + + public String getSpyerContext() { + return spyerContext; + } + + public void setSpyerContext(String spyerContext) { + this.spyerContext = spyerContext; + } + + public String getSpyerExten() { + return spyerExten; + } + + public void setSpyerExten(String spyerExten) { + this.spyerExten = spyerExten; + } + + public Integer getSpyerPriority() { + return spyerPriority; + } + + public void setSpyerPriority(Integer spyerPriority) { + this.spyerPriority = spyerPriority; + } + + public String getSpyerUniqueId() { + return spyerUniqueId; + } + + public void setSpyerUniqueId(String spyerUniqueId) { + this.spyerUniqueId = spyerUniqueId; + } + + public String getSpyerLinkedId() { + return spyerLinkedId; + } + + public void setSpyerLinkedId(String spyerLinkedId) { + this.spyerLinkedId = spyerLinkedId; + } + + public String getSpyeeChannel() { + return spyeeChannel; + } + + public void setSpyeeChannel(String spyeeChannel) { + this.spyeeChannel = spyeeChannel; + } + + public Integer getSpyeeChannelState() { + return spyeeChannelState; + } + + public void setSpyeeChannelState(Integer spyeeChannelState) { + this.spyeeChannelState = spyeeChannelState; + } + + public String getSpyeeChannelStateDesc() { + return spyeeChannelStateDesc; + } + + public void setSpyeeChannelStateDesc(String spyeeChannelStateDesc) { + this.spyeeChannelStateDesc = spyeeChannelStateDesc; + } + + public String getSpyeeCallerIdNum() { + return spyeeCallerIdNum; + } + + public void setSpyeeCallerIdNum(String spyeeCallerIdNum) { + this.spyeeCallerIdNum = spyeeCallerIdNum; + } + + public String getSpyeeCallerIdName() { + return spyeeCallerIdName; + } + + public void setSpyeeCallerIdName(String spyeeCallerIdName) { + this.spyeeCallerIdName = spyeeCallerIdName; + } + + public String getSpyeeConnectedLineNum() { + return spyeeConnectedLineNum; + } + + public void setSpyeeConnectedLineNum(String spyeeConnectedLineNum) { + this.spyeeConnectedLineNum = spyeeConnectedLineNum; + } + + public String getSpyeeConnectedLineName() { + return spyeeConnectedLineName; + } + + public void setSpyeeConnectedLineName(String spyeeConnectedLineName) { + this.spyeeConnectedLineName = spyeeConnectedLineName; + } + + public String getSpyeeLanguage() { + return spyeeLanguage; + } + + public void setSpyeeLanguage(String spyeeLanguage) { + this.spyeeLanguage = spyeeLanguage; + } + + public String getSpyeeAccountCode() { + return spyeeAccountCode; + } + + public void setSpyeeAccountCode(String spyeeAccountCode) { + this.spyeeAccountCode = spyeeAccountCode; + } + + public String getSpyeeContext() { + return spyeeContext; + } + + public void setSpyeeContext(String spyeeContext) { + this.spyeeContext = spyeeContext; + } + + public String getSpyeeExten() { + return spyeeExten; + } + + public void setSpyeeExten(String spyeeExten) { + this.spyeeExten = spyeeExten; + } + + public Integer getSpyeePriority() { + return spyeePriority; + } + + public void setSpyeePriority(Integer spyeePriority) { + this.spyeePriority = spyeePriority; + } + + public String getSpyeeUniqueId() { + return spyeeUniqueId; + } + + public void setSpyeeUniqueId(String spyeeUniqueId) { + this.spyeeUniqueId = spyeeUniqueId; + } + + public String getSpyeeLinkedId() { + return spyeeLinkedId; + } + + public void setSpyeeLinkedId(String spyeeLinkedId) { + this.spyeeLinkedId = spyeeLinkedId; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ChannelHungupEvent.java b/src/main/java/org/asteriskjava/manager/event/ChannelHungupEvent.java new file mode 100644 index 000000000..6992bfaa3 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ChannelHungupEvent.java @@ -0,0 +1,38 @@ +package org.asteriskjava.manager.event; + +public class ChannelHungupEvent extends ResponseEvent { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = -3439496042163782400L; + + private String channel; + + /** + * Constructs a ChannelHungupEvent + * + * @param source The object on which the Event initially occurred. + * @throws IllegalArgumentException if source is null. + */ + public ChannelHungupEvent(Object source) { + super(source); + } + + /** + * Get the name of the channel that was hung up. + * + * @return the name of the channel + */ + public String getChannel() { + return channel; + } + + /** + * Set the name of the channel that was hung up. + * + * @param channel the name of the channel + */ + public void setChannel(String channel) { + this.channel = channel; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ChannelReloadEvent.java b/src/main/java/org/asteriskjava/manager/event/ChannelReloadEvent.java index 01179fd87..d3a6b998e 100644 --- a/src/main/java/org/asteriskjava/manager/event/ChannelReloadEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ChannelReloadEvent.java @@ -22,20 +22,19 @@ /** * A ChannelReloadEvent is when a channel driver is reloaded, either on startup * or by request. - *

      + *
      * For example, channels/chan_sip.c triggers the channel reload * event when the SIP configuration is reloaded from sip.conf because the 'sip * reload' command was issued at the Manager interface, the CLI, or for another * reason. - *

      + *
      * Available since Asterisk 1.4. - *

      + *
      * It is implemented in channels/chan_sip.c * * @author martins */ -public class ChannelReloadEvent extends ManagerEvent -{ +public class ChannelReloadEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -102,8 +101,7 @@ public class ChannelReloadEvent extends ManagerEvent /** * @param source */ - public ChannelReloadEvent(Object source) - { + public ChannelReloadEvent(Object source) { super(source); } @@ -113,13 +111,11 @@ public ChannelReloadEvent(Object source) * @return the type of channel that was reloaded (e.g. SIP) * @since 1.0.0 */ - public String getChannelType() - { + public String getChannelType() { return channelType; } - public void setChannelType(String channelType) - { + public void setChannelType(String channelType) { this.channelType = channelType; } @@ -130,13 +126,12 @@ public void setChannelType(String channelType) * @return the type of channel that was reloaded (e.g. SIP) * @deprecated use {@link #getChannelType()} instead. */ - @Deprecated public String getChannel() - { + @Deprecated + public String getChannel() { return channelType; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channelType = channel; } @@ -145,10 +140,9 @@ public void setChannel(String channel) * channel (e.g. sip peer definitions). * * @return the number of peers defined during the configuration of this - * channel (e.g. sip peer definitions) + * channel (e.g. sip peer definitions) */ - public Integer getPeerCount() - { + public Integer getPeerCount() { return peerCount; } @@ -156,17 +150,15 @@ public Integer getPeerCount() * @param peerCount the number of peers defined during the configuration of * this channel (e.g. sip peer definitions) */ - public void setPeerCount(Integer peerCount) - { + public void setPeerCount(Integer peerCount) { this.peerCount = peerCount; } /** * @return the number of registrations with other channels (e.g. - * registrations with other sip proxies) + * registrations with other sip proxies) */ - public Integer getRegistryCount() - { + public Integer getRegistryCount() { return registryCount; } @@ -174,23 +166,21 @@ public Integer getRegistryCount() * @param registryCount the number of registrations with other channels * (e.g. registrations with other sip proxies) */ - public void setRegistryCount(Integer registryCount) - { + public void setRegistryCount(Integer registryCount) { this.registryCount = registryCount; } /** * Returns the reason that this channel was reloaded as received from Asterisk, for * example "CLIRELOAD (Channel module reload by CLI command)". - *

      + *
      * Usually you don't want to use this method directly. * * @return the reason for the reload as received from Asterisk. * @see #getReloadReasonCode() * @see #getReloadReasonDescription() */ - public String getReloadReason() - { + public String getReloadReason() { return reloadReason; } @@ -200,19 +190,16 @@ public String getReloadReason() * * @param reloadReason the reason that this channel was reloaded */ - public void setReloadReason(String reloadReason) - { + public void setReloadReason(String reloadReason) { Matcher matcher; this.reloadReason = reloadReason; - if (reloadReason == null) - { + if (reloadReason == null) { return; } matcher = REASON_PATTERN.matcher(reloadReason); - if (matcher.matches()) - { + if (matcher.matches()) { reloadReasonCode = matcher.group(1); reloadReasonDescription = matcher.group(2); } @@ -234,8 +221,7 @@ public void setReloadReason(String reloadReason) * @see org.asteriskjava.manager.event.ChannelReloadEvent#REASON_RELOAD * @see org.asteriskjava.manager.event.ChannelReloadEvent#REASON_MANAGER_RELOAD */ - public String getReloadReasonCode() - { + public String getReloadReasonCode() { return reloadReasonCode; } @@ -245,17 +231,15 @@ public String getReloadReasonCode() * * @return the descriptive version of the reason for the reload. */ - public String getReloadReasonDescription() - { + public String getReloadReasonDescription() { return reloadReasonDescription; } /** * @return the number of users defined during the configuration of this - * channel (e.g. sip user definitions) + * channel (e.g. sip user definitions) */ - public Integer getUserCount() - { + public Integer getUserCount() { return userCount; } @@ -263,8 +247,7 @@ public Integer getUserCount() * @param userCount the number of users defined during the configuration of * this channel (e.g. sip user definitions) */ - public void setUserCount(Integer userCount) - { + public void setUserCount(Integer userCount) { this.userCount = userCount; } } diff --git a/src/main/java/org/asteriskjava/manager/event/ChannelTalkingStartEvent.java b/src/main/java/org/asteriskjava/manager/event/ChannelTalkingStartEvent.java new file mode 100644 index 000000000..e305d69f3 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ChannelTalkingStartEvent.java @@ -0,0 +1,22 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +public class ChannelTalkingStartEvent extends AbstractChannelTalkingEvent { + public ChannelTalkingStartEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ChannelTalkingStopEvent.java b/src/main/java/org/asteriskjava/manager/event/ChannelTalkingStopEvent.java new file mode 100644 index 000000000..6e0968e5d --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ChannelTalkingStopEvent.java @@ -0,0 +1,32 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +public class ChannelTalkingStopEvent extends AbstractChannelTalkingEvent { + private Long duration; + + public ChannelTalkingStopEvent(Object source) { + super(source); + } + + public Long getDuration() { + return duration; + } + + public void setDuration(Long duration) { + this.duration = duration; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ChannelUpdateEvent.java b/src/main/java/org/asteriskjava/manager/event/ChannelUpdateEvent.java index 15d250d74..1b8b78184 100644 --- a/src/main/java/org/asteriskjava/manager/event/ChannelUpdateEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ChannelUpdateEvent.java @@ -27,8 +27,7 @@ * @version $Id$ * @since 1.0.0 */ -public class ChannelUpdateEvent extends ManagerEvent -{ +public class ChannelUpdateEvent extends ManagerEvent { private static final long serialVersionUID = 3141630567125429466L; private String channelType; private String channel; @@ -47,12 +46,11 @@ public class ChannelUpdateEvent extends ManagerEvent /** * @param source */ - public ChannelUpdateEvent(Object source) - { + public ChannelUpdateEvent(Object source) { super(source); } - + /** * Returns the type of channel, that is "IAX2" for an IAX2 * channel or "SIP" for a SIP channel.
      @@ -60,13 +58,11 @@ public ChannelUpdateEvent(Object source) * * @return the type of channel that is registered. */ - public String getChannelType() - { + public String getChannelType() { return channelType; } - public void setChannelType(String channelType) - { + public void setChannelType(String channelType) { this.channelType = channelType; } @@ -75,13 +71,11 @@ public void setChannelType(String channelType) * * @return the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -90,83 +84,67 @@ public void setChannel(String channel) * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } - public String getSipCallId() - { + public String getSipCallId() { return sipCallId; } - public void setSipCallId(String sipCallId) - { + public void setSipCallId(String sipCallId) { this.sipCallId = sipCallId; } - public String getSipFullContact() - { + public String getSipFullContact() { return sipFullContact; } - public void setSipFullContact(String sipFullContact) - { + public void setSipFullContact(String sipFullContact) { this.sipFullContact = sipFullContact; } - public String getPeerName() - { + public String getPeerName() { return peerName; } - public void setPeerName(String peerName) - { + public void setPeerName(String peerName) { this.peerName = peerName; } - public String getGtalkSid() - { + public String getGtalkSid() { return gtalkSid; } - public void setGtalkSid(String gtalkSid) - { + public void setGtalkSid(String gtalkSid) { this.gtalkSid = gtalkSid; } - public String getIax2CallNoLocal() - { + public String getIax2CallNoLocal() { return iax2CallNoLocal; } - public void setIax2CallNoLocal(String iax2CallNoLocal) - { + public void setIax2CallNoLocal(String iax2CallNoLocal) { this.iax2CallNoLocal = iax2CallNoLocal; } - public String getIax2CallNoRemote() - { + public String getIax2CallNoRemote() { return iax2CallNoRemote; } - public void setIax2CallNoRemote(String iax2CallNoRemote) - { + public void setIax2CallNoRemote(String iax2CallNoRemote) { this.iax2CallNoRemote = iax2CallNoRemote; } - public String getIax2Peer() - { + public String getIax2Peer() { return iax2Peer; } - public void setIax2Peer(String iax2Peer) - { + public void setIax2Peer(String iax2Peer) { this.iax2Peer = iax2Peer; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/ChannelsHungupListComplete.java b/src/main/java/org/asteriskjava/manager/event/ChannelsHungupListComplete.java new file mode 100644 index 000000000..b5b42ad6d --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ChannelsHungupListComplete.java @@ -0,0 +1,41 @@ +package org.asteriskjava.manager.event; + +public class ChannelsHungupListComplete extends ResponseEvent { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = 2531650218749540207L; + private Integer listItems; + + /** + * Constructs a ChannelsHungupListComplete + * + * @param source The object on which the Event initially occurred. + * @throws IllegalArgumentException if source is null. + */ + public ChannelsHungupListComplete(Object source) { + super(source); + } + + /** + * Returns the number of ChannelHungup that have been reported. + * + * @return the number of ChannelHungup that have been reported. + */ + public Integer getListItems() { + return listItems; + } + + /** + * Sets the number of ChannelHungup that have been reported. + * + * @param listItems the number of ChannelHungup that have been reported. + */ + public void setListItems(Integer listItems) { + this.listItems = listItems; + } + + public void setEventList(String eventList) { + // This exists just to silence a warning, the value is always 'Complete' + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeEndEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeEndEvent.java index 5b74dc9f2..e5d0edd6c 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeEndEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeEndEvent.java @@ -1,40 +1,20 @@ package org.asteriskjava.manager.event; /** - * This event is sent when the last user leaves a conference and it is torn down. + * This event is sent when the last user leaves a conference and it is torn + * down. * * @since 1.0.0 */ -public class ConfbridgeEndEvent extends ManagerEvent { +public class ConfbridgeEndEvent extends AbstractConfbridgeEvent { - /** + /** * Serializable version identifier */ - private static final long serialVersionUID = -8973512592594074108L; - private String conference; - - public ConfbridgeEndEvent(Object source) { - super(source); - } - - /** - * Sets the id of the conference ended. - * - * @param conference the id of the conference ended. - */ - public void setConference(String conference) - { - this.conference = conference; - } + private static final long serialVersionUID = -8973512592594074108L; - /** - * Returns the id of the conference ended. - * - * @return the id of the conference ended. - */ - public String getConference() - { - return conference; + public ConfbridgeEndEvent(Object source) { + super(source); } } diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeJoinEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeJoinEvent.java index 41f1c3cb6..228283784 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeJoinEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeJoinEvent.java @@ -1,41 +1,29 @@ package org.asteriskjava.manager.event; /** - * This event is sent when a user joins a conference - either one already in progress or as the first user to - * join a newly instantiated bridge. + * This event is sent when a user joins a conference - either one already in + * progress or as the first user to join a newly instantiated bridge. * * @since 1.0.0 */ -public class ConfbridgeJoinEvent extends AbstractChannelEvent -{ +public class ConfbridgeJoinEvent extends AbstractConfbridgeEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 1L; - private String conference; - public ConfbridgeJoinEvent(Object source) - { + String muted; + + public ConfbridgeJoinEvent(Object source) { super(source); } - /** - * Sets the id of the conference the participant joined. - * - * @param conference id of the conference the participant joined. - */ - public void setConference(String conference) - { - this.conference = conference; + public String getMuted() { + return muted; } - /** - * Returns the id of the conference the participant joined. - * - * @return id of the conference the participant joined. - */ - public String getConference() - { - return conference; + public void setMuted(String muted) { + this.muted = muted; } + } diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeLeaveEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeLeaveEvent.java index 0a1629656..7abbe5460 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeLeaveEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeLeaveEvent.java @@ -5,36 +5,14 @@ * * @since 1.0.0 */ -public class ConfbridgeLeaveEvent extends AbstractChannelEvent -{ +public class ConfbridgeLeaveEvent extends AbstractConfbridgeEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 1L; - private String conference; - public ConfbridgeLeaveEvent(Object source) - { + public ConfbridgeLeaveEvent(Object source) { super(source); } - /** - * Sets the id of the conference the participant left. - * - * @param conference the id of the conference the participant left. - */ - public void setConference(String conference) - { - this.conference = conference; - } - - /** - * Returns the id of the conference the participant left. - * - * @return the id of the conference the participant left. - */ - public String getConference() - { - return conference; - } } diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeListCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeListCompleteEvent.java index e446f617b..82f4ea5a7 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeListCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeListCompleteEvent.java @@ -1,7 +1,6 @@ package org.asteriskjava.manager.event; -public class ConfbridgeListCompleteEvent extends ResponseEvent -{ +public class ConfbridgeListCompleteEvent extends ResponseEvent { /** * Serializable version identifier */ @@ -13,40 +12,35 @@ public class ConfbridgeListCompleteEvent extends ResponseEvent /** * @param source */ - public ConfbridgeListCompleteEvent(Object source) - { + public ConfbridgeListCompleteEvent(Object source) { super(source); } /** * Sets the status of the list e.g. complete. */ - public void setEventList(String eventList) - { + public void setEventList(String eventList) { this.eventList = eventList; } /** * Returns the status of the list e.g. complete. */ - public String getEventList() - { + public String getEventList() { return eventList; } /** * Sets the number listitems. */ - public void setListItems(String listItems) - { + public void setListItems(String listItems) { this.listItems = listItems; } /** * Returns the number listitems. */ - public String getListItems() - { + public String getListItems() { return listItems; } } diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeListEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeListEvent.java index 64a0928bd..dc76b41fe 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeListEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeListEvent.java @@ -6,22 +6,28 @@ * @see org.asteriskjava.manager.action.ConfbridgeListAction * @since 1.0.0 */ -public class ConfbridgeListEvent extends ResponseEvent -{ +public class ConfbridgeListEvent extends ResponseEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 1L; private String conference; - private String callerIDnum; - private String callerIdName; private Boolean admin; private Boolean markedUser; private String channel; + private String linkedid; + private String waiting; + private String language; + private String talking; + private String muted; + private String uniqueid; + private int answeredtime; + private String waitmarked; + private String endmarked; + private String accountcode; - public ConfbridgeListEvent(Object source) - { + public ConfbridgeListEvent(Object source) { super(source); } @@ -30,8 +36,7 @@ public ConfbridgeListEvent(Object source) * * @param conference the id of the conference to be listed. */ - public void setConference(String conference) - { + public void setConference(String conference) { this.conference = conference; } @@ -40,94 +45,131 @@ public void setConference(String conference) * * @return the id of the conference to be listed. */ - public String getConference() - { + public String getConference() { return conference; } /** - * Sets the Caller*ID Number of the channel in the list of the conference. + * Sets the role of the caller in the list admin = yes or no of the + * conference. * - * @param callerIDnum the Caller*ID Number of the channel in the list of the conference. + * @param admin = yes or no the role of the caller in the list of the + * conference. */ - public void setCallerIDnum(String callerIDnum) - { - this.callerIDnum = callerIDnum; - } - - /** - * Returns the Caller*ID Number of the channel in the list of the conference. - * - * @return the Caller*ID Number of the channel in the list of the conference. - */ - public String getCallerIDnum() - { - return callerIDnum; - } - - /** - * Sets the Caller*ID Name of the channel in the list of the conference. - * - * @param callerIdName the Caller*ID Name of the channel in the list of the conference. - */ - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; - } - - /** - * Returns the Caller*ID Name of the channel in the list of the conference. - * - * @return the Caller*ID Name of the channel in the list of the conference. - */ - public String getCallerIdName() - { - return callerIdName; - } - - /** - * Sets the role of the caller in the list admin = yes or no of the conference. - * - * @param admin = yes or no the role of the caller in the list of the conference. - */ - public void setAdmin(Boolean admin) - { + public void setAdmin(Boolean admin) { this.admin = admin; } /** - * Returns the role of the caller in the list admin = yes or no of the conference. + * Returns the role of the caller in the list admin = yes or no of the + * conference. * - * @return the role of the caller in the list admin = yes or no of the conference. + * @return the role of the caller in the list admin = yes or no of the + * conference. */ - public Boolean getAdmin() - { + public Boolean getAdmin() { return admin; } - public void setMarkedUser(Boolean markedUser) - { + public void setMarkedUser(Boolean markedUser) { this.markedUser = markedUser; } - public Boolean getMarkedUser() - { + public Boolean getMarkedUser() { return markedUser; } /** * Sets the name of the channel in the list. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the name of the channel in the list. */ - public String getChannel() - { + public String getChannel() { return channel; } + + public String getLinkedid() { + return linkedid; + } + + public void setLinkedid(String linkedid) { + this.linkedid = linkedid; + } + + public String getWaiting() { + return waiting; + } + + public void setWaiting(String waiting) { + this.waiting = waiting; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getTalking() { + return talking; + } + + public void setTalking(String talking) { + this.talking = talking; + } + + public String getMuted() { + return muted; + } + + public void setMuted(String muted) { + this.muted = muted; + } + + public String getUniqueid() { + return uniqueid; + } + + public void setUniqueid(String uniqueid) { + this.uniqueid = uniqueid; + } + + public int getAnsweredtime() { + return answeredtime; + } + + public void setAnsweredtime(int answeredtime) { + this.answeredtime = answeredtime; + } + + public String getWaitmarked() { + return waitmarked; + } + + public void setWaitmarked(String waitmarked) { + this.waitmarked = waitmarked; + } + + public String getEndmarked() { + return endmarked; + } + + public void setEndmarked(String endmarked) { + this.endmarked = endmarked; + } + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeListRoomsCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeListRoomsCompleteEvent.java index 62c863a8d..2b7a24c6e 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeListRoomsCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeListRoomsCompleteEvent.java @@ -1,7 +1,6 @@ package org.asteriskjava.manager.event; -public class ConfbridgeListRoomsCompleteEvent extends ResponseEvent -{ +public class ConfbridgeListRoomsCompleteEvent extends ResponseEvent { /** * Serializable version identifier */ @@ -10,24 +9,21 @@ public class ConfbridgeListRoomsCompleteEvent extends ResponseEvent private String eventList; private String listItems; - public ConfbridgeListRoomsCompleteEvent(Object source) - { + public ConfbridgeListRoomsCompleteEvent(Object source) { super(source); } /** * Sets the status of the list that is always "Complete". */ - public void setEventList(String eventList) - { + public void setEventList(String eventList) { this.eventList = eventList; } /** * Returns the status of the list that is always "Complete". */ - public String getEventList() - { + public String getEventList() { return eventList; } @@ -36,8 +32,7 @@ public String getEventList() * * @param listItems the number items returned. */ - public void setListItems(String listItems) - { + public void setListItems(String listItems) { this.listItems = listItems; } @@ -46,8 +41,7 @@ public void setListItems(String listItems) * * @return the number items returned. */ - public String getListItems() - { + public String getListItems() { return listItems; } } diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeListRoomsEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeListRoomsEvent.java index 342ab684a..22a91649e 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeListRoomsEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeListRoomsEvent.java @@ -1,7 +1,6 @@ package org.asteriskjava.manager.event; -public class ConfbridgeListRoomsEvent extends ResponseEvent -{ +public class ConfbridgeListRoomsEvent extends ResponseEvent { /** * Serializable version identifier */ @@ -11,25 +10,23 @@ public class ConfbridgeListRoomsEvent extends ResponseEvent private Integer parties; private Integer marked; private Boolean locked; + private String muted; - public ConfbridgeListRoomsEvent(Object source) - { + public ConfbridgeListRoomsEvent(Object source) { super(source); } /** * Sets the id of the conference to be listed. */ - public void setConference(String conference) - { + public void setConference(String conference) { this.conference = conference; } /** * Returns the id of the conference to be listed. */ - public String getConference() - { + public String getConference() { return conference; } @@ -38,8 +35,7 @@ public String getConference() * * @param parties the number of participants in this conference. */ - public void setParties(Integer parties) - { + public void setParties(Integer parties) { this.parties = parties; } @@ -48,8 +44,7 @@ public void setParties(Integer parties) * * @return the number of participants in this conference. */ - public Integer getParties() - { + public Integer getParties() { return parties; } @@ -58,8 +53,7 @@ public Integer getParties() * * @param marked the number of marked participants in this conference. */ - public void setMarked(Integer marked) - { + public void setMarked(Integer marked) { this.marked = marked; } @@ -68,18 +62,23 @@ public void setMarked(Integer marked) * * @return the number of marked participants in this conference. */ - public Integer getMarked() - { + public Integer getMarked() { return marked; } - public void setLocked(Boolean locked) - { + public void setLocked(Boolean locked) { this.locked = locked; } - public Boolean getLocked() - { + public Boolean getLocked() { return locked; } + + public String getMuted() { + return muted; + } + + public void setMuted(String muted) { + this.muted = muted; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeStartEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeStartEvent.java index 6d7aae433..1368f0915 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeStartEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeStartEvent.java @@ -1,41 +1,22 @@ package org.asteriskjava.manager.event; /** - * This event is sent when the first user requests a conference and it is instantiated. + * This event is sent when the first user requests a conference and it is + * instantiated. * * @since 1.0.0 */ -public class ConfbridgeStartEvent extends ManagerEvent -{ +public class ConfbridgeStartEvent extends AbstractConfbridgeEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 1L; + @SuppressWarnings("unused") private String conference; - public ConfbridgeStartEvent(Object source) - { + public ConfbridgeStartEvent(Object source) { super(source); } - /** - * Sets the id of the conference started. - * - * @param conference the id of the conference started. - */ - public void setConference(String conference) - { - this.conference = conference; - } - - /** - * Returns the id of the conference started. - * - * @return the id of the conference started. - */ - public String getConference() - { - return conference; - } } diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeTalkingEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeTalkingEvent.java index 96b63871b..960ad1ed2 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeTalkingEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeTalkingEvent.java @@ -1,104 +1,40 @@ package org.asteriskjava.manager.event; /** - * This event is sent when the conference detects that a user has either begin or stopped talking. + * This event is sent when the conference detects that a user has either begin + * or stopped talking. * * @since 1.0.0 */ -public class ConfbridgeTalkingEvent extends ManagerEvent -{ +public class ConfbridgeTalkingEvent extends AbstractConfbridgeEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 1L; - private String conference; - private String channel; - private String uniqueId; private Boolean talkingStatus; - public ConfbridgeTalkingEvent(Object source) - { + public ConfbridgeTalkingEvent(Object source) { super(source); } - /** - * Sets the id of the conference. - * - * @param conference the id of the conference. - */ - public void setConference(String conference) - { - this.conference = conference; - } - - /** - * Returns the id of the conference. - * - * @return the id of the conference. - */ - public String getConference() - { - return conference; - } - - /** - * Sets the name of the channel on which a participant started or stopped talking. - * - * @param channel the name of the channel on which a participant started or stopped talking. - */ - public void setChannel(String channel) - { - this.channel = channel; - } - - /** - * Returns the name of the channel on which a participant started or stopped talking. - * - * @return the name of the channel on which a participant started or stopped talking. - */ - public String getChannel() - { - return channel; - } - - /** - * Returns the unique id of the channel on which a participant started or stopped talking. - * - * @return the unique id of the channel on which a participant started or stopped talking. - */ - public String getUniqueId() - { - return uniqueId; - } - - /** - * Sets the unique id of the channel on which a participant started or stopped talking. - * - * @param uniqueId the unique id of the channel on which a participant started or stopped talking. - */ - public void setUniqueId(String uniqueId) - { - this.uniqueId = uniqueId; - } - /** * Sets the talking status on or off. * * @param talkingStatus the talking status */ - public void setTalkingStatus(Boolean talkingStatus) - { + public void setTalkingStatus(Boolean talkingStatus) { this.talkingStatus = talkingStatus; } /** * Returns the talking status. * - * @return true if the participant started talking, false if the participant stopped talking. + * @return true if the participant started talking, + * false if the participant stopped talking. */ - public Boolean getTalkingStatus() - { + public Boolean getTalkingStatus() { return talkingStatus; } + } diff --git a/src/main/java/org/asteriskjava/manager/event/ConnectEvent.java b/src/main/java/org/asteriskjava/manager/event/ConnectEvent.java index a1cbd0593..20a3589a6 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConnectEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConnectEvent.java @@ -19,13 +19,12 @@ /** * A ConnectEvent is triggered after successful login to the Asterisk server.

      * It is a pseudo event not directly related to an Asterisk generated event. - * + * * @author srt * @version $Id$ * @see org.asteriskjava.manager.event.DisconnectEvent */ -public class ConnectEvent extends ManagerEvent -{ +public class ConnectEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -39,13 +38,11 @@ public class ConnectEvent extends ManagerEvent /** * @param source */ - public ConnectEvent(Object source) - { + public ConnectEvent(Object source) { super(source); } - - public ConnectEvent(Object source, String protocolIdentifier) - { + + public ConnectEvent(Object source, String protocolIdentifier) { this(source); this.protocolIdentifier = protocolIdentifier; } @@ -53,21 +50,19 @@ public ConnectEvent(Object source, String protocolIdentifier) /** * Returns the version of the protocol. For example "Asterisk Call Manager/1.0" for Asterisk up to 1.4 and * "Asterisk Call Manager/1.1" for Asterisk 1.6. - * + * * @return the version of the protocol. */ - public String getProtocolIdentifier() - { + public String getProtocolIdentifier() { return protocolIdentifier; } /** * Sets the version of the protocol. - * + * * @param protocolIdentifier the version of the protocol. */ - public void setProtocolIdentifier(String protocolIdentifier) - { + public void setProtocolIdentifier(String protocolIdentifier) { this.protocolIdentifier = protocolIdentifier; } } diff --git a/src/main/java/org/asteriskjava/manager/event/ContactList.java b/src/main/java/org/asteriskjava/manager/event/ContactList.java new file mode 100644 index 000000000..a83958265 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ContactList.java @@ -0,0 +1,235 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A ContactListCompleteEvent is triggered after the details of all peers has + * been reported in response to an PJSipShowContactsAction. + *

      + * Available since Asterisk 16? + * + * @author srt + * @version $Id$ + * @since 3.0 + */ +public class ContactList extends ResponseEvent { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = -1177773673509373296L; + + Double qualifyTimeout; + String callid; + String regserver; + + // roundtripusec when it contains a value is a long, but when it doesn't + // asterisk reports "N/A" + String roundtripusec; + Long expirationtime; + String authenticatequalify; + String objectname; + String useragent; + String uri; + String viaaddr; + Long qualifyfrequency; + String path; + String endpoint; + String viaport; + String outboundproxy; + + String objecttype; + String pruneonboot; + ContactStatusEnum status; + Boolean qualify2xxOnly; + + /** + * Creates a new instance. + * + * @param source + */ + public ContactList(Object source) { + super(source); + } + + public double getQualifyTimeout() { + return qualifyTimeout; + } + + public void setQualifyTimeout(double qualifyTimeout) { + this.qualifyTimeout = qualifyTimeout; + } + + public String getCallid() { + return callid; + } + + public void setCallid(String callid) { + this.callid = callid; + } + + public String getRegserver() { + return regserver; + } + + public void setRegserver(String regserver) { + this.regserver = regserver; + } + + public String getRoundtripusec() { + return roundtripusec; + } + + public void setRoundtripusec(String roundtripusec) { + this.roundtripusec = roundtripusec; + } + + public long getExpirationtime() { + return expirationtime; + } + + public void setExpirationtime(long expirationtime) { + this.expirationtime = expirationtime; + } + + public String getAuthenticatequalify() { + return authenticatequalify; + } + + public void setAuthenticatequalify(String authenticatequalify) { + this.authenticatequalify = authenticatequalify; + } + + public String getObjectname() { + return objectname; + } + + public void setObjectname(String objectname) { + this.objectname = objectname; + } + + public String getUseragent() { + return useragent; + } + + public void setUseragent(String useragent) { + this.useragent = useragent; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public String getViaaddr() { + return viaaddr; + } + + public void setViaaddr(String viaaddr) { + this.viaaddr = viaaddr; + } + + public long getQualifyfrequency() { + return qualifyfrequency; + } + + public void setQualifyfrequency(Long qualifyfrequency) { + this.qualifyfrequency = qualifyfrequency; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getEndpoint() { + return endpoint; + } + + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } + + public String getViaport() { + return viaport; + } + + public void setViaport(String viaport) { + this.viaport = viaport; + } + + public String getOutboundproxy() { + return outboundproxy; + } + + public void setOutboundproxy(String outboundproxy) { + this.outboundproxy = outboundproxy; + } + + public String getObjecttype() { + return objecttype; + } + + public void setObjecttype(String objecttype) { + this.objecttype = objecttype; + } + + public String getPruneonboot() { + return pruneonboot; + } + + public void setPruneonboot(String pruneonboot) { + this.pruneonboot = pruneonboot; + } + + public ContactStatusEnum getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = ContactStatusEnum.UNKNOWN; + + if (status != null && status.length() > 0) { + this.status = ContactStatusEnum.valueOf(status.toUpperCase()); + } + + } + + public Boolean isQualify2xxOnly() { + return qualify2xxOnly; + } + + public void setQualify2xxOnly(Boolean qualify2xxOnly) { + this.qualify2xxOnly = qualify2xxOnly; + } + + @Override + public String toString() { + return "ContactList [qualifyTimeout=" + qualifyTimeout + ", callid=" + callid + ", regserver=" + regserver + + ", roundtripusec=" + roundtripusec + ", expirationtime=" + expirationtime + ", authenticatequalify=" + + authenticatequalify + ", objectname=" + objectname + ", useragent=" + useragent + ", uri=" + uri + + ", viaaddr=" + viaaddr + ", qualifyfrequency=" + qualifyfrequency + ", path=" + path + ", endpoint=" + + endpoint + ", viaport=" + viaport + ", outboundproxy=" + outboundproxy + ", actionId=" + actionId + + ", objecttype=" + objecttype + ", pruneonboot=" + pruneonboot + ", status=" + status + ", qualify2xxOnly=" + qualify2xxOnly + "]\n"; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/ContactListComplete.java b/src/main/java/org/asteriskjava/manager/event/ContactListComplete.java new file mode 100644 index 000000000..13fb427fd --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ContactListComplete.java @@ -0,0 +1,83 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A PeerlistCompleteEvent is triggered after the details of all peers has been + * reported in response to an SIPPeersAction or SIPShowPeerAction. + *

      + * Available since Asterisk 1.2 + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.event.PeerEntryEvent + * @see org.asteriskjava.manager.action.SipPeersAction + * @see org.asteriskjava.manager.action.SipShowPeerAction + * @since 0.2 + */ +public class ContactListComplete extends ResponseEvent { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = -1177773673509373296L; + private Integer listItems; + private String eventList; + + /** + * Creates a new instance. + * + * @param source + */ + public ContactListComplete(Object source) { + super(source); + } + + /** + * Returns the number of PeerEvents that have been reported. + * + * @return the number of PeerEvents that have been reported. + */ + public Integer getListItems() { + return listItems; + } + + /** + * Sets the number of PeerEvents that have been reported. + * + * @param listItems the number of PeerEvents that have been reported. + */ + public void setListItems(Integer listItems) { + this.listItems = listItems; + } + + /** + * Returns always "Complete". + *

      + * Available since Asterisk 1.6. + * + * @return always returns "Complete" confirming that all PeerEntry events + * have been sent. + * @since 1.0.0 + */ + public String getEventList() { + return eventList; + } + + public void setEventList(String eventList) { + this.eventList = eventList; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ContactStatusDetail.java b/src/main/java/org/asteriskjava/manager/event/ContactStatusDetail.java new file mode 100644 index 000000000..08fca1cd1 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ContactStatusDetail.java @@ -0,0 +1,175 @@ +package org.asteriskjava.manager.event; + +/** + * A ContactStatusDetail event is triggered in response to a + * {@link org.asteriskjava.manager.action.PJSipShowEndpoint}, and contains + * information about a PJSIP Contact + *

      + * + * @author Steve Sether + * @version $Id$ + * @since 12 + */ + +public class ContactStatusDetail extends ResponseEvent { + + /** + * Serial version identifier. + */ + private static final long serialVersionUID = 987290433601178780L; + private String aor; + private String uri; + private String userAgent; + private long regExpire; + private String viaAddress; + private String callID; + private String status; + // roundtripusec when it contains a value is a long, but when it doesn't + // asterisk reports "N/A" + private String roundtripUsec; + private String endpointName; + private String id; + private Boolean authenticateQualify; + private String outboundProxy; + private String path; + private int qualifyFrequency; + private Float qualifyTimeout; + private Boolean qualify2xxOnly; + + public String getAor() { + return aor; + } + + public void setAor(String aor) { + this.aor = aor; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getUri() { + return uri; + } + + public void setUri(String uri) { + this.uri = uri; + } + + public String getUserAgent() { + return userAgent; + } + + public void setUserAgent(String userAgent) { + this.userAgent = userAgent; + } + + public long getRegExpire() { + return regExpire; + } + + public void setRegExpire(long regExpire) { + this.regExpire = regExpire; + } + + public String getViaAddress() { + return viaAddress; + } + + public void setViaAddress(String viaAddress) { + this.viaAddress = viaAddress; + } + + public String getCallID() { + return callID; + } + + public void setCallID(String callID) { + this.callID = callID; + } + + public String getEndpointName() { + return endpointName; + } + + public void setEndpointName(String endpointName) { + this.endpointName = endpointName; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Boolean isAuthenticateQualify() { + return authenticateQualify; + } + + public void setAuthenticateQualify(Boolean authenticateQualify) { + this.authenticateQualify = authenticateQualify; + } + + public String getOutboundProxy() { + return outboundProxy; + } + + public void setOutboundProxy(String outboundProxy) { + this.outboundProxy = outboundProxy; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public int getQualifyFrequency() { + return qualifyFrequency; + } + + public void setQualifyFrequency(int qualifyFrequency) { + this.qualifyFrequency = qualifyFrequency; + } + + public Float getQualifyTimeout() { + return qualifyTimeout; + } + + public void setQualifyTimeout(Float qualifyTimeout) { + this.qualifyTimeout = qualifyTimeout; + } + + public void setQualifyTimeout(String qualifyTimeout) { + this.qualifyTimeout = Float.parseFloat(qualifyTimeout); + } + + public Boolean isQualify2xxOnly() { + return qualify2xxOnly; + } + + public void setQualify2xxOnly(Boolean qualify2xxOnly) { + this.qualify2xxOnly = qualify2xxOnly; + } + + public ContactStatusDetail(Object source) { + super(source); + } + + public String getRoundtripUsec() { + return roundtripUsec; + } + + public void setRoundtripUsec(String roundtripUsec) { + this.roundtripUsec = roundtripUsec; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/ContactStatusEnum.java b/src/main/java/org/asteriskjava/manager/event/ContactStatusEnum.java new file mode 100644 index 000000000..84443bceb --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ContactStatusEnum.java @@ -0,0 +1,6 @@ +package org.asteriskjava.manager.event; + +public enum ContactStatusEnum { + REACHABLE, UNREACHABLE, NONQUALIFIED, UNKNOWN + +} diff --git a/src/main/java/org/asteriskjava/manager/event/ContactStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/ContactStatusEvent.java new file mode 100644 index 000000000..eb0b9e463 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ContactStatusEvent.java @@ -0,0 +1,119 @@ +/* + * Copyright 2018 Sean Bright + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * Raised when the state of a contact changes. + *

      + * Available since Asterisk 13 + */ +public class ContactStatusEvent extends ManagerEvent { + private static final long serialVersionUID = 0L; + + public static final String STATUS_CREATED = "Created"; + public static final String STATUS_REACHABLE = "Reachable"; + public static final String STATUS_REMOVED = "Removed"; + public static final String STATUS_UNKNOWN = "Unknown"; + public static final String STATUS_UNREACHABLE = "Unreachable"; + public static final String STATUS_UPDATED = "Updated"; + + private String uri; + private String contactStatus; + private String aor; + private String endpointName; + private String roundtripUsec; + private String userAgent; + private String regExpire; + private String viaAddress; + private String callID; + + public ContactStatusEvent(Object source) { + super(source); + } + + public String getUri() { + return uri; + } + + public void setUri(String value) { + this.uri = value; + } + + public String getContactStatus() { + return contactStatus; + } + + public void setContactStatus(String value) { + this.contactStatus = value; + } + + public String getAor() { + return aor; + } + + public void setAor(String value) { + this.aor = value; + } + + public String getEndpointName() { + return endpointName; + } + + public void setEndpointName(String value) { + this.endpointName = value; + } + + public String getRoundtripUsec() { + return roundtripUsec; + } + + public void setRoundtripUsec(String value) { + this.roundtripUsec = value; + } + + public String getUserAgent() { + return userAgent; + } + + public void setUserAgent(String value) { + this.userAgent = value; + } + + public String getRegExpire() { + return regExpire; + } + + public void setRegExpire(String value) { + this.regExpire = value; + } + + public String getViaAddress() { + return viaAddress; + } + + public void setViaAddress(String value) { + this.viaAddress = value; + } + + public String getCallID() { + return callID; + } + + public void setCallID(String callID) { + this.callID = callID; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/CoreShowChannelEvent.java b/src/main/java/org/asteriskjava/manager/event/CoreShowChannelEvent.java index 531123167..3c8ee2225 100644 --- a/src/main/java/org/asteriskjava/manager/event/CoreShowChannelEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/CoreShowChannelEvent.java @@ -1,12 +1,12 @@ /* * Copyright 2009 Sebastian. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,15 +17,15 @@ package org.asteriskjava.manager.event; /** - * A CoreShowChannelEvent is triggered for each active channel in response to a CoreShowChannelsAction. + * A CoreShowChannelEvent is triggered for each active channel in response to a + * CoreShowChannelsAction. * * @author sebastian gutierrez * @version $Id$ * @see org.asteriskjava.manager.action.CoreShowChannelsAction * @since 1.0.0 */ -public class CoreShowChannelEvent extends ResponseEvent -{ +public class CoreShowChannelEvent extends ResponseEvent { /** * Serializable version identifier. */ @@ -33,21 +33,18 @@ public class CoreShowChannelEvent extends ResponseEvent private String uniqueid; private String channel; - private String context; private String extension; - private String priority; - private String ChannelState; - private String channelstatedesc; private String application; private String applicationdata; - private String calleridnum; private String duration; private String accountcode; private String bridgedChannel; - private String bridgeduniqueid; + private String bridgeid; + private String linkedid; + private String language; - public CoreShowChannelEvent(Object source) - { + + public CoreShowChannelEvent(Object source) { super(source); } @@ -57,28 +54,16 @@ public CoreShowChannelEvent(Object source) * @return channel state */ - public String getChannelState() - { - return ChannelState; - } - - public void setChannelState(String ChannelState) - { - this.ChannelState = ChannelState; - } - /** * Returns the Account code * * @return accountcode */ - public String getAccountcode() - { + public String getAccountcode() { return accountcode; } - public void setAccountcode(String accountcode) - { + public void setAccountcode(String accountcode) { this.accountcode = accountcode; } @@ -87,29 +72,25 @@ public void setAccountcode(String accountcode) * * @return aplication name */ - public String getApplication() - { + public String getApplication() { return application; } - public void setApplication(String application) - { + public void setApplication(String application) { this.application = application; } /** - * Returns the Aplication Data is runnning that channel at that time - * this is the parameters passed to that dialplan application + * Returns the Aplication Data is runnning that channel at that time this is + * the parameters passed to that dialplan application * * @return aplication data */ - public String getApplicationdata() - { + public String getApplicationdata() { return applicationdata; } - public void setApplicationdata(String applicationdata) - { + public void setApplicationdata(String applicationdata) { this.applicationdata = applicationdata; } @@ -118,13 +99,11 @@ public void setApplicationdata(String applicationdata) * * @return Channel name */ - public String getBridgedChannel() - { + public String getBridgedChannel() { return bridgedChannel; } - public void setBridgedChannel(String bridgedChannel) - { + public void setBridgedChannel(String bridgedChannel) { this.bridgedChannel = bridgedChannel; } @@ -133,29 +112,27 @@ public void setBridgedChannel(String bridgedChannel) * * @return uniqueid */ - public String getBridgeduniqueid() - { - return bridgeduniqueid; + @Deprecated + public String getBridgeduniqueid() { + return bridgeid; } - public void setBridgeduniqueid(String bridgeduniqueid) - { - this.bridgeduniqueid = bridgeduniqueid; + @Deprecated + public void setBridgeduniqueid(String bridgeduniqueid) { + this.bridgeid = bridgeduniqueid; } /** - * Returns the CallerID + * Returns the Bridged UniqueID Case params name return "bridgeid" * - * @return callerid + * @return uniqueid */ - public String getCalleridnum() - { - return calleridnum; + public String getBridgeid() { + return bridgeid; } - public void setCalleridnum(String calleridnum) - { - this.calleridnum = calleridnum; + public void setBridgeid(String bridgeid) { + this.bridgeid = bridgeid; } /** @@ -163,58 +140,24 @@ public void setCalleridnum(String calleridnum) * * @return Channel name */ - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - /** - * Returns the Channel state description (RING,...) - * - * @return description - */ - public String getChannelstatedesc() - { - return channelstatedesc; - } - - public void setChannelstatedesc(String channelstatedesc) - { - this.channelstatedesc = channelstatedesc; - } - - /** - * Returns the Context the channel is - * - * @return context - */ - public String getContext() - { - return context; - } - - public void setContext(String context) - { - this.context = context; - } - /** * Returns the duration of the call * * @return duration */ - public String getDuration() - { + public String getDuration() { return duration; } - public void setDuration(String duration) - { + public void setDuration(String duration) { this.duration = duration; } @@ -223,45 +166,54 @@ public void setDuration(String duration) * * @return extension */ - public String getExtension() - { + public String getExtension() { return extension; } - public void setExtension(String extension) - { + public void setExtension(String extension) { this.extension = extension; } /** - * Returns the Priority the channel actualy is + * Returns the Uniqueid * - * @return priority + * @return uniqueid */ - public String getPriority() - { - return priority; + public String getUniqueid() { + return uniqueid; } - public void setPriority(String priority) - { - this.priority = priority; + public void setUniqueid(String uniqueid) { + this.uniqueid = uniqueid; } + /** - * Returns the Uniqueid + * Returns the Channel LinkedID * - * @return uniqueid + * @return linkedid */ - public String getUniqueid() - { - return uniqueid; + public String getLinkedid() { + return linkedid; } - public void setUniqueid(String uniqueid) - { - this.uniqueid = uniqueid; + public void setLinkedid(String linkedid) { + this.linkedid = linkedid; + } + + + /** + * Returns the Channel Language + * + * @return language + */ + public String getLanguage() { + return language; } - + public void setLanguage(String language) { + this.language = language; + } + + } diff --git a/src/main/java/org/asteriskjava/manager/event/CoreShowChannelsCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/CoreShowChannelsCompleteEvent.java index 5362be21e..c4276e9c4 100644 --- a/src/main/java/org/asteriskjava/manager/event/CoreShowChannelsCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/CoreShowChannelsCompleteEvent.java @@ -1,12 +1,12 @@ /* * Copyright 2009 Sebastian. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,8 +26,7 @@ * @see org.asteriskjava.manager.event.CoreShowChannelEvent * @since 1.0.0 */ -public class CoreShowChannelsCompleteEvent extends ResponseEvent -{ +public class CoreShowChannelsCompleteEvent extends ResponseEvent { /** * Serial version identifier. @@ -37,8 +36,7 @@ public class CoreShowChannelsCompleteEvent extends ResponseEvent private Integer listitems; private String eventlist; - public CoreShowChannelsCompleteEvent(Object source) - { + public CoreShowChannelsCompleteEvent(Object source) { super(source); } @@ -48,13 +46,11 @@ public CoreShowChannelsCompleteEvent(Object source) * @return the status of the list. * @since 1.0.0 */ - public String getEventlist() - { + public String getEventlist() { return eventlist; } - public void setEventlist(String eventlist) - { + public void setEventlist(String eventlist) { this.eventlist = eventlist; } @@ -63,18 +59,16 @@ public void setEventlist(String eventlist) * * @return the number of channels reported. */ - public Integer getListitems() - { + public Integer getListitems() { return listitems; } /** * Sets the number of channels reported.

      * - * @param items the number of channels reported. + * @param listitems the number of channels reported. */ - public void setListitems(Integer listitems) - { + public void setListitems(Integer listitems) { this.listitems = listitems; } diff --git a/src/main/java/org/asteriskjava/manager/event/DAHDIChannelEvent.java b/src/main/java/org/asteriskjava/manager/event/DAHDIChannelEvent.java new file mode 100644 index 000000000..40ab63d22 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DAHDIChannelEvent.java @@ -0,0 +1,90 @@ +package org.asteriskjava.manager.event; + +/** + * @author Sebastian + */ +public class DAHDIChannelEvent extends ManagerEvent { + + /** + * + */ + private static final long serialVersionUID = 2L; + + private Integer dahdigroup; + private String dahdichannel; + private String dahdispan; + private String uniqueid; + private String channel; + private String language; + private String accountCode; + private String linkedId; + + public Integer getDahdigroup() { + return this.dahdigroup; + } + + public void setDahdigroup(Integer dahdigroup) { + this.dahdigroup = dahdigroup; + } + + public String getDahdichannel() { + return dahdichannel; + } + + public void setDahdichannel(String dahdichannel) { + this.dahdichannel = dahdichannel; + } + + public String getDahdispan() { + return dahdispan; + } + + public void setDahdispan(String dahdispan) { + this.dahdispan = dahdispan; + } + + public String getUniqueid() { + return uniqueid; + } + + public void setUniqueid(String uniqueid) { + this.uniqueid = uniqueid; + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public String getLinkedId() { + return this.linkedId; + } + + public void setLinkedId(String linkedid) { + this.linkedId = linkedid; + } + + public String getLanguage() { + return this.language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getAccountCode() { + return this.accountCode; + } + + public void setAccountCode(String accountcode) { + this.accountCode = accountcode; + } + + public DAHDIChannelEvent(Object source) { + super(source); + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsCompleteEvent.java new file mode 100644 index 000000000..8053e1e4e --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsCompleteEvent.java @@ -0,0 +1,85 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A DahdiShowChannelsCompleteEvent is triggered after the state of all Dahdi channels has been reported + * in response to a DahdiShowChannelsAction. + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.action.DahdiShowChannelsAction + * @see org.asteriskjava.manager.event.DahdiShowChannelsEvent + */ +public class DahdiShowChannelsCompleteEvent extends ResponseEvent { + /** + * Serial version identifier + */ + private static final long serialVersionUID = 6323249250335885462L; + + private Integer listitems; + private String eventlist; + private Integer items; + + public Integer getItems() { + return items; + } + + public void setItems(Integer items) { + this.items = items; + } + + /** + * @param source + */ + public DahdiShowChannelsCompleteEvent(Object source) { + super(source); + } + + /** + * Returns if the status of the eventlist (should be Complete).

      + * + * @return the status of the list. + * @since 1.0.0 + */ + public String getEventlist() { + return eventlist; + } + + public void setEventlist(String eventlist) { + this.eventlist = eventlist; + } + + /** + * Returns the number of channels reported.

      + * + * @return the number of channels reported. + */ + public Integer getListitems() { + return listitems; + } + + /** + * Sets the number of channels reported.

      + * + * @param listitems the number of channels reported. + */ + public void setListitems(Integer listitems) { + this.listitems = listitems; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsEvent.java b/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsEvent.java new file mode 100644 index 000000000..38035de39 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsEvent.java @@ -0,0 +1,174 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A DahdiShowChannelsEvent is triggered in response to a DahdiShowChannelsAction and shows the state of + * a Dahdi channel. + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.action.DahdiShowChannelsAction + */ +public class DahdiShowChannelsEvent extends ResponseEvent { + /** + * Serial version identifier + */ + private static final long serialVersionUID = -3613642267527361400L; + private Integer Dahdichannel; + private String signalling; + private String signallingcode; + private Boolean dnd; + private String alarm; + private String uniqueid; + private String accountcode; + private String channel; + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public Integer getDahdichannel() { + return Dahdichannel; + } + + public void setDahdichannel(Integer Dahdichannel) { + this.Dahdichannel = Dahdichannel; + } + + public String getSignallingcode() { + return signallingcode; + } + + public void setSignallingcode(String signallingcode) { + this.signallingcode = signallingcode; + } + + public String getUniqueid() { + return uniqueid; + } + + public void setUniqueid(String uniqueid) { + this.uniqueid = uniqueid; + } + + + /** + * @param source + */ + public DahdiShowChannelsEvent(Object source) { + super(source); + } + + + /** + * Returns the signalling of this Dahdi channel.

      + * Possible values are: + *

        + *
      • E & M Immediate
      • + *
      • E & M Wink
      • + *
      • E & M E1
      • + *
      • Feature Group D (DTMF)
      • + *
      • Feature Group D (MF)
      • + *
      • Feature Group B (MF)
      • + *
      • E911 (MF)
      • + *
      • FXS Loopstart
      • + *
      • FXS Groundstart
      • + *
      • FXS Kewlstart
      • + *
      • FXO Loopstart
      • + *
      • FXO Groundstart
      • + *
      • FXO Kewlstart
      • + *
      • PRI Signalling
      • + *
      • R2 Signalling
      • + *
      • SF (Tone) Signalling Immediate
      • + *
      • SF (Tone) Signalling Wink
      • + *
      • SF (Tone) Signalling with Feature Group D (DTMF)
      • + *
      • SF (Tone) Signalling with Feature Group D (MF)
      • + *
      • SF (Tone) Signalling with Feature Group B (MF)
      • + *
      • GR-303 Signalling with FXOKS
      • + *
      • GR-303 Signalling with FXSKS
      • + *
      • Pseudo Signalling
      • + *
      + */ + public String getSignalling() { + return signalling; + } + + /** + * Sets the signalling of this Dahdi channel. + */ + public void setSignalling(String signalling) { + this.signalling = signalling; + } + + /** + * Returns whether dnd (do not disturb) is enabled for this Dahdi channel. + * + * @return Boolean.TRUE if dnd is enabled, Boolean.FALSE if it is disabled, + * null if not set. + * @since 0.3 + */ + public Boolean getDnd() { + return dnd; + } + + /** + * Sets whether dnd (do not disturb) is enabled for this Dahdi channel. + * + * @param dnd Boolean.TRUE if dnd is enabled, Boolean.FALSE if it is disabled. + * @since 0.3 + */ + public void setDnd(Boolean dnd) { + this.dnd = dnd; + } + + /** + * Returns the alarm state of this Dahdi channel.

      + * This may be one of + *

        + *
      • Red Alarm
      • + *
      • Yellow Alarm
      • + *
      • Blue Alarm
      • + *
      • Recovering
      • + *
      • Loopback
      • + *
      • Not Open
      • + *
      • No Alarm
      • + *
      + */ + public String getAlarm() { + return alarm; + } + + /** + * Sets the alarm state of this Dahdi channel. + */ + public void setAlarm(String alarm) { + this.alarm = alarm; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/DbGetResponseEvent.java b/src/main/java/org/asteriskjava/manager/event/DbGetResponseEvent.java index b1fdbb3c9..fdd74b35f 100644 --- a/src/main/java/org/asteriskjava/manager/event/DbGetResponseEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DbGetResponseEvent.java @@ -20,14 +20,13 @@ * A DBGetResponseEvent is sent in response to a DBGetAction and contains the * entry that was queried.

      * Available since Asterisk 1.2 - * - * @see org.asteriskjava.manager.action.DbGetAction + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.DbGetAction * @since 0.2 */ -public class DbGetResponseEvent extends ResponseEvent -{ +public class DbGetResponseEvent extends ResponseEvent { private String family; private String key; private String val; @@ -40,80 +39,72 @@ public class DbGetResponseEvent extends ResponseEvent /** * @param source */ - public DbGetResponseEvent(Object source) - { + public DbGetResponseEvent(Object source) { super(source); } /** * Returns the family of the database entry that was queried. - * + * * @return the family of the database entry that was queried. */ - public String getFamily() - { + public String getFamily() { return family; } /** * Sets the family of the database entry that was queried. - * + * * @param family the family of the database entry that was queried. */ - public void setFamily(String family) - { + public void setFamily(String family) { this.family = family; } /** * Returns the key of the database entry that was queried. - * + * * @return the key of the database entry that was queried. */ - public String getKey() - { + public String getKey() { return key; } /** * Sets the key of the database entry that was queried. - * + * * @param key the key of the database entry that was queried. */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } /** * Returns the value of the database entry that was queried. - * + * * @return the value of the database entry that was queried. */ - public String getVal() - { + public String getVal() { return val; } /** * Sets the value of the database entry that was queried. - * + * * @param val the value of the database entry that was queried. */ - public void setVal(String val) - { + public void setVal(String val) { this.val = val; } - + /** * Sets the value of the database entry that was queried. * It seems that in ast 1.2 ( 1.2.9 +BRIStuff ? ) at least the key is * not val anymore but value. - * + * * @param val the value of the database entry that was queried. */ - public void setValue(String val) - { + public void setValue(String val) { this.val = val; } } diff --git a/src/main/java/org/asteriskjava/manager/event/DeviceStateChangeEvent.java b/src/main/java/org/asteriskjava/manager/event/DeviceStateChangeEvent.java new file mode 100644 index 000000000..841a25be4 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DeviceStateChangeEvent.java @@ -0,0 +1,30 @@ +package org.asteriskjava.manager.event; + +public class DeviceStateChangeEvent extends ManagerEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + private String state; + private String device; + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getDevice() { + return device; + } + + public void setDevice(String device) { + this.device = device; + } + + public DeviceStateChangeEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/DialBeginEvent.java b/src/main/java/org/asteriskjava/manager/event/DialBeginEvent.java new file mode 100644 index 000000000..bba22d876 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DialBeginEvent.java @@ -0,0 +1,74 @@ +package org.asteriskjava.manager.event; + +public class DialBeginEvent extends DialEvent { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String language; + private String destlanguage; + private String destAccountCode; + private String linkedId; + private String destLinkedId; + + private String accountcode; + + public DialBeginEvent(Object source) { + super(source); + setSubEvent(SUBEVENT_BEGIN); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getDestLanguage() { + return destlanguage; + } + + public void setDestLanguage(String destlanguage) { + this.destlanguage = destlanguage; + } + + public String getDestAccountCode() { + return destAccountCode; + } + + public void setDestAccountCode(String destAccountCode) { + this.destAccountCode = destAccountCode; + } + + public String getDestlanguage() { + return destlanguage; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getDestLinkedId() { + return destLinkedId; + } + + public void setDestLinkedId(String destLinkedId) { + this.destLinkedId = destLinkedId; + } + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DialEndEvent.java b/src/main/java/org/asteriskjava/manager/event/DialEndEvent.java new file mode 100644 index 000000000..dcb5be717 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DialEndEvent.java @@ -0,0 +1,77 @@ +package org.asteriskjava.manager.event; + +public class DialEndEvent extends DialEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + private String language; + private String destLanguage; + private String accountCode; + private String destAccountCode; + private String destLinkedId; + private String linkedId; + private String forward; + + public DialEndEvent(Object source) { + super(source); + setSubEvent(SUBEVENT_END); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getDestLanguage() { + return destLanguage; + } + + public void setDestLanguage(String destLanguage) { + this.destLanguage = destLanguage; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getDestAccountCode() { + return destAccountCode; + } + + public void setDestAccountCode(String destAccountCode) { + this.destAccountCode = destAccountCode; + } + + public String getDestLinkedId() { + return destLinkedId; + } + + public void setDestLinkedId(String destLinkedId) { + this.destLinkedId = destLinkedId; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getForward() { + return forward; + } + + public void setForward(String forward) { + this.forward = forward; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DialEvent.java b/src/main/java/org/asteriskjava/manager/event/DialEvent.java index 8d95c9405..4af7c5e6f 100644 --- a/src/main/java/org/asteriskjava/manager/event/DialEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DialEvent.java @@ -17,16 +17,17 @@ package org.asteriskjava.manager.event; /** - * A dial event is triggered whenever a phone attempts to dial someone.

      - * This event is implemented in apps/app_dial.c.

      + * A dial event is triggered whenever a phone attempts to dial someone. + *

      + * This event is implemented in apps/app_dial.c. + *

      * Available since Asterisk 1.2. * - * @author Asteria Solutions Group, Inc. + * @author Asteria Solutions Group, Inc. http://www.asteriasgi.com/ * @version $Id$ * @since 0.2 */ -public class DialEvent extends ManagerEvent -{ +public class DialEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -58,14 +59,22 @@ public class DialEvent extends ManagerEvent private String destination; /** - * The new Caller*ID. + * Destination channel state */ - private String callerIdNum; + private Integer destChannelState; + private String destChannelStateDesc; - /** - * The new Caller*ID Name. - */ - private String callerIdName; + private String destContext; + + private Integer destPriority; + + private String destExten; + + private String destConnectedLineName; + private String destConnectedLineNum; + + private String destCallerIdName; + private String destCallerIdNum; /** * The unique id of the source channel. @@ -80,29 +89,47 @@ public class DialEvent extends ManagerEvent private String dialString; private String dialStatus; - public DialEvent(Object source) - { + public DialEvent(Object source) { super(source); } /** - * Since Asterisk 1.6 the begin and the end of a dial command generate a Dial event. The - * subEvent property returns whether the dial started execution ("Begin") or completed ("End"). - * As Asterisk prior to 1.6 only sends one event per Dial command this always returns "Begin" - * for Asterisk prior to 1.6.
      - * For an "End" sub event only the properies channel, unqiue id and dial status are available, - * for a "Begin" sub event all properties are available except for the dial status. + * Enro 2015-03 Workaround to build legacy DialEvent (unsupported in + * Asterisk 13) from new DialBeginEvent Asterisk 13. + */ + public DialEvent(DialBeginEvent dialBeginEvent) { + this(dialBeginEvent.getSource()); + setDateReceived(dialBeginEvent.getDateReceived()); + setTimestamp(dialBeginEvent.getTimestamp()); + setPrivilege(dialBeginEvent.getPrivilege()); + setCallerId(dialBeginEvent.getCallerIdNum()); + setCallerIdName(dialBeginEvent.getCallerIdName()); + setSrc(dialBeginEvent.getChannel()); + setUniqueId(dialBeginEvent.getSrcUniqueId()); + setDestUniqueId(dialBeginEvent.getDestUniqueId()); + setDestination(dialBeginEvent.getDestChannel()); + setDialStatus(dialBeginEvent.getDialStatus()); + } + + /** + * Since Asterisk 1.6 the begin and the end of a dial command generate a + * Dial event. The subEvent property returns whether the dial started + * execution ("Begin") or completed ("End"). As Asterisk prior to 1.6 only + * sends one event per Dial command this always returns "Begin" for Asterisk + * prior to 1.6.
      + * For an "End" sub event only the properies channel, unqiue id and dial + * status are available, for a "Begin" sub event all properties are + * available except for the dial status. * - * @return "Begin" or "End" for Asterisk since 1.6, "Begin" for Asterisk prior to 1.6. + * @return "Begin" or "End" for Asterisk since 1.6, "Begin" for Asterisk + * prior to 1.6. * @since 1.0.0 */ - public String getSubEvent() - { + public String getSubEvent() { return subEvent; } - public void setSubEvent(String subEvent) - { + public void setSubEvent(String subEvent) { this.subEvent = subEvent; } @@ -112,8 +139,7 @@ public void setSubEvent(String subEvent) * @return the name of the source channel. * @since 1.0.0 */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -123,8 +149,7 @@ public String getChannel() * @param channel the name of the source channel. * @since 1.0.0 */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -134,19 +159,20 @@ public void setChannel(String channel) * @return the name of the source channel. * @deprecated as of 1.0.0, use {@link #getChannel()} instead. */ - @Deprecated public String getSrc() - { + @Deprecated + public String getSrc() { return channel; } /** - * Sets the name of the source channel.

      - * Asterisk versions up to 1.4 use the "Source" property instead of "Channel". + * Sets the name of the source channel. + *

      + * Asterisk versions up to 1.4 use the "Source" property instead of + * "Channel". * * @param src the name of the source channel. */ - public void setSrc(String src) - { + public void setSrc(String src) { this.channel = src; } @@ -155,76 +181,47 @@ public void setSrc(String src) * * @return the name of the destination channel. */ - public String getDestination() - { + public String getDestination() { return destination; } + public String getDestChannel() { + return getDestination(); + } + /** * Sets the name of the destination channel. * * @param destination the name of the destination channel. */ - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } - /** - * Returns the the Caller*ID Number. - * - * @return the the Caller*ID Number or "" if none has been set. - * @since 1.0.0 - */ - public String getCallerIdNum() - { - return callerIdNum; - } - - public void setCallerIdNum(String callerIdNum) - { - this.callerIdNum = callerIdNum; + public void setDestChannel(String destination) { + setDestination(destination); } /** * Returns the Caller*ID. * - * @return the Caller*ID or "" if none has been set. + * @return the Caller*ID or "<unknown>" if none has been set. * @deprecated as of 1.0.0, use {@link #getCallerIdNum()} instead. */ - @Deprecated public String getCallerId() - { - return callerIdNum; + @Deprecated + public String getCallerId() { + return getCallerIdNum(); } /** * Sets the caller*ID. * * @param callerId the caller*ID. + * @deprecated as of 1.0.0, use {@link #setCallerIdNum()} instead. */ - public void setCallerId(String callerId) - { - this.callerIdNum = callerId; - } - - /** - * Returns the Caller*ID Name. - * - * @return the Caller*ID Name or "" if none has been set. - */ - public String getCallerIdName() - { - return callerIdName; - } - - /** - * Sets the Caller*Id Name. - * - * @param callerIdName the Caller*Id Name to set. - */ - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; + @Deprecated + public void setCallerId(String callerId) { + setCallerIdNum(callerId); } /** @@ -233,8 +230,7 @@ public void setCallerIdName(String callerIdName) * @return the unique ID of the source channel. * @since 1.0.0 */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -244,8 +240,7 @@ public String getUniqueId() * @param srcUniqueId the unique ID of the source channel. * @since 1.0.0 */ - public void setUniqueId(String srcUniqueId) - { + public void setUniqueId(String srcUniqueId) { this.uniqueId = srcUniqueId; } @@ -255,19 +250,20 @@ public void setUniqueId(String srcUniqueId) * @return the unique ID of the source channel. * @deprecated as of 1.0.0, use {@link #getUniqueId()} instead. */ - @Deprecated public String getSrcUniqueId() - { + @Deprecated + public String getSrcUniqueId() { return uniqueId; } /** - * Sets the unique ID of the source channel.

      - * Asterisk versions up to 1.4 use the "SrcUniqueId" property instead of "UniqueId". + * Sets the unique ID of the source channel. + *

      + * Asterisk versions up to 1.4 use the "SrcUniqueId" property instead of + * "UniqueId". * * @param srcUniqueId the unique ID of the source channel. */ - public void setSrcUniqueId(String srcUniqueId) - { + public void setSrcUniqueId(String srcUniqueId) { this.uniqueId = srcUniqueId; } @@ -276,8 +272,7 @@ public void setSrcUniqueId(String srcUniqueId) * * @return the unique ID of the destination channel. */ - public String getDestUniqueId() - { + public String getDestUniqueId() { return destUniqueId; } @@ -286,20 +281,19 @@ public String getDestUniqueId() * * @param destUniqueId the unique ID of the destination channel. */ - public void setDestUniqueId(String destUniqueId) - { + public void setDestUniqueId(String destUniqueId) { this.destUniqueId = destUniqueId; } /** - * Returns the dial string passed to the Dial application.

      + * Returns the dial string passed to the Dial application. + *

      * Available since Asterisk 1.6. * * @return the dial string passed to the Dial application. * @since 1.0.0 */ - public String getDialString() - { + public String getDialString() { return dialString; } @@ -309,13 +303,13 @@ public String getDialString() * @param dialString the dial string passed to the Dial application. * @since 1.0.0 */ - public void setDialString(String dialString) - { + public void setDialString(String dialString) { this.dialString = dialString; } /** - * For end subevents this returns whether the completion status of the dial application.
      + * For end subevents this returns whether the completion status of the dial + * application.
      * Possible values are: *

        *
      • CHANUNAVAIL
      • @@ -328,19 +322,119 @@ public void setDialString(String dialString) *
      • TORTURE
      • *
      • INVALIDARGS
      • *
      - * It corresponds the the DIALSTATUS variable used in the dialplan.

      + * It corresponds the the DIALSTATUS variable used in the dialplan. + *

      * Available since Asterisk 1.6. * * @return the completion status of the dial application. * @since 1.0.0 */ - public String getDialStatus() - { + public String getDialStatus() { return dialStatus; } - public void setDialStatus(String dialStatus) - { + public void setDialStatus(String dialStatus) { this.dialStatus = dialStatus; } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("DialEvent [subEvent="); + builder.append(subEvent); + builder.append(", channel="); + builder.append(channel); + builder.append(", destination="); + builder.append(destination); + builder.append(", callerIdNum="); + builder.append(callerIdNum); + builder.append(", callerIdName="); + builder.append(callerIdName); + builder.append(", uniqueId="); + builder.append(uniqueId); + builder.append(", destUniqueId="); + builder.append(destUniqueId); + builder.append(", dialString="); + builder.append(dialString); + builder.append(", dialStatus="); + builder.append(dialStatus); + builder.append(", connectedLineNum="); + builder.append(connectedLineNum); + builder.append(", connectedLineName="); + builder.append(connectedLineName); + builder.append("]"); + return builder.toString(); + } + + public Integer getDestChannelState() { + return destChannelState; + } + + public void setDestChannelState(Integer destChannelState) { + this.destChannelState = destChannelState; + } + + public String getDestContext() { + return destContext; + } + + public void setDestContext(String destContext) { + this.destContext = destContext; + } + + public Integer getDestPriority() { + return destPriority; + } + + public void setDestPriority(Integer destPriority) { + this.destPriority = destPriority; + } + + public String getDestChannelStateDesc() { + return destChannelStateDesc; + } + + public void setDestChannelStateDesc(String destChannelStateDesc) { + this.destChannelStateDesc = destChannelStateDesc; + } + + public String getDestExten() { + return destExten; + } + + public void setDestExten(String destExten) { + this.destExten = destExten; + } + + public String getDestConnectedLineName() { + return destConnectedLineName; + } + + public void setDestConnectedLineName(String destConnectedLineName) { + this.destConnectedLineName = destConnectedLineName; + } + + public String getDestConnectedLineNum() { + return destConnectedLineNum; + } + + public void setDestConnectedLineNum(String destConnectedLineNum) { + this.destConnectedLineNum = destConnectedLineNum; + } + + public String getDestCallerIdName() { + return destCallerIdName; + } + + public void setDestCallerIdName(String destCallerIdName) { + this.destCallerIdName = destCallerIdName; + } + + public String getDestCallerIdNum() { + return destCallerIdNum; + } + + public void setDestCallerIdNum(String destCallerIdNum) { + this.destCallerIdNum = destCallerIdNum; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/DialStateEvent.java b/src/main/java/org/asteriskjava/manager/event/DialStateEvent.java new file mode 100644 index 000000000..7e6ce09c6 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DialStateEvent.java @@ -0,0 +1,215 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +public class DialStateEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + String destAccountCode; + String destCallerIdName; + String destCallerIdNum; + String destChannel; + String destChannelState; + String destChannelStateDesc; + String destConnectedLineName; + String destConnectedLineNum; + String destContext; + String destExten; + String destLanguage; + String destLinkedId; + String destPriority; + String destUniqueId; + String dialStatus; + String privilege; + String uniqueId; + String linkedId; + String accountCode; + String language; + String channel; + + public DialStateEvent(Object source) { + super(source); + } + + public String getDestAccountCode() { + return destAccountCode; + } + + public void setDestAccountCode(String destAccountCode) { + this.destAccountCode = destAccountCode; + } + + public String getDestCallerIdName() { + return destCallerIdName; + } + + public void setDestCallerIdName(String destCallerIdName) { + this.destCallerIdName = destCallerIdName; + } + + public String getDestCallerIdNum() { + return destCallerIdNum; + } + + public void setDestCallerIdNum(String destCallerIdNum) { + this.destCallerIdNum = destCallerIdNum; + } + + public String getDestChannel() { + return destChannel; + } + + public void setDestChannel(String destChannel) { + this.destChannel = destChannel; + } + + public String getDestChannelState() { + return destChannelState; + } + + public void setDestChannelState(String destChannelState) { + this.destChannelState = destChannelState; + } + + public String getDestChannelStateDesc() { + return destChannelStateDesc; + } + + public void setDestChannelStateDesc(String destChannelStateDesc) { + this.destChannelStateDesc = destChannelStateDesc; + } + + public String getDestConnectedLineName() { + return destConnectedLineName; + } + + public void setDestConnectedLineName(String destConnectedLineName) { + this.destConnectedLineName = destConnectedLineName; + } + + public String getDestConnectedLineNum() { + return destConnectedLineNum; + } + + public void setDestConnectedLineNum(String destConnectedLineNum) { + this.destConnectedLineNum = destConnectedLineNum; + } + + public String getDestContext() { + return destContext; + } + + public void setDestContext(String destContext) { + this.destContext = destContext; + } + + public String getDestExten() { + return destExten; + } + + public void setDestExten(String destExten) { + this.destExten = destExten; + } + + public String getDestLanguage() { + return destLanguage; + } + + public void setDestLanguage(String destLanguage) { + this.destLanguage = destLanguage; + } + + public String getDestLinkedId() { + return destLinkedId; + } + + public void setDestLinkedId(String destLinkedId) { + this.destLinkedId = destLinkedId; + } + + public String getDestPriority() { + return destPriority; + } + + public void setDestPriority(String destPriority) { + this.destPriority = destPriority; + } + + public String getDestUniqueId() { + return destUniqueId; + } + + public void setDestUniqueId(String destUniqueId) { + this.destUniqueId = destUniqueId; + } + + public String getDialStatus() { + return dialStatus; + } + + public void setDialStatus(String dialStatus) { + this.dialStatus = dialStatus; + } + + public String getPrivilege() { + return privilege; + } + + public void setPrivilege(String privilege) { + this.privilege = privilege; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/DisconnectEvent.java b/src/main/java/org/asteriskjava/manager/event/DisconnectEvent.java index 129490d26..7ce68e4f3 100644 --- a/src/main/java/org/asteriskjava/manager/event/DisconnectEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DisconnectEvent.java @@ -19,13 +19,12 @@ /** * A DisconnectEvent is triggered when the connection to the asterisk server is lost.

      * It is a pseudo event not directly related to an Asterisk generated event. - * + * * @author srt * @version $Id$ * @see org.asteriskjava.manager.event.ConnectEvent */ -public class DisconnectEvent extends ManagerEvent -{ +public class DisconnectEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -34,8 +33,7 @@ public class DisconnectEvent extends ManagerEvent /** * @param source */ - public DisconnectEvent(Object source) - { + public DisconnectEvent(Object source) { super(source); } } diff --git a/src/main/java/org/asteriskjava/manager/event/DndStateEvent.java b/src/main/java/org/asteriskjava/manager/event/DndStateEvent.java index 7af8b31e2..1e4e4bccf 100644 --- a/src/main/java/org/asteriskjava/manager/event/DndStateEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DndStateEvent.java @@ -21,13 +21,12 @@ * or leaves DND (do not disturb) state.

      * It is implemented in channels/chan_zap.c.

      * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class DndStateEvent extends ManagerEvent -{ +public class DndStateEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -45,11 +44,10 @@ public class DndStateEvent extends ManagerEvent /** * Creates a new DNDStateEvent. - * + * * @param source */ - public DndStateEvent(Object source) - { + public DndStateEvent(Object source) { super(source); } @@ -57,34 +55,30 @@ public DndStateEvent(Object source) * Returns the name of the channel. The channel name is of the form * "Zap/<channel number>". */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns DND state of the channel. - * + * * @return Boolean.TRUE if do not disturb is on, Boolean.FALSE if it is off. */ - public Boolean getState() - { + public Boolean getState() { return state; } /** * Sets the DND state of the channel. */ - public void setState(Boolean state) - { + public void setState(Boolean state) { this.state = state; } } diff --git a/src/main/java/org/asteriskjava/manager/event/DongleCENDEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleCENDEvent.java new file mode 100644 index 000000000..4911a06f1 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DongleCENDEvent.java @@ -0,0 +1,57 @@ +package org.asteriskjava.manager.event; + +public class DongleCENDEvent extends ManagerEvent { + private static final long serialVersionUID = 3257845467831284784L; + private String device; + private String endstatus; + private String cccause; + private String duration; + private String callidx; + + + public DongleCENDEvent(Object source) { + super(source); + } + + public String getDevice() { + return this.device; + } + + public void setDevice(String device) { + this.device = device; + } + + public String getCallidx() { + return callidx; + } + + public void setCallidx(String callidx) { + this.callidx = callidx; + } + + public String getCccause() { + return cccause; + } + + public void setCccause(String cccause) { + this.cccause = cccause; + } + + public String getDuration() { + return duration; + } + + public void setDuration(String duration) { + this.duration = duration; + } + + public String getEndstatus() { + return endstatus; + } + + public void setEndstatus(String endstatus) { + this.endstatus = endstatus; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleCallStateChangeEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleCallStateChangeEvent.java new file mode 100644 index 000000000..1c32b334d --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DongleCallStateChangeEvent.java @@ -0,0 +1,38 @@ +package org.asteriskjava.manager.event; + +public class DongleCallStateChangeEvent extends ManagerEvent { + private static final long serialVersionUID = 3257845467831284784L; + private String device; + private String callidx; + private String newstate; + + public DongleCallStateChangeEvent(Object source) { + super(source); + } + + public String getDevice() { + return this.device; + } + + public void setDevice(String device) { + this.device = device; + } + + public String getCallidx() { + return callidx; + } + + public void setCallidx(String callidx) { + this.callidx = callidx; + } + + public String getNewstate() { + return newstate; + } + + public void setNewstate(String newstate) { + this.newstate = newstate; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleDeviceEntryEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleDeviceEntryEvent.java new file mode 100644 index 000000000..08020c101 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DongleDeviceEntryEvent.java @@ -0,0 +1,519 @@ +package org.asteriskjava.manager.event; + +public class DongleDeviceEntryEvent extends ResponseEvent { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String Device; + private String AudioSetting; + private String DataSetting; + private String IMEISetting; + private String IMSISetting; + private String ChannelLanguage; + private String Group; + private String RXGain; + private String TXGain; + private String U2DIAG; + private String UseCallingPres; + private String DefaultCallingPres; + private String AutoDeleteSMS; + private String DisableSMS; + private String ResetDongle; + private String SMSPDU; + private String CallWaitingSetting; + private String DTMF; + private String MinimalDTMFGap; + private String MinimalDTMFDuration; + private String MinimalDTMFInterval; + + private String State; + private String AudioState; + private String DataState; + private String Voice; + private String SMS; + private String Manufacturer; + private String Model; + private String Firmware; + private String IMEIState; + private String GSMRegistrationStatus; + private String RSSI; + private String Mode; + private String Submode; + private String ProviderName; + private String LocationAreaCode; + private String CellID; + private String SubscriberNumber; + private String SMSServiceCenter; + private String UseUCS2Encoding; + private String USSDUse7BitEncoding; + private String USSDUseUCS2Decoding; + private String TasksInQueue; + private String CommandsInQueue; + private String CallWaitingState; + private String CurrentDeviceState; + private String DesiredDeviceState; + private String CallsChannels; + private String Active; + private String Held; + private String Dialing; + private String Alerting; + private String Incoming; + private String Waiting; + private String Releasing; + private String Initializing; + + public DongleDeviceEntryEvent(Object source) { + super(source); + } + + public String getDevice() { + return Device; + } + + public void setDevice(String Device) { + this.Device = Device; + } + + public String getAudioSetting() { + return AudioSetting; + } + + public void setAudioSetting(String AudioSetting) { + this.AudioSetting = AudioSetting; + } + + public String getDataSetting() { + return DataSetting; + } + + public void setDataSetting(String DataSetting) { + this.DataSetting = DataSetting; + } + + public String getIMEISetting() { + return IMEISetting; + } + + public void setIMEISetting(String IMEISetting) { + this.IMEISetting = IMEISetting; + } + + public String getIMSISetting() { + return IMSISetting; + } + + public void setIMSISetting(String IMSISetting) { + this.IMSISetting = IMSISetting; + } + + public String getChannelLanguage() { + return ChannelLanguage; + } + + public void setChannelLanguage(String ChannelLanguage) { + this.ChannelLanguage = ChannelLanguage; + } + + public String getGroup() { + return Group; + } + + public void setGroup(String Group) { + this.Group = Group; + } + + public String getRXGain() { + return RXGain; + } + + public void setRXGain(String RXGain) { + this.RXGain = RXGain; + } + + public String getTXGain() { + return TXGain; + } + + public void setTXGain(String TXGain) { + this.TXGain = TXGain; + } + + public String getU2DIAG() { + return U2DIAG; + } + + public void setU2DIAG(String U2DIAG) { + this.U2DIAG = U2DIAG; + } + + public String getUseCallingPres() { + return UseCallingPres; + } + + public void setUseCallingPres(String UseCallingPres) { + this.UseCallingPres = UseCallingPres; + } + + public String getDefaultCallingPres() { + return DefaultCallingPres; + } + + public void setDefaultCallingPres(String DefaultCallingPres) { + this.DefaultCallingPres = DefaultCallingPres; + } + + public String getAutoDeleteSMS() { + return AutoDeleteSMS; + } + + public void setAutoDeleteSMS(String AutoDeleteSMS) { + this.AutoDeleteSMS = AutoDeleteSMS; + } + + public String getDisableSMS() { + return DisableSMS; + } + + public void setDisableSMS(String DisableSMS) { + this.DisableSMS = DisableSMS; + } + + public String getResetDongle() { + return ResetDongle; + } + + public void setResetDongle(String ResetDongle) { + this.ResetDongle = ResetDongle; + } + + public String getSMSPDU() { + return SMSPDU; + } + + public void setSMSPDU(String SMSPDU) { + this.SMSPDU = SMSPDU; + } + + public String getCallWaitingSetting() { + return CallWaitingSetting; + } + + public void setCallWaitingSetting(String CallWaitingSetting) { + this.CallWaitingSetting = CallWaitingSetting; + } + + public String getDTMF() { + return DTMF; + } + + public void setDTMF(String DTMF) { + this.DTMF = DTMF; + } + + public String getMinimalDTMFGap() { + return MinimalDTMFGap; + } + + public void setMinimalDTMFGap(String MinimalDTMFGap) { + this.MinimalDTMFGap = MinimalDTMFGap; + } + + public String getMinimalDTMFDuration() { + return MinimalDTMFDuration; + } + + public void setMinimalDTMFDuration(String MinimalDTMFDuration) { + this.MinimalDTMFDuration = MinimalDTMFDuration; + } + + public String getMinimalDTMFInterval() { + return MinimalDTMFInterval; + } + + public void setMinimalDTMFInterval(String MinimalDTMFInterval) { + this.MinimalDTMFInterval = MinimalDTMFInterval; + } + + public String getState() { + return State; + } + + public void setState(String State) { + this.State = State; + } + + public String getAudioState() { + return AudioState; + } + + public void setAudioState(String AudioState) { + this.AudioState = AudioState; + } + + public String getDataState() { + return DataState; + } + + public void setDataState(String DataState) { + this.DataState = DataState; + } + + public String getVoice() { + return Voice; + } + + public void setVoice(String Voice) { + this.Voice = Voice; + } + + public String getSMS() { + return SMS; + } + + public void setSMS(String SMS) { + this.SMS = SMS; + } + + public String getManufacturer() { + return Manufacturer; + } + + public void setManufacturer(String Manufacturer) { + this.Manufacturer = Manufacturer; + } + + public String getModel() { + return Model; + } + + public void setModel(String Model) { + this.Model = Model; + } + + public String getFirmware() { + return Firmware; + } + + public void setFirmware(String Firmware) { + this.Firmware = Firmware; + } + + public String getIMEIState() { + return IMEIState; + } + + public void setIMEIState(String IMEIState) { + this.IMEIState = IMEIState; + } + + public String getGSMRegistrationStatus() { + return GSMRegistrationStatus; + } + + public void setGSMRegistrationStatus(String GSMRegistrationStatus) { + this.GSMRegistrationStatus = GSMRegistrationStatus; + } + + public String getRSSI() { + return RSSI; + } + + public void setRSSI(String RSSI) { + this.RSSI = RSSI; + } + + public String getMode() { + return Mode; + } + + public void setMode(String Mode) { + this.Mode = Mode; + } + + public String getSubmode() { + return Submode; + } + + public void setSubmode(String Submode) { + this.Submode = Submode; + } + + public String getProviderName() { + return ProviderName; + } + + public void setProviderName(String ProviderName) { + this.ProviderName = ProviderName; + } + + public String getLocationAreaCode() { + return LocationAreaCode; + } + + public void setLocationAreaCode(String LocationAreaCode) { + this.LocationAreaCode = LocationAreaCode; + } + + public String getCellID() { + return CellID; + } + + public void setCellID(String CellID) { + this.CellID = CellID; + } + + public String getSubscriberNumber() { + return SubscriberNumber; + } + + public void setSubscriberNumber(String SubscriberNumber) { + this.SubscriberNumber = SubscriberNumber; + } + + public String getSMSServiceCenter() { + return SMSServiceCenter; + } + + public void setSMSServiceCenter(String SMSServiceCenter) { + this.SMSServiceCenter = SMSServiceCenter; + } + + public String getUseUCS2Encoding() { + return UseUCS2Encoding; + } + + public void setUseUCS2Encoding(String UseUCS2Encoding) { + this.UseUCS2Encoding = UseUCS2Encoding; + } + + public String getUSSDUse7BitEncoding() { + return USSDUse7BitEncoding; + } + + public void setUSSDUse7BitEncoding(String USSDUse7BitEncoding) { + this.USSDUse7BitEncoding = USSDUse7BitEncoding; + } + + public String getUSSDUseUCS2Decoding() { + return USSDUseUCS2Decoding; + } + + public void setUSSDUseUCS2Decoding(String USSDUseUCS2Decoding) { + this.USSDUseUCS2Decoding = USSDUseUCS2Decoding; + } + + public String getTasksInQueue() { + return TasksInQueue; + } + + public void setTasksInQueue(String TasksInQueue) { + this.TasksInQueue = TasksInQueue; + } + + public String getCommandsInQueue() { + return CommandsInQueue; + } + + public void setCommandsInQueue(String CommandsInQueue) { + this.CommandsInQueue = CommandsInQueue; + } + + public String getCallWaitingState() { + return CallWaitingState; + } + + public void setCallWaitingState(String CallWaitingState) { + this.CallWaitingState = CallWaitingState; + } + + public String getCurrentDeviceState() { + return CurrentDeviceState; + } + + public void setCurrentDeviceState(String CurrentDeviceState) { + this.CurrentDeviceState = CurrentDeviceState; + } + + public String getDesiredDeviceState() { + return DesiredDeviceState; + } + + public void setDesiredDeviceState(String DesiredDeviceState) { + this.DesiredDeviceState = DesiredDeviceState; + } + + public String getCallsChannels() { + return CallsChannels; + } + + public void setCallsChannels(String CallsChannels) { + this.CallsChannels = CallsChannels; + } + + public String getActive() { + return Active; + } + + public void setActive(String Active) { + this.Active = Active; + } + + public String getHeld() { + return Held; + } + + public void setHeld(String Held) { + this.Held = Held; + } + + public String getDialing() { + return Dialing; + } + + public void setDialing(String Dialing) { + this.Dialing = Dialing; + } + + public String getAlerting() { + return Alerting; + } + + public void setAlerting(String Alerting) { + this.Alerting = Alerting; + } + + public String getIncoming() { + return Incoming; + } + + public void setIncoming(String Incoming) { + this.Incoming = Incoming; + } + + public String getWaiting() { + return Waiting; + } + + public void setWaiting(String Waiting) { + this.Waiting = Waiting; + } + + public String getReleasing() { + return Releasing; + } + + public void setReleasing(String Releasing) { + this.Releasing = Releasing; + } + + public String getInitializing() { + return Initializing; + } + + public void setInitializing(String Initializing) { + this.Initializing = Initializing; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleNewCMGREvent.java b/src/main/java/org/asteriskjava/manager/event/DongleNewCMGREvent.java new file mode 100644 index 000000000..cbc3d457a --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DongleNewCMGREvent.java @@ -0,0 +1,19 @@ +package org.asteriskjava.manager.event; + +public class DongleNewCMGREvent extends ManagerEvent { + private static final long serialVersionUID = 3257845467831284784L; + private String device; + + public DongleNewCMGREvent(Object source) { + super(source); + } + + public String getDevice() { + return this.device; + } + + public void setDevice(String device) { + this.device = device; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleNewSMSBase64Event.java b/src/main/java/org/asteriskjava/manager/event/DongleNewSMSBase64Event.java new file mode 100644 index 000000000..ba794e9e3 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DongleNewSMSBase64Event.java @@ -0,0 +1,36 @@ +package org.asteriskjava.manager.event; + +public class DongleNewSMSBase64Event extends ManagerEvent { + private static final long serialVersionUID = 3257845467831284784L; + private String from; + private String message; + private String device; + + public DongleNewSMSBase64Event(Object source) { + super(source); + } + + public String getDevice() { + return this.device; + } + + public void setDevice(String device) { + this.device = device; + } + + public String getFrom() { + return this.from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getMessage() { + return this.message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleNewSMSEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleNewSMSEvent.java new file mode 100644 index 000000000..b6d07b1f0 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DongleNewSMSEvent.java @@ -0,0 +1,48 @@ +package org.asteriskjava.manager.event; + +public class DongleNewSMSEvent extends ManagerEvent { + private static final long serialVersionUID = 3257845467831284784L; + private String from; + private String messageline0; + private String device; + private String linecount; + + + public DongleNewSMSEvent(Object source) { + super(source); + } + + public String getDevice() { + return this.device; + } + + public void setDevice(String device) { + this.device = device; + } + + public String getFrom() { + return this.from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getLinecount() { + return linecount; + } + + public void setLinecount(String linecount) { + this.linecount = linecount; + } + + public String getMessageline0() { + return messageline0; + } + + public void setMessageline0(String messageline0) { + this.messageline0 = messageline0; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleShowDevicesCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleShowDevicesCompleteEvent.java new file mode 100644 index 000000000..c61e690ea --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DongleShowDevicesCompleteEvent.java @@ -0,0 +1,85 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A DahdiShowChannelsCompleteEvent is triggered after the state of all Dahdi channels has been reported + * in response to a DahdiShowChannelsAction. + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.action.DahdiShowChannelsAction + * @see org.asteriskjava.manager.event.DahdiShowChannelsEvent + */ +public class DongleShowDevicesCompleteEvent extends ResponseEvent { + /** + * Serial version identifier + */ + private static final long serialVersionUID = 6323249250335885462L; + + private Integer listitems; + private String eventlist; + private Integer items; + + public Integer getItems() { + return items; + } + + public void setItems(Integer items) { + this.items = items; + } + + /** + * @param source + */ + public DongleShowDevicesCompleteEvent(Object source) { + super(source); + } + + /** + * Returns if the status of the eventlist (should be Complete).

      + * + * @return the status of the list. + * @since 1.0.0 + */ + public String getEventlist() { + return eventlist; + } + + public void setEventlist(String eventlist) { + this.eventlist = eventlist; + } + + /** + * Returns the number of channels reported.

      + * + * @return the number of channels reported. + */ + public Integer getListitems() { + return listitems; + } + + /** + * Sets the number of channels reported.

      + * + * @param listitems the number of channels reported. + */ + public void setListitems(Integer listitems) { + this.listitems = listitems; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleStatusEvent.java new file mode 100644 index 000000000..6ea1c24d6 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DongleStatusEvent.java @@ -0,0 +1,29 @@ +package org.asteriskjava.manager.event; + +public class DongleStatusEvent extends ManagerEvent { + private static final long serialVersionUID = 3257845467831284784L; + private String device; + private String status; + + public DongleStatusEvent(Object source) { + super(source); + } + + public String getDevice() { + return this.device; + } + + public void setDevice(String device) { + this.device = device; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/DtmfBeginEvent.java b/src/main/java/org/asteriskjava/manager/event/DtmfBeginEvent.java new file mode 100644 index 000000000..eee04cc48 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DtmfBeginEvent.java @@ -0,0 +1,17 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public class DtmfBeginEvent extends DtmfEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + + public DtmfBeginEvent(Object source) { + super(source); + setBegin(true); + setEnd(false); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/DtmfEndEvent.java b/src/main/java/org/asteriskjava/manager/event/DtmfEndEvent.java new file mode 100644 index 000000000..245847d22 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/DtmfEndEvent.java @@ -0,0 +1,26 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public class DtmfEndEvent extends DtmfEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + private Integer durationMs; + + public DtmfEndEvent(Object source) { + super(source); + setBegin(false); + setEnd(true); + } + + public Integer getDurationMs() { + return durationMs; + } + + public void setDurationMs(Integer durationMs) { + this.durationMs = durationMs; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/DtmfEvent.java b/src/main/java/org/asteriskjava/manager/event/DtmfEvent.java index 1f1d57537..14b107a8c 100644 --- a/src/main/java/org/asteriskjava/manager/event/DtmfEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DtmfEvent.java @@ -29,7 +29,7 @@ * Generally it is safe to just ignore them and only react on AST_FRAME_DTMF_END frames.
      * To check whether an DtmfEvent represents an AST_FRAME_DTMF_BEGIN or * AST_FRAME_DTMF_END frame use the {@link #isBegin()} and {@link #isEnd()} methods. - *

      + *
      * You can find more information on how Asterisk handles DTMF in the * DTMF article at voip-info.org

      * It is implemented in main/channel.c.

      @@ -39,12 +39,11 @@ * @version $Id$ * @since 1.0.0 */ -public class DtmfEvent extends ManagerEvent -{ +public class DtmfEvent extends ManagerEvent { /** * Serializable version identifier. */ - static final long serialVersionUID = 0L; + static final long serialVersionUID = 1L; public static final String DIRECTION_RECEIVED = "Received"; public static final String DIRECTION_SENT = "Sent"; @@ -56,13 +55,16 @@ public class DtmfEvent extends ManagerEvent private Boolean begin; private Boolean end; + private String language; + private String linkedId; + private String accountCode; + /** * Creates a new DtmfEvent. * * @param source */ - public DtmfEvent(Object source) - { + public DtmfEvent(Object source) { super(source); } @@ -72,8 +74,7 @@ public DtmfEvent(Object source) * * @return the channel name. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -82,8 +83,7 @@ public String getChannel() * * @param channel the channel name. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -92,8 +92,7 @@ public void setChannel(String channel) * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -102,8 +101,7 @@ public String getUniqueId() * * @param uniqueId the unique id of the the channel. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -112,8 +110,7 @@ public void setUniqueId(String uniqueId) * * @return the DTMF digit that was sent or received. */ - public String getDigit() - { + public String getDigit() { return digit; } @@ -122,8 +119,7 @@ public String getDigit() * * @param digit the DTMF digit that was sent or received. */ - public void setDigit(String digit) - { + public void setDigit(String digit) { this.digit = digit; } @@ -136,12 +132,11 @@ public void setDigit(String digit) *

    * * @return "Reveived" if the DTMF was received (sent from the device to Asterisk) or "Sent" if the DTMF - * digit was sent (sent from Asterisk to the device). + * digit was sent (sent from Asterisk to the device). * @see #DIRECTION_RECEIVED * @see #DIRECTION_SENT */ - public String getDirection() - { + public String getDirection() { return direction; } @@ -150,8 +145,7 @@ public String getDirection() * * @param direction "Received" or "Sent". */ - public void setDirection(String direction) - { + public void setDirection(String direction) { this.direction = direction; } @@ -164,10 +158,9 @@ public void setDirection(String direction) * DTMF. * * @return true if this is a DTMF begin event (key pressed), - * false otherwise. + * false otherwise. */ - public Boolean isBegin() - { + public Boolean isBegin() { return begin != null && begin; } @@ -177,8 +170,7 @@ public Boolean isBegin() * @param begin true if this is a DTMF begin event (key pressed), * false otherwise. */ - public void setBegin(Boolean begin) - { + public void setBegin(Boolean begin) { this.begin = begin; } @@ -188,10 +180,9 @@ public void setBegin(Boolean begin) * DTMF you will only see DTMF end events. * * @return true if this is a DTMF end event (key released), - * false otherwise. + * false otherwise. */ - public boolean isEnd() - { + public boolean isEnd() { return end != null && end; } @@ -201,8 +192,7 @@ public boolean isEnd() * @param end true if this is a DTMF end event (key released), * false otherwise. */ - public void setEnd(Boolean end) - { + public void setEnd(Boolean end) { this.end = end; } @@ -210,23 +200,47 @@ public void setEnd(Boolean end) * Returns whether the DTMF digit was received by Asterisk (sent from the device to Asterisk). * * @return true if the DTMF digit was received by Asterisk, - * false otherwise. + * false otherwise. * @see #getDirection() */ - public boolean isReceived() - { - return direction != null && DIRECTION_RECEIVED.equalsIgnoreCase(direction); + public boolean isReceived() { + return DIRECTION_RECEIVED.equalsIgnoreCase(direction); } /** * Returns whether the DTMF digit was sent from Asterisk to the device. * * @return true if the DTMF digit was sent from Asterisk to the device, - * false otherwise. + * false otherwise. * @see #getDirection() */ - public boolean isSent() - { - return direction != null && DIRECTION_SENT.equalsIgnoreCase(direction); + public boolean isSent() { + return DIRECTION_SENT.equalsIgnoreCase(direction); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; } -} \ No newline at end of file + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/EndpointDetail.java b/src/main/java/org/asteriskjava/manager/event/EndpointDetail.java new file mode 100644 index 000000000..b2aa6408f --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/EndpointDetail.java @@ -0,0 +1,1133 @@ +package org.asteriskjava.manager.event; + +/** + * A EndpointDetail event is triggered in response to a + * {@link org.asteriskjava.manager.action.PJSipShowEndpoint}, and contains + * information about a PJSIP endpoint + *

    + * + * @author Steve Sether + * @version $Id$ + * @since 12 + */ + +public class EndpointDetail extends ResponseEvent { + + /** + * Serial version identifier. + */ + private static final long serialVersionUID = 77481930059189731L; + private Integer listItems; + private String eventList; + + public Integer getListItems() { + return listItems; + } + + public void setListItems(Integer listItems) { + this.listItems = listItems; + } + + public String getEventList() { + return eventList; + } + + public void setEventList(String eventList) { + this.eventList = eventList; + } + + private String objectName; + private String objectType; + private Boolean rpidImmediate; + private Boolean webrtc; + private Boolean ignorel83WithoutSdp; + private int deviceStateBusyAt; + private int t38UdptlMaxdatagram; + private int dtlsRekey; + private String namedPickupGroup; + private String directMediaMethod; + private Boolean sendRpid; + private String pickupGroup; + private String sdpSession; + private String dtlsVerify; + private String messageContext; + private String mailboxes; + private String recordOnFeature; + private String dtlsPrivateKey; + private String dtlsFingerprint; + private String fromDomain; + private int timersSessExpires; + private String namedCallGroup; + private String dtlsCipher; + private Boolean mediaEncryptionOptimistic; + private Boolean suppressQ850ReasonHeaders; + private String aors; + private String identifyBy; + private String calleridPrivacy; + private String mwiSubscribeReplacesUnsolicited; + private String cosAudio; + private Boolean followEarlyMediaFork; + private String context; + private Boolean rtpSymmetric; + private String transport; + private String mohSuggest; + private Boolean t38Udptl; + private Boolean faxDetect; + private String tosVideo; + private Boolean srtpTag32; + private Boolean referBlindProgress; + private int maxAudioStreams; + private Boolean bundle; + private Boolean useAvpf; + private String callGroup; + private Boolean sendConnectedLine; + private int faxDetectTimeout; + private String sdpOwner; + private Boolean forceRport; + private String calleridTag; + private int rtpTimeoutHold; + private Boolean usePtime; + private String mediaAddress; + private String voicemailExtension; + private int rtpTimeout; + private String setVar; + private String contactAcl; + private Boolean preferredCodecOnly; + private Boolean forceAvp; + private String recordOffFeature; + private String fromUser; + private Boolean sendDiversion; + private Boolean t38UdptlIpv6; + private String toneZone; + private String language; + private Boolean allowSubscribe; + private Boolean rtpIpv6; + private String callerid; + private Boolean mohPassthrough; + private String cosVideo; + private String dtlsAutoGenerateCert; + private Boolean asymmetricRtpCodec; + private Boolean iceSupport; + private Boolean aggregateMwi; + private Boolean oneTouchRecording; + private String mwiFromUser; + private String accountcode; + private String allow; + private Boolean rewriteContact; + private Boolean userEqPhone; + private String rtpEngine; + private String subscribeContext; + private Boolean notifyEarlyInuseRinging; + private String incomingMwiMailbox; + private String auth; + private String directMediaGlareMitigation; + private Boolean trustIdInbound; + private Boolean bindRtpToMediaAddress; + private Boolean disableDirectMediaOnNat; + private Boolean mediaEncryption; + private Boolean mediaUseReceivedTransport; + private Boolean allowOverlap; + private String dtmfMode; + private String outboundAuth; + private String tosAudio; + private String dtlsCertFile; + private String dtlsCaPath; + private String dtlsSetup; + private String connectedLineMethod; + private Boolean g726NonStandard; + private String _100rel; + private String timers; + private Boolean directMedia; + private String acl; + private int timersMinSe; + private Boolean trustIdOutbound; + private int subMinExpiry; + private Boolean rtcpMux; + private int maxVideoStreams; + private Boolean acceptMultipleSdpAnswers; + private Boolean trustConnectedLine; + private Boolean sendPai; + private int rtpKeepalive; + private String t38UdptlEc; + private Boolean t38UdptlNat; + private Boolean allowTransfer; + private String dtlsCaFile; + private String outboundProxy; + private Boolean inbandProgress; + private String deviceState; + private String activeChannels; + private Boolean ignore183withoutsdp; + + public int getMaxVideoStreams() { + return maxVideoStreams; + } + + public void setMaxVideoStreams(int maxVideoStreams) { + this.maxVideoStreams = maxVideoStreams; + } + + public String getObjectName() { + return objectName; + } + + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + public Boolean isRpidImmediate() { + return rpidImmediate; + } + + public void setRpidImmediate(Boolean rpidImmediate) { + this.rpidImmediate = rpidImmediate; + } + + public Boolean isWebrtc() { + return webrtc; + } + + public void setWebrtc(Boolean webrtc) { + this.webrtc = webrtc; + } + + public Boolean isIgnorel83WithoutSdp() { + return ignorel83WithoutSdp; + } + + public void setIgnorel83WithoutSdp(Boolean ignorel83WithoutSdp) { + this.ignorel83WithoutSdp = ignorel83WithoutSdp; + } + + public int getDeviceStateBusyAt() { + return deviceStateBusyAt; + } + + public void setDeviceStateBusyAt(int deviceStateBusyAt) { + this.deviceStateBusyAt = deviceStateBusyAt; + } + + public int getT38UdptlMaxdatagram() { + return t38UdptlMaxdatagram; + } + + public void setT38UdptlMaxdatagram(int t38UdptlMaxdatagram) { + this.t38UdptlMaxdatagram = t38UdptlMaxdatagram; + } + + public int getDtlsRekey() { + return dtlsRekey; + } + + public void setDtlsRekey(int dtlsRekey) { + this.dtlsRekey = dtlsRekey; + } + + public String getNamedPickupGroup() { + return namedPickupGroup; + } + + public void setNamedPickupGroup(String namedPickupGroup) { + this.namedPickupGroup = namedPickupGroup; + } + + public String getDirectMediaMethod() { + return directMediaMethod; + } + + public void setDirectMediaMethod(String directMediaMethod) { + this.directMediaMethod = directMediaMethod; + } + + public Boolean isSendRpid() { + return sendRpid; + } + + public void setSendRpid(Boolean sendRpid) { + this.sendRpid = sendRpid; + } + + public String getPickupGroup() { + return pickupGroup; + } + + public void setPickupGroup(String pickupGroup) { + this.pickupGroup = pickupGroup; + } + + public String getSdpSession() { + return sdpSession; + } + + public void setSdpSession(String sdpSession) { + this.sdpSession = sdpSession; + } + + public String getDtlsVerify() { + return dtlsVerify; + } + + public void setDtlsVerify(String dtlsVerify) { + this.dtlsVerify = dtlsVerify; + } + + public String getMessageContext() { + return messageContext; + } + + public void setMessageContext(String messageContext) { + this.messageContext = messageContext; + } + + public String getMailboxes() { + return mailboxes; + } + + public void setMailboxes(String mailboxes) { + this.mailboxes = mailboxes; + } + + public String getRecordOnFeature() { + return recordOnFeature; + } + + public void setRecordOnFeature(String recordOnFeature) { + this.recordOnFeature = recordOnFeature; + } + + public String getDtlsPrivateKey() { + return dtlsPrivateKey; + } + + public void setDtlsPrivateKey(String dtlsPrivateKey) { + this.dtlsPrivateKey = dtlsPrivateKey; + } + + public String getDtlsFingerprint() { + return dtlsFingerprint; + } + + public void setDtlsFingerprint(String dtlsFingerprint) { + this.dtlsFingerprint = dtlsFingerprint; + } + + public String getFromDomain() { + return fromDomain; + } + + public void setFromDomain(String fromDomain) { + this.fromDomain = fromDomain; + } + + public int getTimersSessExpires() { + return timersSessExpires; + } + + public void setTimersSessExpires(int timersSessExpires) { + this.timersSessExpires = timersSessExpires; + } + + public String getNamedCallGroup() { + return namedCallGroup; + } + + public void setNamedCallGroup(String namedCallGroup) { + this.namedCallGroup = namedCallGroup; + } + + public String getDtlsCipher() { + return dtlsCipher; + } + + public void setDtlsCipher(String dtlsCipher) { + this.dtlsCipher = dtlsCipher; + } + + public Boolean isMediaEncryptionOptimistic() { + return mediaEncryptionOptimistic; + } + + public void setMediaEncryptionOptimistic(Boolean mediaEncryptionOptimistic) { + this.mediaEncryptionOptimistic = mediaEncryptionOptimistic; + } + + public Boolean isSuppressQ850ReasonHeaders() { + return suppressQ850ReasonHeaders; + } + + public void setSuppressQ850ReasonHeaders(Boolean suppressQ850ReasonHeaders) { + this.suppressQ850ReasonHeaders = suppressQ850ReasonHeaders; + } + + public String getAors() { + return aors; + } + + public void setAors(String aors) { + this.aors = aors; + } + + public String getIdentifyBy() { + return identifyBy; + } + + public void setIdentifyBy(String identifyBy) { + this.identifyBy = identifyBy; + } + + public String getCalleridPrivacy() { + return calleridPrivacy; + } + + public void setCalleridPrivacy(String calleridPrivacy) { + this.calleridPrivacy = calleridPrivacy; + } + + public String getMwiSubscribeReplacesUnsolicited() { + return mwiSubscribeReplacesUnsolicited; + } + + public void setMwiSubscribeReplacesUnsolicited(String mwiSubscribeReplacesUnsolicited) { + this.mwiSubscribeReplacesUnsolicited = mwiSubscribeReplacesUnsolicited; + } + + public Boolean isFollowEarlyMediaFork() { + return followEarlyMediaFork; + } + + public void setFollowEarlyMediaFork(Boolean followEarlyMediaFork) { + this.followEarlyMediaFork = followEarlyMediaFork; + } + + public String getContext() { + return context; + } + + public void setContext(String context) { + this.context = context; + } + + public Boolean isRtpSymmetric() { + return rtpSymmetric; + } + + public void setRtpSymmetric(Boolean rtpSymmetric) { + this.rtpSymmetric = rtpSymmetric; + } + + public String getTransport() { + return transport; + } + + public void setTransport(String transport) { + this.transport = transport; + } + + public String getMohSuggest() { + return mohSuggest; + } + + public void setMohSuggest(String mohSuggest) { + this.mohSuggest = mohSuggest; + } + + public Boolean isT38Udptl() { + return t38Udptl; + } + + public void setT38Udptl(Boolean t38Udptl) { + this.t38Udptl = t38Udptl; + } + + public Boolean isFaxDetect() { + return faxDetect; + } + + public void setFaxDetect(Boolean faxDetect) { + this.faxDetect = faxDetect; + } + + public Boolean getSrtpTag32() { + return srtpTag32; + } + + public void setSrtpTag32(Boolean srtpTag32) { + this.srtpTag32 = srtpTag32; + } + + public Boolean isReferBlindProgress() { + return referBlindProgress; + } + + public void setReferBlindProgress(Boolean referBlindProgress) { + this.referBlindProgress = referBlindProgress; + } + + public int getMaxAudioStreams() { + return maxAudioStreams; + } + + public void setMaxAudioStreams(int maxAudioStreams) { + this.maxAudioStreams = maxAudioStreams; + } + + public Boolean isBundle() { + return bundle; + } + + public void setBundle(Boolean bundle) { + this.bundle = bundle; + } + + public Boolean isUseAvpf() { + return useAvpf; + } + + public void setUseAvpf(Boolean useAvpf) { + this.useAvpf = useAvpf; + } + + public String getCallGroup() { + return callGroup; + } + + public void setCallGroup(String callGroup) { + this.callGroup = callGroup; + } + + public Boolean isSendConnectedLine() { + return sendConnectedLine; + } + + public void setSendConnectedLine(Boolean sendConnectedLine) { + this.sendConnectedLine = sendConnectedLine; + } + + public int getFaxDetectTimeout() { + return faxDetectTimeout; + } + + public void setFaxDetectTimeout(int faxDetectTimeout) { + this.faxDetectTimeout = faxDetectTimeout; + } + + public String getSdpOwner() { + return sdpOwner; + } + + public void setSdpOwner(String sdpOwner) { + this.sdpOwner = sdpOwner; + } + + public Boolean isForceRport() { + return forceRport; + } + + public void setForceRport(Boolean forceRport) { + this.forceRport = forceRport; + } + + public String getCalleridTag() { + return calleridTag; + } + + public void setCalleridTag(String calleridTag) { + this.calleridTag = calleridTag; + } + + public int getRtpTimeoutHold() { + return rtpTimeoutHold; + } + + public void setRtpTimeoutHold(int rtpTimeoutHold) { + this.rtpTimeoutHold = rtpTimeoutHold; + } + + public Boolean isUsePtime() { + return usePtime; + } + + public void setUsePtime(Boolean usePtime) { + this.usePtime = usePtime; + } + + public String getMediaAddress() { + return mediaAddress; + } + + public void setMediaAddress(String mediaAddress) { + this.mediaAddress = mediaAddress; + } + + public String getVoicemailExtension() { + return voicemailExtension; + } + + public void setVoicemailExtension(String voicemailExtension) { + this.voicemailExtension = voicemailExtension; + } + + public int getRtpTimeout() { + return rtpTimeout; + } + + public void setRtpTimeout(int rtpTimeout) { + this.rtpTimeout = rtpTimeout; + } + + public String getSetVar() { + return setVar; + } + + public void setSetVar(String setVar) { + this.setVar = setVar; + } + + public String getContactAcl() { + return contactAcl; + } + + public void setContactAcl(String contactAcl) { + this.contactAcl = contactAcl; + } + + public Boolean isPreferredCodecOnly() { + return preferredCodecOnly; + } + + public void setPreferredCodecOnly(Boolean preferredCodecOnly) { + this.preferredCodecOnly = preferredCodecOnly; + } + + public Boolean isForceAvp() { + return forceAvp; + } + + public void setForceAvp(Boolean forceAvp) { + this.forceAvp = forceAvp; + } + + public String getRecordOffFeature() { + return recordOffFeature; + } + + public void setRecordOffFeature(String recordOffFeature) { + this.recordOffFeature = recordOffFeature; + } + + public String getFromUser() { + return fromUser; + } + + public void setFromUser(String fromUser) { + this.fromUser = fromUser; + } + + public Boolean isSendDiversion() { + return sendDiversion; + } + + public void setSendDiversion(Boolean sendDiversion) { + this.sendDiversion = sendDiversion; + } + + public Boolean isT38UdptlIpv6() { + return t38UdptlIpv6; + } + + public void setT38UdptlIpv6(Boolean t38UdptlIpv6) { + this.t38UdptlIpv6 = t38UdptlIpv6; + } + + public String getToneZone() { + return toneZone; + } + + public void setToneZone(String toneZone) { + this.toneZone = toneZone; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public Boolean isAllowSubscribe() { + return allowSubscribe; + } + + public void setAllowSubscribe(Boolean allowSubscribe) { + this.allowSubscribe = allowSubscribe; + } + + public Boolean isRtpIpv6() { + return rtpIpv6; + } + + public void setRtpIpv6(Boolean rtpIpv6) { + this.rtpIpv6 = rtpIpv6; + } + + public String getCallerid() { + return callerid; + } + + public void setCallerid(String callerid) { + this.callerid = callerid; + } + + public Boolean isMohPassthrough() { + return mohPassthrough; + } + + public void setMohPassthrough(Boolean mohPassthrough) { + this.mohPassthrough = mohPassthrough; + } + + public String getCosAudio() { + return cosAudio; + } + + public void setCosAudio(String cosAudio) { + this.cosAudio = cosAudio; + } + + public String getCosVideo() { + return cosVideo; + } + + public void setCosVideo(String cosVideo) { + this.cosVideo = cosVideo; + } + + public String getDtlsAutoGenerateCert() { + return dtlsAutoGenerateCert; + } + + public void setDtlsAutoGenerateCert(String dtlsAutoGenerateCert) { + this.dtlsAutoGenerateCert = dtlsAutoGenerateCert; + } + + public Boolean isAsymmetricRtpCodec() { + return asymmetricRtpCodec; + } + + public void setAsymmetricRtpCodec(Boolean asymmetricRtpCodec) { + this.asymmetricRtpCodec = asymmetricRtpCodec; + } + + public Boolean isIceSupport() { + return iceSupport; + } + + public void setIceSupport(Boolean iceSupport) { + this.iceSupport = iceSupport; + } + + public Boolean isAggregateMwi() { + return aggregateMwi; + } + + public void setAggregateMwi(Boolean aggregateMwi) { + this.aggregateMwi = aggregateMwi; + } + + public Boolean isOneTouchRecording() { + return oneTouchRecording; + } + + public void setOneTouchRecording(Boolean oneTouchRecording) { + this.oneTouchRecording = oneTouchRecording; + } + + public String getMwiFromUser() { + return mwiFromUser; + } + + public void setMwiFromUser(String mwiFromUser) { + this.mwiFromUser = mwiFromUser; + } + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } + + public String getAllow() { + return allow; + } + + public void setAllow(String allow) { + this.allow = allow; + } + + public Boolean isRewriteContact() { + return rewriteContact; + } + + public void setRewriteContact(Boolean rewriteContact) { + this.rewriteContact = rewriteContact; + } + + public Boolean isUserEqPhone() { + return userEqPhone; + } + + public void setUserEqPhone(Boolean userEqPhone) { + this.userEqPhone = userEqPhone; + } + + public String getRtpEngine() { + return rtpEngine; + } + + public void setRtpEngine(String rtpEngine) { + this.rtpEngine = rtpEngine; + } + + public String getSubscribeContext() { + return subscribeContext; + } + + public void setSubscribeContext(String subscribeContext) { + this.subscribeContext = subscribeContext; + } + + public Boolean isNotifyEarlyInuseRinging() { + return notifyEarlyInuseRinging; + } + + public void setNotifyEarlyInuseRinging(Boolean notifyEarlyInuseRinging) { + this.notifyEarlyInuseRinging = notifyEarlyInuseRinging; + } + + public String getIncomingMwiMailbox() { + return incomingMwiMailbox; + } + + public void setIncomingMwiMailbox(String incomingMwiMailbox) { + this.incomingMwiMailbox = incomingMwiMailbox; + } + + public String getAuth() { + return auth; + } + + public void setAuth(String auth) { + this.auth = auth; + } + + public String getDirectMediaGlareMitigation() { + return directMediaGlareMitigation; + } + + public void setDirectMediaGlareMitigation(String directMediaGlareMitigation) { + this.directMediaGlareMitigation = directMediaGlareMitigation; + } + + public Boolean isTrustIdInbound() { + return trustIdInbound; + } + + public void setTrustIdInbound(Boolean trustIdInbound) { + this.trustIdInbound = trustIdInbound; + } + + public Boolean isBindRtpToMediaAddress() { + return bindRtpToMediaAddress; + } + + public void setBindRtpToMediaAddress(Boolean bindRtpToMediaAddress) { + this.bindRtpToMediaAddress = bindRtpToMediaAddress; + } + + public Boolean isDisableDirectMediaOnNat() { + return disableDirectMediaOnNat; + } + + public void setDisableDirectMediaOnNat(Boolean disableDirectMediaOnNat) { + this.disableDirectMediaOnNat = disableDirectMediaOnNat; + } + + public Boolean isMediaEncryption() { + return mediaEncryption; + } + + public void setMediaEncryption(Boolean mediaEncryption) { + this.mediaEncryption = mediaEncryption; + } + + public Boolean isMediaUseReceivedTransport() { + return mediaUseReceivedTransport; + } + + public void setMediaUseReceivedTransport(Boolean mediaUseReceivedTransport) { + this.mediaUseReceivedTransport = mediaUseReceivedTransport; + } + + public Boolean isAllowOverlap() { + return allowOverlap; + } + + public void setAllowOverlap(Boolean allowOverlap) { + this.allowOverlap = allowOverlap; + } + + public String getDtmfMode() { + return dtmfMode; + } + + public void setDtmfMode(String dtmfMode) { + this.dtmfMode = dtmfMode; + } + + public String getOutboundAuth() { + return outboundAuth; + } + + public void setOutboundAuth(String outboundAuth) { + this.outboundAuth = outboundAuth; + } + + public String getTosVideo() { + return tosVideo; + } + + public void setTosVideo(String tosVideo) { + this.tosVideo = tosVideo; + } + + public String getTosAudio() { + return tosAudio; + } + + public void setTosAudio(String tosAudio) { + this.tosAudio = tosAudio; + } + + public String getDtlsCertFile() { + return dtlsCertFile; + } + + public void setDtlsCertFile(String dtlsCertFile) { + this.dtlsCertFile = dtlsCertFile; + } + + public String getDtlsCaPath() { + return dtlsCaPath; + } + + public void setDtlsCaPath(String dtlsCaPath) { + this.dtlsCaPath = dtlsCaPath; + } + + public String getDtlsSetup() { + return dtlsSetup; + } + + public void setDtlsSetup(String dtlsSetup) { + this.dtlsSetup = dtlsSetup; + } + + public String getConnectedLineMethod() { + return connectedLineMethod; + } + + public void setConnectedLineMethod(String connectedLineMethod) { + this.connectedLineMethod = connectedLineMethod; + } + + public Boolean isG726NonStandard() { + return g726NonStandard; + } + + public void setG726NonStandard(Boolean g726NonStandard) { + this.g726NonStandard = g726NonStandard; + } + + public String get100rel() { + return _100rel; + } + + public void set100rel(String _100rel) { + this._100rel = _100rel; + } + + public String getTimers() { + return timers; + } + + public void setTimers(String timers) { + this.timers = timers; + } + + public Boolean isDirectMedia() { + return directMedia; + } + + public void setDirectMedia(Boolean directMedia) { + this.directMedia = directMedia; + } + + public String getAcl() { + return acl; + } + + public void setAcl(String acl) { + this.acl = acl; + } + + public int getTimersMinSe() { + return timersMinSe; + } + + public void setTimersMinSe(int timersMinSe) { + this.timersMinSe = timersMinSe; + } + + public Boolean isTrustIdOutbound() { + return trustIdOutbound; + } + + public void setTrustIdOutbound(Boolean trustIdOutbound) { + this.trustIdOutbound = trustIdOutbound; + } + + public int getSubMinExpiry() { + return subMinExpiry; + } + + public void setSubMinExpiry(int subMinExpiry) { + this.subMinExpiry = subMinExpiry; + } + + public Boolean isRtcpMux() { + return rtcpMux; + } + + public void setRtcpMux(Boolean rtcpMux) { + this.rtcpMux = rtcpMux; + } + + public Boolean isAcceptMultipleSdpAnswers() { + return acceptMultipleSdpAnswers; + } + + public void setAcceptMultipleSdpAnswers(Boolean acceptMultipleSdpAnswers) { + this.acceptMultipleSdpAnswers = acceptMultipleSdpAnswers; + } + + public Boolean isTrustConnectedLine() { + return trustConnectedLine; + } + + public void setTrustConnectedLine(Boolean trustConnectedLine) { + this.trustConnectedLine = trustConnectedLine; + } + + public Boolean isSendPai() { + return sendPai; + } + + public void setSendPai(Boolean sendPai) { + this.sendPai = sendPai; + } + + public int getRtpKeepalive() { + return rtpKeepalive; + } + + public void setRtpKeepalive(int rtpKeepalive) { + this.rtpKeepalive = rtpKeepalive; + } + + public String getT38UdptlEc() { + return t38UdptlEc; + } + + public void setT38UdptlEc(String t38UdptlEc) { + this.t38UdptlEc = t38UdptlEc; + } + + public Boolean isT38UdptlNat() { + return t38UdptlNat; + } + + public void setT38UdptlNat(Boolean t38UdptlNat) { + this.t38UdptlNat = t38UdptlNat; + } + + public Boolean isAllowTransfer() { + return allowTransfer; + } + + public void setAllowTransfer(Boolean allowTransfer) { + this.allowTransfer = allowTransfer; + } + + public String getDtlsCaFile() { + return dtlsCaFile; + } + + public void setDtlsCaFile(String dtlsCaFile) { + this.dtlsCaFile = dtlsCaFile; + } + + public String getOutboundProxy() { + return outboundProxy; + } + + public void setOutboundProxy(String outboundProxy) { + this.outboundProxy = outboundProxy; + } + + public Boolean isInbandProgress() { + return inbandProgress; + } + + public void setInbandProgress(Boolean inbandProgress) { + this.inbandProgress = inbandProgress; + } + + public String getDeviceState() { + return deviceState; + } + + public void setDeviceState(String deviceState) { + this.deviceState = deviceState; + } + + public String getActiveChannels() { + return activeChannels; + } + + public void setActiveChannels(String activeChannels) { + this.activeChannels = activeChannels; + } + + public EndpointDetail(Object source) { + super(source); + } + + public Boolean getIgnore183withoutsdp() { + return ignore183withoutsdp; + } + + public void setIgnore183withoutsdp(Boolean ignore183withoutsdp) { + this.ignore183withoutsdp = ignore183withoutsdp; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/EndpointDetailComplete.java b/src/main/java/org/asteriskjava/manager/event/EndpointDetailComplete.java new file mode 100644 index 000000000..f1c07eac2 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/EndpointDetailComplete.java @@ -0,0 +1,81 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * An EndpointDetailComplete event is triggered after the details of an endpoint has been + * reported in response to a PJSIPShowEndpoint + *

    + * Available since Asterisk 12 + * + * @author Steve Sether + * @version $Id$ + * @see org.asteriskjava.manager.event.PJSIpShowEndpoint + * @since 12 + */ +public class EndpointDetailComplete extends ResponseEvent { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = -1177773673509373296L; + private Integer listItems; + private String eventList; + + /** + * Creates a new instance. + * + * @param source + */ + public EndpointDetailComplete(Object source) { + super(source); + } + + /** + * Returns the number of EndpointDetail events that have been reported. + * + * @return the number of EndpointDetail events that have been reported. + */ + public Integer getListItems() { + return listItems; + } + + /** + * Sets the number of EndpointDetail events that have been reported. + * + * @param listItems the number of EndpointDetail events that have been reported. + */ + public void setListItems(Integer listItems) { + this.listItems = listItems; + } + + /** + * Returns always "Complete". + *

    + * Available since Asterisk 12. + * + * @return always returns "Complete" confirming that all EndpointDetail events have + * been sent. + * @since 12 + */ + public String getEventList() { + return eventList; + } + + public void setEventList(String eventList) { + this.eventList = eventList; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/EndpointList.java b/src/main/java/org/asteriskjava/manager/event/EndpointList.java new file mode 100644 index 000000000..3781a4cf1 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/EndpointList.java @@ -0,0 +1,174 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A PeerlistCompleteEvent is triggered after the details of all peers has been + * reported in response to an SIPPeersAction or SIPShowPeerAction. + *

    + * Available since Asterisk 1.2 + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.event.PeerEntryEvent + * @see org.asteriskjava.manager.action.SipPeersAction + * @see org.asteriskjava.manager.action.SipShowPeerAction + * @since 0.2 + */ +public class EndpointList extends ResponseEvent { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = -1177773673509373296L; + private Integer listItems; + private String eventList; + + private String aor; + private String auths; + private String objectName; + private String activeChannels; + private String transport; + private String outboundAuths; + private String devicestate; + private String event; + private String objectType; + private String contacts; + + /** + * Creates a new instance. + * + * @param source + */ + public EndpointList(Object source) { + super(source); + } + + /** + * Returns the number of PeerEvents that have been reported. + * + * @return the number of PeerEvents that have been reported. + */ + public Integer getListItems() { + return listItems; + } + + /** + * Sets the number of PeerEvents that have been reported. + * + * @param listItems the number of PeerEvents that have been reported. + */ + public void setListItems(Integer listItems) { + this.listItems = listItems; + } + + /** + * Returns always "Complete". + *

    + * Available since Asterisk 1.6. + * + * @return always returns "Complete" confirming that all PeerEntry events have + * been sent. + * @since 1.0.0 + */ + public String getEventList() { + return eventList; + } + + public void setEventList(String eventList) { + this.eventList = eventList; + } + + public String getAor() { + return aor; + } + + public void setAor(String aor) { + this.aor = aor; + } + + public String getAuths() { + return auths; + } + + public void setAuths(String auths) { + this.auths = auths; + } + + public String getObjectName() { + return objectName; + } + + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + public String getTransport() { + return transport; + } + + public void setTransport(String transport) { + this.transport = transport; + } + + public String getOutboundAuths() { + return outboundAuths; + } + + public void setOutboundAuths(String outboundAuths) { + this.outboundAuths = outboundAuths; + } + + public String getDevicestate() { + return devicestate; + } + + public void setDevicestate(String devicestate) { + this.devicestate = devicestate; + } + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + public String getContacts() { + return contacts; + } + + public void setContacts(String contacts) { + this.contacts = contacts; + } + + public String getActiveChannels() { + return activeChannels; + } + + public void setActiveChannels(String activeChannels) { + this.activeChannels = activeChannels; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/EndpointListComplete.java b/src/main/java/org/asteriskjava/manager/event/EndpointListComplete.java new file mode 100644 index 000000000..432a2de94 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/EndpointListComplete.java @@ -0,0 +1,81 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * An EndpointListComplete event is triggered after the details of all end points have been + * reported in response to a PJSIPShowEndpoints event. + *

    + * Available since Asterisk 12 + * + * @author srt + * @version $Id$ + * @see org.asteriskjava.manager.event.PJSipShowEndpoints + * @since 12 + */ +public class EndpointListComplete extends ResponseEvent { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = -1177773673509373296L; + private Integer listItems; + private String eventList; + + /** + * Creates a new instance. + * + * @param source + */ + public EndpointListComplete(Object source) { + super(source); + } + + /** + * Returns the number of Endpoints that have been reported. + * + * @return the number of Endpoints that have been reported. + */ + public Integer getListItems() { + return listItems; + } + + /** + * Sets the number of Endpoints that have been reported. + * + * @param listItems the number of PeerEvents that have been reported. + */ + public void setListItems(Integer listItems) { + this.listItems = listItems; + } + + /** + * Returns always "Complete". + *

    + * Available since Asterisk 1.6. + * + * @return always returns "Complete" confirming that all PeerEntry events have + * been sent. + * @since 1.0.0 + */ + public String getEventList() { + return eventList; + } + + public void setEventList(String eventList) { + this.eventList = eventList; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ExtensionStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/ExtensionStatusEvent.java index 4ca352079..037d273a1 100644 --- a/src/main/java/org/asteriskjava/manager/event/ExtensionStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ExtensionStatusEvent.java @@ -20,21 +20,20 @@ * An ExtensionStatusEvent is triggered when the state of an extension changes.

    * For this to work for you must provide appropriate hints in your dialplan to * map channels to extensions. - *

    + *
    * Example: - *

    exten => 1234,1,Dial(SIP/myuser)
    - * exten => 1234,hint,SIP/myuser
    + *
    exten => 1234,1,Dial(SIP/myuser)
    + * exten => 1234,hint,SIP/myuser
    * Hints can also be used to map the state of multiple channels to an extension: - *
    exten => 6789,hint,SIP/user1&SIP/user2
    - * 

    + *

    exten => 6789,hint,SIP/user1&SIP/user2
    + *
    * It is implemented in manager.c, values for state are defined in * include/asterisk/pbx.h. * * @author srt * @version $Id$ */ -public class ExtensionStatusEvent extends ManagerEvent -{ +public class ExtensionStatusEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -65,47 +64,14 @@ public class ExtensionStatusEvent extends ManagerEvent */ public static final int RINGING = 1 << 3; - private String exten; - private String context; private String hint; private Integer status; private String callerId; + private String statustext; - public ExtensionStatusEvent(Object source) - { - super(source); - } - - /** - * Returns the extension. - */ - public String getExten() - { - return exten; - } - - /** - * Sets the extension. - */ - public void setExten(String exten) - { - this.exten = exten; - } - - /** - * Returns the context of the extension. - */ - public String getContext() - { - return context; - } - /** - * Sets the context of the extension. - */ - public void setContext(String context) - { - this.context = context; + public ExtensionStatusEvent(Object source) { + super(source); } /** @@ -116,13 +82,11 @@ public void setContext(String context) * @return the hint (channel name) assigned to the extension. * @since 1.0.0 */ - public String getHint() - { + public String getHint() { return hint; } - public void setHint(String hint) - { + public void setHint(String hint) { this.hint = hint; } @@ -130,37 +94,34 @@ public void setHint(String hint) * Returns the state of the extension.

    * Possible values are: *

      - *
    • RINGING - *
    • INUSE | RINGING - *
    • INUSE - *
    • NOT_INUSE - *
    • BUSY - *
    • UNAVAILABLE - *
    • + *
    • RINGING
    • + *
    • INUSE | RINGING
    • + *
    • INUSE
    • + *
    • NOT_INUSE
    • + *
    • BUSY
    • + *
    • UNAVAILABLE
    • + *
    */ - public Integer getStatus() - { + public Integer getStatus() { return status; } /** * Sets the state of the extension. */ - public void setStatus(Integer status) - { + public void setStatus(Integer status) { this.status = status; } /** * Returns the Caller*ID in the form "Some Name" <1234>. - *

    + *
    * This property is only available on BRIstuffed Asterisk servers. * * @return the Caller*ID. * @since 0.3 */ - public String getCallerId() - { + public String getCallerId() { return callerId; } @@ -170,8 +131,16 @@ public String getCallerId() * @param callerId the Caller*ID. * @since 0.3 */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } + + public String getStatustext() { + return statustext; + } + + public void setStatustext(String statustext) { + this.statustext = statustext; + } + } diff --git a/src/main/java/org/asteriskjava/manager/event/FailedACLEvent.java b/src/main/java/org/asteriskjava/manager/event/FailedACLEvent.java new file mode 100644 index 000000000..8b7d19474 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/FailedACLEvent.java @@ -0,0 +1,17 @@ +package org.asteriskjava.manager.event; + +public final class FailedACLEvent extends AbstractSecurityEvent { + private String aclName; + + public FailedACLEvent(Object source) { + super(source); + } + + public String getAclName() { + return this.aclName; + } + + public void setAclName(String aclName) { + this.aclName = aclName; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/FaxDocumentStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/FaxDocumentStatusEvent.java index 74754b27c..894718ba6 100644 --- a/src/main/java/org/asteriskjava/manager/event/FaxDocumentStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/FaxDocumentStatusEvent.java @@ -19,8 +19,7 @@ /** * A FaxDocumentStatusEvent is an event of Digium's Fax For Asterisk add-on. */ -public class FaxDocumentStatusEvent extends AbstractFaxEvent -{ +public class FaxDocumentStatusEvent extends AbstractFaxEvent { /** * Serial version identifier. */ @@ -42,9 +41,12 @@ public class FaxDocumentStatusEvent extends AbstractFaxEvent private String remoteSid; private String remoteDis; + private String language; + private String accountCode; + private String linkedId; + private String uniqueId; - public FaxDocumentStatusEvent(Object source) - { + public FaxDocumentStatusEvent(Object source) { super(source); } @@ -52,8 +54,7 @@ public FaxDocumentStatusEvent(Object source) /** * @return the documentNumber */ - public Integer getDocumentNumber() - { + public Integer getDocumentNumber() { return documentNumber; } @@ -61,8 +62,7 @@ public Integer getDocumentNumber() /** * @param documentNumber the documentNumber to set */ - public void setDocumentNumber(Integer documentNumber) - { + public void setDocumentNumber(Integer documentNumber) { this.documentNumber = documentNumber; } @@ -70,8 +70,7 @@ public void setDocumentNumber(Integer documentNumber) /** * @return the lastError */ - public Integer getLastError() - { + public Integer getLastError() { return lastError; } @@ -79,8 +78,7 @@ public Integer getLastError() /** * @param lastError the lastError to set */ - public void setLastError(Integer lastError) - { + public void setLastError(Integer lastError) { this.lastError = lastError; } @@ -88,8 +86,7 @@ public void setLastError(Integer lastError) /** * @return the pageCount */ - public Integer getPageCount() - { + public Integer getPageCount() { return pageCount; } @@ -97,8 +94,7 @@ public Integer getPageCount() /** * @param pageCount the pageCount to set */ - public void setPageCount(Integer pageCount) - { + public void setPageCount(Integer pageCount) { this.pageCount = pageCount; } @@ -106,8 +102,7 @@ public void setPageCount(Integer pageCount) /** * @return the startPage */ - public Integer getStartPage() - { + public Integer getStartPage() { return startPage; } @@ -115,8 +110,7 @@ public Integer getStartPage() /** * @param startPage the startPage to set */ - public void setStartPage(Integer startPage) - { + public void setStartPage(Integer startPage) { this.startPage = startPage; } @@ -124,8 +118,7 @@ public void setStartPage(Integer startPage) /** * @return the lastPageProcessed */ - public Integer getLastPageProcessed() - { + public Integer getLastPageProcessed() { return lastPageProcessed; } @@ -133,8 +126,7 @@ public Integer getLastPageProcessed() /** * @param lastPageProcessed the lastPageProcessed to set */ - public void setLastPageProcessed(Integer lastPageProcessed) - { + public void setLastPageProcessed(Integer lastPageProcessed) { this.lastPageProcessed = lastPageProcessed; } @@ -142,8 +134,7 @@ public void setLastPageProcessed(Integer lastPageProcessed) /** * @return the retransmitCount */ - public Integer getRetransmitCount() - { + public Integer getRetransmitCount() { return retransmitCount; } @@ -151,8 +142,7 @@ public Integer getRetransmitCount() /** * @param retransmitCount the retransmitCount to set */ - public void setRetransmitCount(Integer retransmitCount) - { + public void setRetransmitCount(Integer retransmitCount) { this.retransmitCount = retransmitCount; } @@ -160,8 +150,7 @@ public void setRetransmitCount(Integer retransmitCount) /** * @return the transferPels */ - public Integer getTransferPels() - { + public Integer getTransferPels() { return transferPels; } @@ -169,8 +158,7 @@ public Integer getTransferPels() /** * @param transferPels the transferPels to set */ - public void setTransferPels(Integer transferPels) - { + public void setTransferPels(Integer transferPels) { this.transferPels = transferPels; } @@ -178,8 +166,7 @@ public void setTransferPels(Integer transferPels) /** * @return the transferRate */ - public Integer getTransferRate() - { + public Integer getTransferRate() { return transferRate; } @@ -187,8 +174,7 @@ public Integer getTransferRate() /** * @param transferRate the transferRate to set */ - public void setTransferRate(Integer transferRate) - { + public void setTransferRate(Integer transferRate) { this.transferRate = transferRate; } @@ -196,8 +182,7 @@ public void setTransferRate(Integer transferRate) /** * @return the transferDuration */ - public String getTransferDuration() - { + public String getTransferDuration() { return transferDuration; } @@ -205,8 +190,7 @@ public String getTransferDuration() /** * @param transferDuration the transferDuration to set */ - public void setTransferDuration(String transferDuration) - { + public void setTransferDuration(String transferDuration) { this.transferDuration = transferDuration; } @@ -214,8 +198,7 @@ public void setTransferDuration(String transferDuration) /** * @return the badLineCount */ - public Integer getBadLineCount() - { + public Integer getBadLineCount() { return badLineCount; } @@ -223,8 +206,7 @@ public Integer getBadLineCount() /** * @param badLineCount the badLineCount to set */ - public void setBadLineCount(Integer badLineCount) - { + public void setBadLineCount(Integer badLineCount) { this.badLineCount = badLineCount; } @@ -232,8 +214,7 @@ public void setBadLineCount(Integer badLineCount) /** * @return the processedStatus */ - public String getProcessedStatus() - { + public String getProcessedStatus() { return processedStatus; } @@ -241,8 +222,7 @@ public String getProcessedStatus() /** * @param processedStatus the processedStatus to set */ - public void setProcessedStatus(String processedStatus) - { + public void setProcessedStatus(String processedStatus) { this.processedStatus = processedStatus; } @@ -250,8 +230,7 @@ public void setProcessedStatus(String processedStatus) /** * @return the documentTime */ - public String getDocumentTime() - { + public String getDocumentTime() { return documentTime; } @@ -259,8 +238,7 @@ public String getDocumentTime() /** * @param documentTime the documentTime to set */ - public void setDocumentTime(String documentTime) - { + public void setDocumentTime(String documentTime) { this.documentTime = documentTime; } @@ -268,8 +246,7 @@ public void setDocumentTime(String documentTime) /** * @return the localSid */ - public String getLocalSid() - { + public String getLocalSid() { return localSid; } @@ -277,8 +254,7 @@ public String getLocalSid() /** * @param localSid the localSid to set */ - public void setLocalSid(String localSid) - { + public void setLocalSid(String localSid) { this.localSid = localSid; } @@ -286,8 +262,7 @@ public void setLocalSid(String localSid) /** * @return the localDis */ - public String getLocalDis() - { + public String getLocalDis() { return localDis; } @@ -295,8 +270,7 @@ public String getLocalDis() /** * @param localDis the localDis to set */ - public void setLocalDis(String localDis) - { + public void setLocalDis(String localDis) { this.localDis = localDis; } @@ -304,8 +278,7 @@ public void setLocalDis(String localDis) /** * @return the remoteSid */ - public String getRemoteSid() - { + public String getRemoteSid() { return remoteSid; } @@ -313,8 +286,7 @@ public String getRemoteSid() /** * @param remoteSid the remoteSid to set */ - public void setRemoteSid(String remoteSid) - { + public void setRemoteSid(String remoteSid) { this.remoteSid = remoteSid; } @@ -322,8 +294,7 @@ public void setRemoteSid(String remoteSid) /** * @return the remoteDis */ - public String getRemoteDis() - { + public String getRemoteDis() { return remoteDis; } @@ -331,11 +302,40 @@ public String getRemoteDis() /** * @param remoteDis the remoteDis to set */ - public void setRemoteDis(String remoteDis) - { + public void setRemoteDis(String remoteDis) { this.remoteDis = remoteDis; } + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/FaxLicenseEvent.java b/src/main/java/org/asteriskjava/manager/event/FaxLicenseEvent.java new file mode 100644 index 000000000..184e8d0d5 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/FaxLicenseEvent.java @@ -0,0 +1,64 @@ +package org.asteriskjava.manager.event; + +public final class FaxLicenseEvent extends ResponseEvent { + private String file; + private String key; + private String product; + private String hostId; + private Integer ports; + private String status; + + public FaxLicenseEvent(Object source) { + super(source); + } + + @Override + public String getFile() { + return file; + } + + @Override + public void setFile(String file) { + this.file = file; + } + + public String getHostId() { + return hostId; + } + + public void setHostId(String hostId) { + this.hostId = hostId; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public Integer getPorts() { + return ports; + } + + public void setPorts(Integer ports) { + this.ports = ports; + } + + public String getProduct() { + return product; + } + + public void setProduct(String product) { + this.product = product; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/FaxLicenseListCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/FaxLicenseListCompleteEvent.java new file mode 100644 index 000000000..a4167232d --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/FaxLicenseListCompleteEvent.java @@ -0,0 +1,10 @@ +package org.asteriskjava.manager.event; + +import org.asteriskjava.manager.AsteriskMapping; + +@AsteriskMapping("FaxLicenseList complete") +public final class FaxLicenseListCompleteEvent extends ResponseEvent { + public FaxLicenseListCompleteEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/FaxReceivedEvent.java b/src/main/java/org/asteriskjava/manager/event/FaxReceivedEvent.java index fdc05551a..3becf967b 100644 --- a/src/main/java/org/asteriskjava/manager/event/FaxReceivedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/FaxReceivedEvent.java @@ -24,19 +24,17 @@ * See http://soft-switch.org/installing-spandsp.html for details. *

    * Implemented in apps/app_rxfax.c. - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class FaxReceivedEvent extends AbstractFaxEvent -{ +public class FaxReceivedEvent extends AbstractFaxEvent { /** * Serial version identifier. */ private static final long serialVersionUID = 1L; - private String exten; private String callerId; private String remoteStationId; private String localStationId; @@ -45,171 +43,135 @@ public class FaxReceivedEvent extends AbstractFaxEvent private Integer transferRate; private String filename; - public FaxReceivedEvent(Object source) - { + public FaxReceivedEvent(Object source) { super(source); } - /** - * Returns the extension in Asterisk's dialplan the fax was received - * through. - * - * @return the extension the fax was received through. - */ - public String getExten() - { - return exten; - } - - /** - * Sets the extension the fax was received through. - * - * @param exten the extension the fax was received through. - */ - public void setExten(String exten) - { - this.exten = exten; - } - /** * Returns the Caller*ID of the calling party or an empty string if none is * available. - * + * * @return the Caller*ID of the calling party. */ - public String getCallerId() - { + public String getCallerId() { return callerId; } /** * Sets the Caller*ID of the calling party. - * + * * @param callerId the Caller*ID of the calling party. */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } /** * Retruns the identifier of the remote fax station. - * + * * @return the identifier of the remote fax station. */ - public String getRemoteStationId() - { + public String getRemoteStationId() { return remoteStationId; } /** * Sets the identifier of the remote fax station. - * + * * @param remoteStationId the identifier of the remote fax station. */ - public void setRemoteStationId(String remoteStationId) - { + public void setRemoteStationId(String remoteStationId) { this.remoteStationId = remoteStationId; } /** * Returns the identifier of the local fax station. - * + * * @return the identifier of the local fax station. */ - public String getLocalStationId() - { + public String getLocalStationId() { return localStationId; } /** * Sets the identifier of the local fax station. - * + * * @param localStationId the identifier of the local fax station. */ - public void setLocalStationId(String localStationId) - { + public void setLocalStationId(String localStationId) { this.localStationId = localStationId; } /** * Returns the number of pages transferred. - * + * * @return the number of pages transferred. */ - public Integer getPagesTransferred() - { + public Integer getPagesTransferred() { return pagesTransferred; } /** * Sets the number of pages transferred. - * + * * @param pagesTransferred the number of pages transferred. */ - public void setPagesTransferred(Integer pagesTransferred) - { + public void setPagesTransferred(Integer pagesTransferred) { this.pagesTransferred = pagesTransferred; } /** * Returns the row resolution of the received fax. - * + * * @return the row resolution of the received fax. */ - public Integer getResolution() - { + public Integer getResolution() { return resolution; } /** * Sets the row resolution of the received fax. - * + * * @param resolution the row resolution of the received fax. */ - public void setResolution(Integer resolution) - { + public void setResolution(Integer resolution) { this.resolution = resolution; } /** * Returns the transfer rate in bits/s. - * + * * @return the transfer rate in bits/s. */ - public Integer getTransferRate() - { + public Integer getTransferRate() { return transferRate; } /** * Sets the transfer rate in bits/s. - * + * * @param transferRate the transfer rate in bits/s. */ - public void setTransferRate(Integer transferRate) - { + public void setTransferRate(Integer transferRate) { this.transferRate = transferRate; } /** * Returns the filename of the received fax including its full path on the * Asterisk server. - * + * * @return the filename of the received fax */ - public String getFilename() - { + public String getFilename() { return filename; } /** * Sets the filename of the received fax. - * + * * @param filename the filename of the received fax */ - public void setFilename(String filename) - { + public void setFilename(String filename) { this.filename = filename; } } diff --git a/src/main/java/org/asteriskjava/manager/event/FaxStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/FaxStatusEvent.java index 4015ea26e..1724fc197 100644 --- a/src/main/java/org/asteriskjava/manager/event/FaxStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/FaxStatusEvent.java @@ -19,8 +19,7 @@ /** * A FaxDocumentStatusEvent is an event of Digium's Fax For Asterisk add-on. */ -public class FaxStatusEvent extends AbstractFaxEvent -{ +public class FaxStatusEvent extends AbstractFaxEvent { /** * Serial version identifier. */ @@ -52,9 +51,17 @@ public class FaxStatusEvent extends AbstractFaxEvent private Integer rtnCount; private Integer dcnCount; private String remoteStationId; + private String localStationId; + private String callerId; + private String status; + private String operation; - public FaxStatusEvent(Object source) - { + private String language; + private String accountCode; + private String linkedId; + private String uniqueId; + + public FaxStatusEvent(Object source) { super(source); } @@ -62,434 +69,467 @@ public FaxStatusEvent(Object source) /** * @return the operatingMode */ - public String getOperatingMode() - { + public String getOperatingMode() { return operatingMode; } /** * @param operatingMode the operatingMode to set */ - public void setOperatingMode(String operatingMode) - { + public void setOperatingMode(String operatingMode) { this.operatingMode = operatingMode; } /** * @return the result */ - public String getResult() - { + public String getResult() { return result; } /** * @param result the result to set */ - public void setResult(String result) - { + public void setResult(String result) { this.result = result; } /** * @return the error */ - public String getError() - { + public String getError() { return error; } /** * @param error the error to set */ - public void setError(String error) - { + public void setError(String error) { this.error = error; } /** * @return the callDuration */ - public Double getCallDuration() - { + public Double getCallDuration() { return callDuration; } /** * @param callDuration the callDuration to set */ - public void setCallDuration(Double callDuration) - { + public void setCallDuration(Double callDuration) { this.callDuration = callDuration; } /** * @return the ecmMode */ - public String getEcmMode() - { + public String getEcmMode() { return ecmMode; } /** * @param ecmMode the ecmMode to set */ - public void setEcmMode(String ecmMode) - { + public void setEcmMode(String ecmMode) { this.ecmMode = ecmMode; } /** * @return the dataRate */ - public Integer getDataRate() - { + public Integer getDataRate() { return dataRate; } /** * @param dataRate the dataRate to set */ - public void setDataRate(Integer dataRate) - { + public void setDataRate(Integer dataRate) { this.dataRate = dataRate; } /** * @return the imageResolution */ - public String getImageResolution() - { + public String getImageResolution() { return imageResolution; } /** * @param imageResolution the imageResolution to set */ - public void setImageResolution(String imageResolution) - { + public void setImageResolution(String imageResolution) { this.imageResolution = imageResolution; } /** * @return the imageEncoding */ - public String getImageEncoding() - { + public String getImageEncoding() { return imageEncoding; } /** * @param imageEncoding the imageEncoding to set */ - public void setImageEncoding(String imageEncoding) - { + public void setImageEncoding(String imageEncoding) { this.imageEncoding = imageEncoding; } /** * @return the pageSize */ - public String getPageSize() - { + public String getPageSize() { return pageSize; } /** * @param pageSize the pageSize to set */ - public void setPageSize(String pageSize) - { + public void setPageSize(String pageSize) { this.pageSize = pageSize; } /** * @return the documentNumber */ - public Integer getDocumentNumber() - { + public Integer getDocumentNumber() { return documentNumber; } /** * @param documentNumber the documentNumber to set */ - public void setDocumentNumber(Integer documentNumber) - { + public void setDocumentNumber(Integer documentNumber) { this.documentNumber = documentNumber; } /** * @return the pageNumber */ - public Integer getPageNumber() - { + public Integer getPageNumber() { return pageNumber; } /** * @param pageNumber the pageNumber to set */ - public void setPageNumber(Integer pageNumber) - { + public void setPageNumber(Integer pageNumber) { this.pageNumber = pageNumber; } /** * @return the fileName */ - public String getFileName() - { + public String getFileName() { return fileName; } /** * @param fileName the fileName to set */ - public void setFileName(String fileName) - { + public void setFileName(String fileName) { this.fileName = fileName; } /** * @return the txPages */ - public Integer getTxPages() - { + public Integer getTxPages() { return txPages; } /** * @param txPages the txPages to set */ - public void setTxPages(Integer txPages) - { + public void setTxPages(Integer txPages) { this.txPages = txPages; } /** * @return the txBytes */ - public Integer getTxBytes() - { + public Integer getTxBytes() { return txBytes; } /** * @param txBytes the txBytes to set */ - public void setTxBytes(Integer txBytes) - { + public void setTxBytes(Integer txBytes) { this.txBytes = txBytes; } /** * @return the totalTxLines */ - public Integer getTotalTxLines() - { + public Integer getTotalTxLines() { return totalTxLines; } /** * @param totalTxLines the totalTxLines to set */ - public void setTotalTxLines(Integer totalTxLines) - { + public void setTotalTxLines(Integer totalTxLines) { this.totalTxLines = totalTxLines; } /** * @return the rxPages */ - public Integer getRxPages() - { + public Integer getRxPages() { return rxPages; } /** * @param rxPages the rxPages to set */ - public void setRxPages(Integer rxPages) - { + public void setRxPages(Integer rxPages) { this.rxPages = rxPages; } /** * @return the rxBytes */ - public Integer getRxBytes() - { + public Integer getRxBytes() { return rxBytes; } /** * @param rxBytes the rxBytes to set */ - public void setRxBytes(Integer rxBytes) - { + public void setRxBytes(Integer rxBytes) { this.rxBytes = rxBytes; } /** * @return the totalRxLines */ - public Integer getTotalRxLines() - { + public Integer getTotalRxLines() { return totalRxLines; } /** * @param totalRxLines the totalRxLines to set */ - public void setTotalRxLines(Integer totalRxLines) - { + public void setTotalRxLines(Integer totalRxLines) { this.totalRxLines = totalRxLines; } /** * @return the totalBadLines */ - public Integer getTotalBadLines() - { + public Integer getTotalBadLines() { return totalBadLines; } /** * @param totalBadLines the totalBadLines to set */ - public void setTotalBadLines(Integer totalBadLines) - { + public void setTotalBadLines(Integer totalBadLines) { this.totalBadLines = totalBadLines; } /** * @return the disDcsDtcCtcCount */ - public Integer getDisDcsDtcCtcCount() - { + public Integer getDisDcsDtcCtcCount() { return disDcsDtcCtcCount; } /** * @param disDcsDtcCtcCount the disDcsDtcCtcCount to set */ - public void setDisDcsDtcCtcCount(Integer disDcsDtcCtcCount) - { + public void setDisDcsDtcCtcCount(Integer disDcsDtcCtcCount) { this.disDcsDtcCtcCount = disDcsDtcCtcCount; } /** * @return the cfrCount */ - public Integer getCfrCount() - { + public Integer getCfrCount() { return cfrCount; } /** * @param cfrCount the cfrCount to set */ - public void setCfrCount(Integer cfrCount) - { + public void setCfrCount(Integer cfrCount) { this.cfrCount = cfrCount; } /** * @return the fttCount */ - public Integer getFttCount() - { + public Integer getFttCount() { return fttCount; } /** * @param fttCount the fttCount to set */ - public void setFttCount(Integer fttCount) - { + public void setFttCount(Integer fttCount) { this.fttCount = fttCount; } /** * @return the mcfCount */ - public Integer getMcfCount() - { + public Integer getMcfCount() { return mcfCount; } /** * @param mcfCount the mcfCount to set */ - public void setMcfCount(Integer mcfCount) - { + public void setMcfCount(Integer mcfCount) { this.mcfCount = mcfCount; } /** * @return the pprCount */ - public Integer getPprCount() - { + public Integer getPprCount() { return pprCount; } /** * @param pprCount the pprCount to set */ - public void setPprCount(Integer pprCount) - { + public void setPprCount(Integer pprCount) { this.pprCount = pprCount; } /** * @return the rtnCount */ - public Integer getRtnCount() - { + public Integer getRtnCount() { return rtnCount; } /** * @param rtnCount the rtnCount to set */ - public void setRtnCount(Integer rtnCount) - { + public void setRtnCount(Integer rtnCount) { this.rtnCount = rtnCount; } /** * @return the dcnCount */ - public Integer getDcnCount() - { + public Integer getDcnCount() { return dcnCount; } /** * @param dcnCount the dcnCount to set */ - public void setDcnCount(Integer dcnCount) - { + public void setDcnCount(Integer dcnCount) { this.dcnCount = dcnCount; } /** * @return the remoteStationId */ - public String getRemoteStationId() - { + public String getRemoteStationId() { return remoteStationId; } /** * @param remoteStationId the remoteStationId to set */ - public void setRemoteStationId(String remoteStationId) - { + public void setRemoteStationId(String remoteStationId) { this.remoteStationId = remoteStationId; } + /** + * @return the localStationId + */ + public String getLocalStationId() { + return localStationId; + } + + /** + * @param localStationId the localStationId to set + */ + public void setLocalStationId(String localStationId) { + this.localStationId = localStationId; + } + + /** + * @return the callerId + */ + public String getCallerId() { + return callerId; + } + + /** + * @param callerId the callerId to set + */ + public void setCallerId(String callerid) { + this.callerId = callerid; + } + + /** + * @return the status + */ + public String getStatus() { + return status; + } + + /** + * @param status the status to set + */ + public void setStatus(String status) { + this.status = status; + } + + /** + * @return the operation + */ + public String getOperation() { + return operation; + } + + /** + * @param context the context to set + */ + public void setOperation(String operation) { + this.operation = operation; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/FullyBootedEvent.java b/src/main/java/org/asteriskjava/manager/event/FullyBootedEvent.java index 69c4f8da8..3577e22b7 100644 --- a/src/main/java/org/asteriskjava/manager/event/FullyBootedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/FullyBootedEvent.java @@ -1,7 +1,7 @@ package org.asteriskjava.manager.event; /** - * Indicates that Asterisk has loaded all its modules and finished booting.

    + * Indicates that Asterisk has loaded all its modules and finished booting.
    * It is handy to have a single event notification for when all Asterisk * modules have been loaded - especially for situations like running * automated tests. This event will fire 1) immediately upon all modules @@ -10,17 +10,17 @@ * that a user will never miss getting a FullyBooted event. In vary rare * circumstances, it might be possible to get two copies of the message * if the AMI connection is made right as the modules finish loading. - *

    - * It is implemented in main/asterisk.c and manager.c.

    + *
    + * It is implemented in main/asterisk.c and manager.c.
    * Available since Asterisk 1.8 */ -public class FullyBootedEvent extends ManagerEvent -{ +public class FullyBootedEvent extends ManagerEvent { private static final long serialVersionUID = 0L; private String status; + private String lastreload; + private Integer uptime; - public FullyBootedEvent(Object source) - { + public FullyBootedEvent(Object source) { super(source); } @@ -29,8 +29,7 @@ public FullyBootedEvent(Object source) * * @return the status. */ - public String getStatus() - { + public String getStatus() { return status; } @@ -39,8 +38,23 @@ public String getStatus() * * @param status the status. */ - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } + + public String getLastreload() { + return lastreload; + } + + public void setLastreload(String lastreload) { + this.lastreload = lastreload; + } + + public Integer getUptime() { + return uptime; + } + + public void setUptime(Integer uptime) { + this.uptime = uptime; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/HangupEvent.java b/src/main/java/org/asteriskjava/manager/event/HangupEvent.java index 83c4c42ac..214dae62b 100644 --- a/src/main/java/org/asteriskjava/manager/event/HangupEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/HangupEvent.java @@ -17,14 +17,14 @@ package org.asteriskjava.manager.event; /** - * A HangupEvent is triggered when a channel is hung up.

    + * A HangupEvent is triggered when a channel is hung up. + *

    * It is implemented in channel.c * * @author srt * @version $Id$ */ -public class HangupEvent extends AbstractChannelEvent -{ +public class HangupEvent extends AbstractChannelStateEvent { /** * Serializable version identifier. */ @@ -32,20 +32,28 @@ public class HangupEvent extends AbstractChannelEvent private Integer cause; private String causeTxt; + private String language; + private String linkedId; - public HangupEvent(Object source) - { + public HangupEvent(Object source) { super(source); } + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + /** * Returns the cause of the hangup. * * @return the hangup cause. * @see org.asteriskjava.live.HangupCause */ - public Integer getCause() - { + public Integer getCause() { return cause; } @@ -54,8 +62,7 @@ public Integer getCause() * * @param cause the hangup cause. */ - public void setCause(Integer cause) - { + public void setCause(Integer cause) { this.cause = cause; } @@ -65,8 +72,7 @@ public void setCause(Integer cause) * @return the textual representation of the hangup cause. * @since 0.2 */ - public String getCauseTxt() - { + public String getCauseTxt() { return causeTxt; } @@ -76,8 +82,33 @@ public String getCauseTxt() * @param causeTxt the textual representation of the hangup cause. * @since 0.2 */ - public void setCauseTxt(String causeTxt) - { + public void setCauseTxt(String causeTxt) { this.causeTxt = causeTxt; } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HangupEvent [cause="); + builder.append(cause); + builder.append(", causeTxt="); + builder.append(causeTxt); + builder.append(", language="); + builder.append(language); + builder.append(", linkedId="); + builder.append(linkedId); + builder.append(", accountCode="); + builder.append(accountCode); + builder.append("]"); + return builder.toString(); + } + } diff --git a/src/main/java/org/asteriskjava/manager/event/HangupHandlerPushEvent.java b/src/main/java/org/asteriskjava/manager/event/HangupHandlerPushEvent.java new file mode 100644 index 000000000..3925d4dc9 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/HangupHandlerPushEvent.java @@ -0,0 +1,78 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A HangupHandlerPushEvent is triggered when a channel pushes a hangup handler. + *

    + * It is implemented in channel.c + * + * @author srt + * @version $Id$ + */ +public class HangupHandlerPushEvent extends AbstractChannelStateEvent { + /** + * Serializable version identifier. + */ + static final long serialVersionUID = 0L; + + private String language; + private String linkedId; + + private String handler; + + public HangupHandlerPushEvent(Object source) { + super(source); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getHandler() { + return handler; + } + + public void setHandler(String handler) { + this.handler = handler; + } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HangupHandlerPush [language="); + builder.append(language); + builder.append(", linkedId="); + builder.append(linkedId); + builder.append(", accountCode="); + builder.append(accountCode); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/HangupHandlerRunEvent.java b/src/main/java/org/asteriskjava/manager/event/HangupHandlerRunEvent.java new file mode 100644 index 000000000..dbdfbb486 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/HangupHandlerRunEvent.java @@ -0,0 +1,77 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A HangupHandlerRunEvent is triggered when a hangup handler is run. + *

    + * It is implemented in channel.c + * + * @author srt + * @version $Id$ + */ +public class HangupHandlerRunEvent extends AbstractChannelStateEvent { + /** + * Serializable version identifier. + */ + static final long serialVersionUID = 0L; + + private String language; + private String linkedId; + private String handler; + + public HangupHandlerRunEvent(Object source) { + super(source); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getHandler() { + return handler; + } + + public void setHandler(String handler) { + this.handler = handler; + } + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HangupHandlerRun [language="); + builder.append(language); + builder.append(", linkedId="); + builder.append(linkedId); + builder.append(", accountCode="); + builder.append(accountCode); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/HangupRequestEvent.java b/src/main/java/org/asteriskjava/manager/event/HangupRequestEvent.java new file mode 100644 index 000000000..6ebf0a036 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/HangupRequestEvent.java @@ -0,0 +1,73 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A HangupEvent is triggered when a channel is requested hung up. + *

    + * It is implemented in channel.c + */ +public class HangupRequestEvent extends AbstractChannelEvent { + /** + * Serializable version identifier. + */ + static final long serialVersionUID = 0L; + + private Integer cause; + private String language; + private String linkedId; + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public HangupRequestEvent(Object source) { + super(source); + } + + /** + * Returns the cause of the hangup. + * + * @return the hangup cause. + * @see org.asteriskjava.live.HangupCause + */ + public Integer getCause() { + return cause; + } + + /** + * Sets the cause of the hangup. + * + * @param cause the hangup cause. + */ + public void setCause(Integer cause) { + this.cause = cause; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/HoldEvent.java b/src/main/java/org/asteriskjava/manager/event/HoldEvent.java index a51fbc9da..ad3d21065 100644 --- a/src/main/java/org/asteriskjava/manager/event/HoldEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/HoldEvent.java @@ -17,134 +17,51 @@ package org.asteriskjava.manager.event; /** - * A HoldEvent is triggered when a channel is put on hold (or no longer on hold).

    - * It is implemented in channels/chan_sip.c.

    + * A HoldEvent is triggered when a channel is put on hold (or no longer on + * hold). + *

    + * It is implemented in channels/chan_sip.c. + *

    * Available since Asterisk 1.2 for SIP channels, as of Asterisk 1.6 this event - * is also supported for IAX2 channels.

    - * To receive HoldEvents for SIP channels you must set callevents = yes - * in sip.conf. + * is also supported for IAX2 channels. + *

    + * To receive HoldEvents for SIP channels you must set + * callevents = yes in sip.conf. * * @author srt * @version $Id$ * @since 0.2 */ -public class HoldEvent extends ManagerEvent -{ +public class HoldEvent extends AbstractHoldEvent { /** * Serializable version identifier. */ private static final long serialVersionUID = 0L; - /** - * The name of the channel. - */ - private String channel; - - /** - * The unique id of the channel. - */ - private String uniqueId; - - private Boolean status; + private String musicClass; /** * Creates a new HoldEvent. * * @param source */ - public HoldEvent(Object source) - { + public HoldEvent(Object source) { super(source); - - /* Asterisk prior to 1.6 uses Hold and Unhold events instead of the status - * So we set the status to true in the Hold event and to false in Unhold. - * For Asterisk 1.6 this is overridden by the status property received with - * the hold event. + /* + * Asterisk prior to 1.6 and after 11 uses Hold and Unhold events + * instead of the status So we set the status to true in the Hold event + * and to false in Unhold. For Asterisk 1.6-11 this is overridden by the + * status property received with the hold event. */ setStatus(true); } - /** - * Returns the name of the channel. - * - * @return channel the name of the channel. - */ - public String getChannel() - { - return channel; - } - - /** - * Sets the name of the channel. - * - * @param channel the name of the channel. - */ - public void setChannel(String channel) - { - this.channel = channel; - } - - /** - * Returns the unique id of the channel. - * - * @return the unique id of the channel. - */ - public String getUniqueId() - { - return uniqueId; - } - - /** - * Sets the unique id of the channel. - * - * @param uniqueId the unique id of the channel. - */ - public void setUniqueId(String uniqueId) - { - this.uniqueId = uniqueId; + public String getMusicClass() { + return musicClass; } - /** - * Returns whether this is a hold or unhold event. - * - * @return true if this a hold event, false if it's an unhold event. - * @since 1.0.0 - */ - public Boolean getStatus() - { - return status; + public void setMusicClass(String musicClass) { + this.musicClass = musicClass; } - /** - * Returns whether this is a hold or unhold event. - * - * @param status true if this a hold event, false if it's an unhold event. - * @since 1.0.0 - */ - public void setStatus(Boolean status) - { - this.status = status; - } - - /** - * Returns whether this is a hold event. - * - * @return true if this a hold event, false if it's an unhold event. - * @since 1.0.0 - */ - public boolean isHold() - { - return status != null && status; - } - - /** - * Returns whether this is an unhold event. - * - * @return true if this an unhold event, false if it's a hold event. - * @since 1.0.0 - */ - public boolean isUnhold() - { - return status != null && !status; - } } diff --git a/src/main/java/org/asteriskjava/manager/event/HoldedCallEvent.java b/src/main/java/org/asteriskjava/manager/event/HoldedCallEvent.java index 53e904019..0aff8ed1a 100644 --- a/src/main/java/org/asteriskjava/manager/event/HoldedCallEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/HoldedCallEvent.java @@ -19,12 +19,11 @@ /** * A HoldedCallEvent is triggered when a channel is put on hold.

    * It is implemented in res/res_features.c - * + * * @author srt * @version $Id$ */ -public class HoldedCallEvent extends ManagerEvent -{ +public class HoldedCallEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -37,72 +36,63 @@ public class HoldedCallEvent extends ManagerEvent /** * @param source */ - public HoldedCallEvent(Object source) - { + public HoldedCallEvent(Object source) { super(source); } /** * Returns the unique id of the channel that put the other channel on hold. */ - public String getUniqueId1() - { + public String getUniqueId1() { return uniqueId1; } /** * Sets the unique id of the channel that put the other channel on hold. */ - public void setUniqueId1(String uniqueId1) - { + public void setUniqueId1(String uniqueId1) { this.uniqueId1 = uniqueId1; } /** * Returns the unique id of the channel that has been put on hold. */ - public String getUniqueId2() - { + public String getUniqueId2() { return uniqueId2; } /** * Sets the unique id of the channel that has been put on hold. */ - public void setUniqueId2(String uniqueId2) - { + public void setUniqueId2(String uniqueId2) { this.uniqueId2 = uniqueId2; } /** * Returns the name of the channel that put the other channel on hold. */ - public String getChannel1() - { + public String getChannel1() { return channel1; } /** * Sets the name of the channel that put the other channel on hold. */ - public void setChannel1(String channel1) - { + public void setChannel1(String channel1) { this.channel1 = channel1; } /** * Returns the name of the channel that has been put on hold. */ - public String getChannel2() - { + public String getChannel2() { return channel2; } /** * Sets the name of the channel that has been put on hold. */ - public void setChannel2(String channel2) - { + public void setChannel2(String channel2) { this.channel2 = channel2; } diff --git a/src/main/java/org/asteriskjava/manager/event/InvalidAccountId.java b/src/main/java/org/asteriskjava/manager/event/InvalidAccountId.java new file mode 100644 index 000000000..24db59dce --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/InvalidAccountId.java @@ -0,0 +1,120 @@ +package org.asteriskjava.manager.event; + +/** + * @author Jefferson Alves Reis (jefaokpta) < jefaokpta@hotmail.com > + * Date: 2021-03-03 + */ + +public class InvalidAccountId extends ManagerEvent { + /** + * + */ + private static final long serialVersionUID = 7812041063040911614L; + private String severity; + private Integer eventVersion; + private String eventtv; + private String sessionId; + private String localAddress; + private String accountId; + private String service; + private String remoteAddress; + private String event; + private String module; + private String sessiontv; + + public InvalidAccountId(Object source) { + super(source); + } + + public static long getSerialVersionUID() { + return serialVersionUID; + } + + public String getSeverity() { + return severity; + } + + public void setSeverity(String severity) { + this.severity = severity; + } + + public Integer getEventVersion() { + return eventVersion; + } + + public void setEventVersion(Integer eventVersion) { + this.eventVersion = eventVersion; + } + + public String getEventtv() { + return eventtv; + } + + public void setEventtv(String eventtv) { + this.eventtv = eventtv; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getLocalAddress() { + return localAddress; + } + + public void setLocalAddress(String localAddress) { + this.localAddress = localAddress; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } + + public String getRemoteAddress() { + return remoteAddress; + } + + public void setRemoteAddress(String remoteAddress) { + this.remoteAddress = remoteAddress; + } + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } + + public String getModule() { + return module; + } + + public void setModule(String module) { + this.module = module; + } + + public String getSessiontv() { + return sessiontv; + } + + public void setSessiontv(String sessiontv) { + this.sessiontv = sessiontv; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/InvalidPasswordEvent.java b/src/main/java/org/asteriskjava/manager/event/InvalidPasswordEvent.java new file mode 100644 index 000000000..866dc725e --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/InvalidPasswordEvent.java @@ -0,0 +1,150 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/23/15. + */ +public class InvalidPasswordEvent extends ManagerEvent { + /** + * + */ + private static final long serialVersionUID = -5161586187203331724L; + private String severity; + private Integer eventVersion; + private String eventtv; + private String sessionid; + private String receivedHash; + private String localaddress; + private String accountId; + private String receivedChallenge; + private String service; + private String remoteAddress; + private String challenge; + private String sessiontv; + private String localAddress; + private String sessionId; + private String module; + + public InvalidPasswordEvent(Object source) { + super(source); + } + + public String getSeverity() { + return severity; + } + + public void setSeverity(String severity) { + this.severity = severity; + } + + public Integer getEventVersion() { + return eventVersion; + } + + public void setEventVersion(Integer eventVersion) { + this.eventVersion = eventVersion; + } + + public String getEventtv() { + return eventtv; + } + + public void setEventtv(String eventtv) { + this.eventtv = eventtv; + } + + public String getSessionid() { + return sessionid; + } + + public void setSessionid(String sessionid) { + this.sessionid = sessionid; + } + + public String getReceivedHash() { + return receivedHash; + } + + public void setReceivedHash(String receivedHash) { + this.receivedHash = receivedHash; + } + + public String getLocaladdress() { + return localaddress; + } + + public void setLocaladdress(String localaddress) { + this.localaddress = localaddress; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getReceivedChallenge() { + return receivedChallenge; + } + + public void setReceivedChallenge(String receivedChallenge) { + this.receivedChallenge = receivedChallenge; + } + + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } + + public String getRemoteAddress() { + return remoteAddress; + } + + public void setRemoteAddress(String remoteAddress) { + this.remoteAddress = remoteAddress; + } + + public String getChallenge() { + return challenge; + } + + public void setChallenge(String challenge) { + this.challenge = challenge; + } + + public String getLocalAddress() { + return localAddress; + } + + public void setLocalAddress(String localAddress) { + this.localAddress = localAddress; + } + + public String getModule() { + return module; + } + + public void setModule(String module) { + this.module = module; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getSessiontv() { + return sessiontv; + } + + public void setSessiontv(String sessiontv) { + this.sessiontv = sessiontv; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/InvalidTransportEvent.java b/src/main/java/org/asteriskjava/manager/event/InvalidTransportEvent.java new file mode 100644 index 000000000..6a2e1c5d9 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/InvalidTransportEvent.java @@ -0,0 +1,17 @@ +package org.asteriskjava.manager.event; + +public final class InvalidTransportEvent extends AbstractSecurityEvent { + private String attemptedTransport; + + public InvalidTransportEvent(Object source) { + super(source); + } + + public String getAttemptedTransport() { + return attemptedTransport; + } + + public void setAttemptedTransport(String value) { + this.attemptedTransport = value; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/JabberEventEvent.java b/src/main/java/org/asteriskjava/manager/event/JabberEventEvent.java index 0daf07591..0e78da0af 100644 --- a/src/main/java/org/asteriskjava/manager/event/JabberEventEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/JabberEventEvent.java @@ -25,35 +25,29 @@ * @version $Id$ * @since 1.0.0 */ -public class JabberEventEvent extends ManagerEvent -{ +public class JabberEventEvent extends ManagerEvent { private static final long serialVersionUID = 1L; private String account; private String packet; - public JabberEventEvent(Object source) - { + public JabberEventEvent(Object source) { super(source); } - public String getAccount() - { + public String getAccount() { return account; } - public void setAccount(String account) - { + public void setAccount(String account) { this.account = account; } - public String getPacket() - { + public String getPacket() { return packet; } - public void setPacket(String packet) - { + public void setPacket(String packet) { this.packet = packet; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/JitterBufStatsEvent.java b/src/main/java/org/asteriskjava/manager/event/JitterBufStatsEvent.java index f321811b8..daf0f6531 100644 --- a/src/main/java/org/asteriskjava/manager/event/JitterBufStatsEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/JitterBufStatsEvent.java @@ -26,8 +26,7 @@ * @version $Id$ * @since 1.0.0 */ -public class JitterBufStatsEvent extends ManagerEvent -{ +public class JitterBufStatsEvent extends ManagerEvent { private static final long serialVersionUID = 1L; private String owner; @@ -47,8 +46,7 @@ public class JitterBufStatsEvent extends ManagerEvent private Integer remoteooo; private Integer remoteReceived; - public JitterBufStatsEvent(Object source) - { + public JitterBufStatsEvent(Object source) { super(source); } @@ -57,163 +55,131 @@ public JitterBufStatsEvent(Object source) * * @return channel the name of the channel. */ - public String getOwner() - { + public String getOwner() { return owner; } - public void setOwner(String owner) - { + public void setOwner(String owner) { this.owner = owner; } - public Integer getPing() - { + public Integer getPing() { return ping; } - public void setPing(Integer ping) - { + public void setPing(Integer ping) { this.ping = ping; } - public Integer getLocalJitter() - { + public Integer getLocalJitter() { return localJitter; } - public void setLocalJitter(Integer localJitter) - { + public void setLocalJitter(Integer localJitter) { this.localJitter = localJitter; } - public Integer getLocalJbDelay() - { + public Integer getLocalJbDelay() { return localJbDelay; } - public void setLocalJbDelay(Integer localJbDelay) - { + public void setLocalJbDelay(Integer localJbDelay) { this.localJbDelay = localJbDelay; } - public Integer getLocalTotalLost() - { + public Integer getLocalTotalLost() { return localTotalLost; } - public void setLocalTotalLost(Integer localTotalLost) - { + public void setLocalTotalLost(Integer localTotalLost) { this.localTotalLost = localTotalLost; } - public Integer getLocalLossPercent() - { + public Integer getLocalLossPercent() { return localLossPercent; } - public void setLocalLossPercent(Integer localLossPercent) - { + public void setLocalLossPercent(Integer localLossPercent) { this.localLossPercent = localLossPercent; } - public Integer getLocalDropped() - { + public Integer getLocalDropped() { return localDropped; } - public void setLocalDropped(Integer localDropped) - { + public void setLocalDropped(Integer localDropped) { this.localDropped = localDropped; } - public Integer getLocalooo() - { + public Integer getLocalooo() { return localooo; } - public void setLocalooo(Integer localooo) - { + public void setLocalooo(Integer localooo) { this.localooo = localooo; } - public Integer getLocalReceived() - { + public Integer getLocalReceived() { return localReceived; } - public void setLocalReceived(Integer localReceived) - { + public void setLocalReceived(Integer localReceived) { this.localReceived = localReceived; } - public Integer getRemoteJitter() - { + public Integer getRemoteJitter() { return remoteJitter; } - public void setRemoteJitter(Integer remoteJitter) - { + public void setRemoteJitter(Integer remoteJitter) { this.remoteJitter = remoteJitter; } - public Integer getRemoteJbDelay() - { + public Integer getRemoteJbDelay() { return remoteJbDelay; } - public void setRemoteJbDelay(Integer remoteJbDelay) - { + public void setRemoteJbDelay(Integer remoteJbDelay) { this.remoteJbDelay = remoteJbDelay; } - public Integer getRemoteTotalLost() - { + public Integer getRemoteTotalLost() { return remoteTotalLost; } - public void setRemoteTotalLost(Integer remoteTotalLost) - { + public void setRemoteTotalLost(Integer remoteTotalLost) { this.remoteTotalLost = remoteTotalLost; } - public Integer getRemoteLossPercent() - { + public Integer getRemoteLossPercent() { return remoteLossPercent; } - public void setRemoteLossPercent(Integer remoteLossPercent) - { + public void setRemoteLossPercent(Integer remoteLossPercent) { this.remoteLossPercent = remoteLossPercent; } - public Integer getRemoteDropped() - { + public Integer getRemoteDropped() { return remoteDropped; } - public void setRemoteDropped(Integer remoteDropped) - { + public void setRemoteDropped(Integer remoteDropped) { this.remoteDropped = remoteDropped; } - public Integer getRemoteooo() - { + public Integer getRemoteooo() { return remoteooo; } - public void setRemoteooo(Integer remoteooo) - { + public void setRemoteooo(Integer remoteooo) { this.remoteooo = remoteooo; } - public Integer getRemoteReceived() - { + public Integer getRemoteReceived() { return remoteReceived; } - public void setRemoteReceived(Integer remoteReceived) - { + public void setRemoteReceived(Integer remoteReceived) { this.remoteReceived = remoteReceived; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/JoinEvent.java b/src/main/java/org/asteriskjava/manager/event/JoinEvent.java index 231ddd5d8..22c355ef2 100644 --- a/src/main/java/org/asteriskjava/manager/event/JoinEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/JoinEvent.java @@ -17,25 +17,22 @@ package org.asteriskjava.manager.event; /** - * A JoinEvent is triggered when a channel joines a queue.

    + * A JoinEvent is triggered when a channel joines a queue. + *

    * It is implemented in apps/app_queue.c * * @author srt - * @version $Id$ */ -public class JoinEvent extends QueueEvent -{ +public class JoinEvent extends QueueEvent { /** * Serializable version identifier. */ static final long serialVersionUID = 0L; - protected String callerIdNum; protected String callerIdName; protected Integer position; - public JoinEvent(Object source) - { + public JoinEvent(Object source) { super(source); } @@ -46,77 +43,33 @@ public JoinEvent(Object source) * @return the Caller*ID number of the channel that joined the queue * @deprecated since 1.0.0, use {@link #getCallerIdNum()} instead. */ - @Deprecated public String getCallerId() - { + @Deprecated + public String getCallerId() { return callerIdNum; } /** * Sets the Caller*ID number of the channel that joined the queue. * - * @param callerId the Caller*ID number of the channel that joined the queue. + * @param callerId the Caller*ID number of the channel that joined the + * queue. */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerIdNum = callerId; } - /** - * Returns the Caller*ID number of the channel that joined the queue if set. - * If the channel has no caller id set "unknown" is returned. - * - * @return the Caller*ID number of the channel that joined the queue - * @since 1.0.0 - */ - public String getCallerIdNum() - { - return callerIdNum; - } - - /** - * Sets the Caller*ID number of the channel that joined the queue. - * - * @param callerIdNum the Caller*ID number of the channel that joined the queue. - */ - public void setCallerIdNum(String callerIdNum) - { - this.callerIdNum = callerIdNum; - } - - /** - * Returns the Caller*ID name of the channel that joined the queue if set. - * If the channel has no caller id set "unknown" is returned. - * - * @since 0.2 - */ - public String getCallerIdName() - { - return callerIdName; - } - - /** - * Sets the Caller*ID name of the channel that joined the queue. - * - * @since 0.2 - */ - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; - } - /** * Returns the position of the joined channel in the queue. */ - public Integer getPosition() - { + public Integer getPosition() { return position; } /** * Sets the position of the joined channel in the queue. */ - public void setPosition(Integer position) - { + public void setPosition(Integer position) { this.position = position; } + } diff --git a/src/main/java/org/asteriskjava/manager/event/LeaveEvent.java b/src/main/java/org/asteriskjava/manager/event/LeaveEvent.java index 39864b855..c6eada661 100644 --- a/src/main/java/org/asteriskjava/manager/event/LeaveEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/LeaveEvent.java @@ -19,22 +19,32 @@ /** * A LeaveEvent is triggered when a channel leaves a queue.

    * It is implemented in apps/app_queue.c - * + * * @author srt - * @version $Id$ */ -public class LeaveEvent extends QueueEvent -{ +public class LeaveEvent extends QueueEvent { /** * Serializable version identifier */ static final long serialVersionUID = -7450401017732634240L; + private Integer position; + /** * @param source */ - public LeaveEvent(Object source) - { + public LeaveEvent(Object source) { super(source); } + + /** + * @return the position of the caller at the time they leave the queue + */ + public Integer getPosition() { + return position; + } + + public void setPosition(Integer position) { + this.position = position; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/LinkEvent.java b/src/main/java/org/asteriskjava/manager/event/LinkEvent.java index c0614ed57..6547be706 100644 --- a/src/main/java/org/asteriskjava/manager/event/LinkEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/LinkEvent.java @@ -27,17 +27,16 @@ * @author srt * @version $Id$ * @deprecated as of 1.0.0, use {@link org.asteriskjava.manager.event.BridgeEvent} and - * {@link BridgeEvent#isLink()} instead + * {@link BridgeEvent#isLink()} instead */ -@Deprecated public class LinkEvent extends BridgeEvent -{ +@Deprecated +public class LinkEvent extends BridgeEvent { /** * Serializable version identifier. */ static final long serialVersionUID = -4023240534975776225L; - public LinkEvent(Object source) - { + public LinkEvent(Object source) { super(source); setBridgeState(BRIDGE_STATE_LINK); } diff --git a/src/main/java/org/asteriskjava/manager/event/ListDialplanEvent.java b/src/main/java/org/asteriskjava/manager/event/ListDialplanEvent.java index addf70367..7e9740bed 100644 --- a/src/main/java/org/asteriskjava/manager/event/ListDialplanEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ListDialplanEvent.java @@ -12,104 +12,70 @@ * @see ShowDialplanCompleteEvent * @since 1.0.0 */ -public class ListDialplanEvent extends ResponseEvent -{ +public class ListDialplanEvent extends ResponseEvent { private static final long serialVersionUID = 1L; private static final String PRIORITY_HINT = "hint"; - private String context; private String extension; private String extensionLabel; - private Integer priority; private boolean hint = false; private String application; private String appData; private String registrar; + private String includeContext; + private String _switch; + private String ignorePattern; - public ListDialplanEvent(Object source) - { + public ListDialplanEvent(Object source) { super(source); } - /** - * Returns the context. - * - * @return the context. - */ - public String getContext() - { - return context; - } - - public void setContext(String context) - { - this.context = context; - } - /** * Returns the extension or extension pattern. * * @return the extension or extension pattern. */ - public String getExtension() - { + public String getExtension() { return extension; } - public void setExtension(String extension) - { + public void setExtension(String extension) { this.extension = extension; } /** * Returns the extension label. + * * @return the extension label or null if none. */ - public String getExtensionLabel() - { + public String getExtensionLabel() { return extensionLabel; } - public void setExtensionLabel(String extensionLabel) - { + public void setExtensionLabel(String extensionLabel) { this.extensionLabel = extensionLabel; } - /** - * Returns the priority. - * - * @return the priority or null if this is a hint. - */ - public Integer getPriority() - { - return priority; - } - /** * Checks whether this is a hint. + * * @return true if this is a hint, false otherwise. */ - public boolean isHint() - { + public boolean isHint() { return hint; } - public void setPriority(String priorityString) - { - if (priorityString == null) - { + public void setPriority(String priorityString) { + if (priorityString == null) { this.priority = null; return; } - if (PRIORITY_HINT.equals(priorityString)) - { + if (PRIORITY_HINT.equals(priorityString)) { hint = true; this.priority = null; - } - else - { + } else { this.priority = Integer.parseInt(priorityString); } } @@ -119,13 +85,11 @@ public void setPriority(String priorityString) * * @return the application configured to handle this priority. */ - public String getApplication() - { + public String getApplication() { return application; } - public void setApplication(String application) - { + public void setApplication(String application) { this.application = application; } @@ -133,33 +97,55 @@ public void setApplication(String application) * Returns the parameters of the application configured to handle this priority. * * @return the parameters of the application configured to handle this priority - * or null if none. + * or null if none. */ - public String getAppData() - { + public String getAppData() { return appData; } - public void setAppData(String appData) - { + public void setAppData(String appData) { this.appData = appData; } /** * Returns the registrar that registered this priority.

    * Typical values are "features" for the parkedcalls context, "pbx_config" for priorities - * defined in extensions.conf or "app_dial" for the + * defined in extensions.conf or "app_dial" for the * app_dial_gosub_virtual_context context. * * @return the registrar that registered this priority. */ - public String getRegistrar() - { + public String getRegistrar() { return registrar; } - public void setRegistrar(String registrar) - { + public void setRegistrar(String registrar) { this.registrar = registrar; } -} \ No newline at end of file + + public String getIncludeContext() { + return includeContext; + } + + public void setIncludeContext(String includeContext) { + this.includeContext = includeContext; + } + + public String getSwitch() { + return _switch; + } + + public ListDialplanEvent setSwitch(String _switch) { + this._switch = _switch; + return this; + } + + public String getIgnorePattern() { + return ignorePattern; + } + + public ListDialplanEvent setIgnorePattern(String ignorePattern) { + this.ignorePattern = ignorePattern; + return this; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/LoadAverageLimitEvent.java b/src/main/java/org/asteriskjava/manager/event/LoadAverageLimitEvent.java new file mode 100644 index 000000000..71aa38e24 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/LoadAverageLimitEvent.java @@ -0,0 +1,7 @@ +package org.asteriskjava.manager.event; + +public final class LoadAverageLimitEvent extends AbstractSecurityEvent { + public LoadAverageLimitEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/LocalBridgeEvent.java b/src/main/java/org/asteriskjava/manager/event/LocalBridgeEvent.java new file mode 100644 index 000000000..45dd94ba5 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/LocalBridgeEvent.java @@ -0,0 +1,373 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * https://wiki.asterisk.org/wiki/display/AST/Asterisk+11+ManagerEvent_LocalBridge + * Triggered when 2 halves of a local channels are bridged + *

    + * It is implemented in channels/chan_local.c + * + * @author jylebleu + * @version $Id$ + */ +public class LocalBridgeEvent extends ManagerEvent { + /** + * Serializable version identifier. + */ + static final long serialVersionUID = 0L; + + private String uniqueId1; + private String uniqueId2; + private String channel1; + private String channel2; + private String callerId1; + private String callerId2; + private String localOptimization; + private String localOneCalleridName; + private String localTwoChannel; + private String localTwoLanguage; + private String localTwoExten; + private String localOneChannel; + private String localOneContext; + private String localOneConnectedLineNum; + private String localOneConnectedLineName; + private String localOneChannelStateDesc; + private String localOneChannelState; + private String localOneExten; + private String localOneLanguage; + private String localOnePriority; + private String localOneUniqueId; + private String localTwochannelState; + private String localTwoChannelStateDesc; + private String localTwoPriority; + private String localTwoContext; + private String localTwoCalleridNum; + private String localTwoCalleridName; + private String localTwoUniqueid; + private String localOneCalleridNum; + private String localTwoConnectedLineName; + private String localTwoConnectedLineNum; + + private String localTwoLinkedid; + private String localOneLinkedid; + private String localOneAccountCode; + private String localTwoAccountCode; + + public LocalBridgeEvent(Object source) { + super(source); + } + + public String getUniqueId1() { + return uniqueId1; + } + + public void setUniqueId1(String uniqueId1) { + this.uniqueId1 = uniqueId1; + } + + public String getUniqueId2() { + return uniqueId2; + } + + public void setUniqueId2(String uniqueId2) { + this.uniqueId2 = uniqueId2; + } + + /** + * The name of the Local Channel half that bridges to another channel. + * + * @return The name of the Local Channel half that bridges to another channel. + */ + public String getChannel1() { + return channel1; + } + + public void setChannel1(String channel1) { + this.channel1 = channel1; + } + + /** + * The name of the Local Channel half that executes the dialplan. + * + * @return The name of the Local Channel half that executes the dialplan. + */ + public String getChannel2() { + return channel2; + } + + public void setChannel2(String channel2) { + this.channel2 = channel2; + } + + public String getCallerId1() { + return callerId1; + } + + public void setCallerId1(String callerId1) { + this.callerId1 = callerId1; + } + + public String getCallerId2() { + return callerId2; + } + + public void setCallerId2(String callerId2) { + this.callerId2 = callerId2; + } + + /** + * Local optimization values + *

    + * Yes + * No + * + * @return Local optimization + */ + + public String getLocalOptimization() { + return localOptimization; + } + + public void setLocalOptimization(String localOptimization) { + this.localOptimization = localOptimization; + } + + public String getLocalOneCalleridName() { + return localOneCalleridName; + } + + public void setLocalOneCalleridName(String localOneCalleridName) { + this.localOneCalleridName = localOneCalleridName; + } + + public String getLocalTwoChannel() { + return localTwoChannel; + } + + public void setLocalTwoChannel(String localTwoChannel) { + this.localTwoChannel = localTwoChannel; + } + + public String getLocalTwoLanguage() { + return localTwoLanguage; + } + + public void setLocalTwoLanguage(String localTwoLanguage) { + this.localTwoLanguage = localTwoLanguage; + } + + public String getLocalTwoExten() { + return localTwoExten; + } + + public void setLocalTwoExten(String localTwoExten) { + this.localTwoExten = localTwoExten; + } + + public String getLocalOneChannel() { + return localOneChannel; + } + + public void setLocalOneChannel(String localOneChannel) { + this.localOneChannel = localOneChannel; + } + + public String getLocalOneContext() { + return localOneContext; + } + + public void setLocalOneContext(String localOneContext) { + this.localOneContext = localOneContext; + } + + public String getLocalOneConnectedLineNum() { + return localOneConnectedLineNum; + } + + public void setLocalOneConnectedLineNum(String localOneConnectedLineNum) { + this.localOneConnectedLineNum = localOneConnectedLineNum; + } + + public String getLocalOneConnectedLineName() { + return localOneConnectedLineName; + } + + public void setLocalOneConnectedLineName(String localOneConnectedLineName) { + this.localOneConnectedLineName = localOneConnectedLineName; + } + + public String getLocalOneChannelStateDesc() { + return localOneChannelStateDesc; + } + + public void setLocalOneChannelStateDesc(String localOneChannelStateDesc) { + this.localOneChannelStateDesc = localOneChannelStateDesc; + } + + public String getLocalOneChannelState() { + return localOneChannelState; + } + + public void setLocalOneChannelState(String localOneChannelState) { + this.localOneChannelState = localOneChannelState; + } + + public String getLocalOneExten() { + return localOneExten; + } + + public void setLocalOneExten(String localOneExten) { + this.localOneExten = localOneExten; + } + + public String getLocalOneLanguage() { + return localOneLanguage; + } + + public void setLocalOneLanguage(String localOneLanguage) { + this.localOneLanguage = localOneLanguage; + } + + public String getLocalOnePriority() { + return localOnePriority; + } + + public void setLocalOnePriority(String localOnePriority) { + this.localOnePriority = localOnePriority; + } + + public String getLocalOneUniqueId() { + return localOneUniqueId; + } + + public void setLocalOneUniqueId(String localOneUniqueId) { + this.localOneUniqueId = localOneUniqueId; + } + + public String getLocalTwochannelState() { + return localTwochannelState; + } + + public void setLocalTwochannelState(String localTwochannelState) { + this.localTwochannelState = localTwochannelState; + } + + public String getLocalTwoChannelStateDesc() { + return localTwoChannelStateDesc; + } + + public void setLocalTwoChannelStateDesc(String localTwoChannelStateDesc) { + this.localTwoChannelStateDesc = localTwoChannelStateDesc; + } + + public String getLocalTwoPriority() { + return localTwoPriority; + } + + public void setLocalTwoPriority(String localTwoPriority) { + this.localTwoPriority = localTwoPriority; + } + + public String getLocalTwoContext() { + return localTwoContext; + } + + public void setLocalTwoContext(String localTwoContext) { + this.localTwoContext = localTwoContext; + } + + public String getLocalTwoCalleridNum() { + return localTwoCalleridNum; + } + + public void setLocalTwoCalleridNum(String localTwoCalleridNum) { + this.localTwoCalleridNum = localTwoCalleridNum; + } + + public String getLocalTwoCalleridName() { + return localTwoCalleridName; + } + + public void setLocalTwoCalleridName(String localTwoCalleridName) { + this.localTwoCalleridName = localTwoCalleridName; + } + + public String getLocalTwoUniqueid() { + return localTwoUniqueid; + } + + public void setLocalTwoUniqueid(String localTwoUniqueid) { + this.localTwoUniqueid = localTwoUniqueid; + } + + public String getLocalOneCalleridNum() { + return localOneCalleridNum; + } + + public void setLocalOneCalleridNum(String localOneCalleridNum) { + this.localOneCalleridNum = localOneCalleridNum; + } + + public String getLocalTwoConnectedLineName() { + return localTwoConnectedLineName; + } + + public void setLocalTwoConnectedLineName(String localTwoConnectedLineName) { + this.localTwoConnectedLineName = localTwoConnectedLineName; + } + + public String getLocalTwoConnectedLineNum() { + return localTwoConnectedLineNum; + } + + public void setLocalTwoConnectedLineNum(String localTwoConnectedLineNum) { + this.localTwoConnectedLineNum = localTwoConnectedLineNum; + } + + public String getLocalTwoLinkedid() { + return localTwoLinkedid; + } + + public void setLocalTwoLinkedid(String localTwoLinkedid) { + this.localTwoLinkedid = localTwoLinkedid; + } + + public String getLocalOneLinkedid() { + return localOneLinkedid; + } + + public void setLocalOneLinkedid(String localOneLinkedid) { + this.localOneLinkedid = localOneLinkedid; + } + + public String getLocalOneAccountCode() { + return localOneAccountCode; + } + + public void setLocalOneAccountCode(String localOneAccountCode) { + this.localOneAccountCode = localOneAccountCode; + } + + public String getLocalTwoAccountCode() { + return localTwoAccountCode; + } + + public void setLocalTwoAccountCode(String localTwoAccountCode) { + this.localTwoAccountCode = localTwoAccountCode; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/LocalOptimizationBeginEvent.java b/src/main/java/org/asteriskjava/manager/event/LocalOptimizationBeginEvent.java new file mode 100644 index 000000000..aa815f099 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/LocalOptimizationBeginEvent.java @@ -0,0 +1,430 @@ +/* + * Copyright 2018 Sean Bright + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * Raised when two halves of a Local Channel begin to optimize themselves out of + * the media path. Available since Asterisk 12 + */ +public class LocalOptimizationBeginEvent extends ManagerEvent { + private static final long serialVersionUID = 0L; + + private Integer id; + private String destUniqueId; + + private String localOneChannel; + private String localOneChannelState; + private String localOneChannelStateDesc; + private String localOneCallerIDNum; + private String localOneCallerIDName; + private String localOneConnectedLineNum; + private String localOneConnectedLineName; + private String localOneAccountCode; + private String localOneContext; + private String localOneExten; + private Integer localOnePriority; + private String localOneUniqueid; + private String localOneLinkedid; + + private String localTwoChannel; + private String localTwoChannelState; + private String localTwoChannelStateDesc; + private String localTwoCallerIDNum; + private String localTwoCallerIDName; + private String localTwoConnectedLineNum; + private String localTwoConnectedLineName; + private String localTwoAccountCode; + private String localTwoContext; + private String localTwoExten; + private Integer localTwoPriority; + private String localTwoUniqueid; + private String localTwoLinkedid; + + private String sourceChannel; + private String sourceChannelState; + private String sourceChannelStateDesc; + private String sourceCallerIDNum; + private String sourceCallerIDName; + private String sourceConnectedLineNum; + private String sourceConnectedLineName; + private String sourceAccountCode; + private String sourceContext; + private String sourceExten; + private Integer sourcePriority; + private String sourceUniqueid; + private String sourceLinkedid; + + private String localTwoLanguage; + private String localOneLanguage; + private String sourceLanguage; + + public LocalOptimizationBeginEvent(Object source) { + super(source); + } + + public Integer getId() { + return this.id; + } + + public void setId(Integer value) { + this.id = value; + } + + public String getDestUniqueId() { + return this.destUniqueId; + } + + public void setDestUniqueId(String value) { + this.destUniqueId = value; + } + + public String getLocalOneChannel() { + return this.localOneChannel; + } + + public void setLocalOneChannel(String value) { + this.localOneChannel = value; + } + + public String getLocalOneChannelState() { + return this.localOneChannelState; + } + + public void setLocalOneChannelState(String value) { + this.localOneChannelState = value; + } + + public String getLocalOneChannelStateDesc() { + return this.localOneChannelStateDesc; + } + + public void setLocalOneChannelStateDesc(String value) { + this.localOneChannelStateDesc = value; + } + + public String getLocalOneCallerIDNum() { + return this.localOneCallerIDNum; + } + + public void setLocalOneCallerIDNum(String value) { + this.localOneCallerIDNum = value; + } + + public String getLocalOneCallerIDName() { + return this.localOneCallerIDName; + } + + public void setLocalOneCallerIDName(String value) { + this.localOneCallerIDName = value; + } + + public String getLocalOneConnectedLineNum() { + return this.localOneConnectedLineNum; + } + + public void setLocalOneConnectedLineNum(String value) { + this.localOneConnectedLineNum = value; + } + + public String getLocalOneConnectedLineName() { + return this.localOneConnectedLineName; + } + + public void setLocalOneConnectedLineName(String value) { + this.localOneConnectedLineName = value; + } + + public String getLocalOneAccountCode() { + return this.localOneAccountCode; + } + + public void setLocalOneAccountCode(String value) { + this.localOneAccountCode = value; + } + + public String getLocalOneContext() { + return this.localOneContext; + } + + public void setLocalOneContext(String value) { + this.localOneContext = value; + } + + public String getLocalOneExten() { + return this.localOneExten; + } + + public void setLocalOneExten(String value) { + this.localOneExten = value; + } + + public Integer getLocalOnePriority() { + return this.localOnePriority; + } + + public void setLocalOnePriority(Integer value) { + this.localOnePriority = value; + } + + public String getLocalOneUniqueid() { + return this.localOneUniqueid; + } + + public void setLocalOneUniqueid(String value) { + this.localOneUniqueid = value; + } + + public String getLocalOneLinkedid() { + return this.localOneLinkedid; + } + + public void setLocalOneLinkedid(String value) { + this.localOneLinkedid = value; + } + + public String getLocalTwoChannel() { + return this.localTwoChannel; + } + + public void setLocalTwoChannel(String value) { + this.localTwoChannel = value; + } + + public String getLocalTwoChannelState() { + return this.localTwoChannelState; + } + + public void setLocalTwoChannelState(String value) { + this.localTwoChannelState = value; + } + + public String getLocalTwoChannelStateDesc() { + return this.localTwoChannelStateDesc; + } + + public void setLocalTwoChannelStateDesc(String value) { + this.localTwoChannelStateDesc = value; + } + + public String getLocalTwoCallerIDNum() { + return this.localTwoCallerIDNum; + } + + public void setLocalTwoCallerIDNum(String value) { + this.localTwoCallerIDNum = value; + } + + public String getLocalTwoCallerIDName() { + return this.localTwoCallerIDName; + } + + public void setLocalTwoCallerIDName(String value) { + this.localTwoCallerIDName = value; + } + + public String getLocalTwoConnectedLineNum() { + return this.localTwoConnectedLineNum; + } + + public void setLocalTwoConnectedLineNum(String value) { + this.localTwoConnectedLineNum = value; + } + + public String getLocalTwoConnectedLineName() { + return this.localTwoConnectedLineName; + } + + public void setLocalTwoConnectedLineName(String value) { + this.localTwoConnectedLineName = value; + } + + public String getLocalTwoAccountCode() { + return this.localTwoAccountCode; + } + + public void setLocalTwoAccountCode(String value) { + this.localTwoAccountCode = value; + } + + public String getLocalTwoContext() { + return this.localTwoContext; + } + + public void setLocalTwoContext(String value) { + this.localTwoContext = value; + } + + public String getLocalTwoExten() { + return this.localTwoExten; + } + + public void setLocalTwoExten(String value) { + this.localTwoExten = value; + } + + public Integer getLocalTwoPriority() { + return this.localTwoPriority; + } + + public void setLocalTwoPriority(Integer value) { + this.localTwoPriority = value; + } + + public String getLocalTwoUniqueid() { + return this.localTwoUniqueid; + } + + public void setLocalTwoUniqueid(String value) { + this.localTwoUniqueid = value; + } + + public String getLocalTwoLinkedid() { + return this.localTwoLinkedid; + } + + public void setLocalTwoLinkedid(String value) { + this.localTwoLinkedid = value; + } + + public String getSourceChannel() { + return this.sourceChannel; + } + + public void setSourceChannel(String value) { + this.sourceChannel = value; + } + + public String getSourceChannelState() { + return this.sourceChannelState; + } + + public void setSourceChannelState(String value) { + this.sourceChannelState = value; + } + + public String getSourceChannelStateDesc() { + return this.sourceChannelStateDesc; + } + + public void setSourceChannelStateDesc(String value) { + this.sourceChannelStateDesc = value; + } + + public String getSourceCallerIDNum() { + return this.sourceCallerIDNum; + } + + public void setSourceCallerIDNum(String value) { + this.sourceCallerIDNum = value; + } + + public String getSourceCallerIDName() { + return this.sourceCallerIDName; + } + + public void setSourceCallerIDName(String value) { + this.sourceCallerIDName = value; + } + + public String getSourceConnectedLineNum() { + return this.sourceConnectedLineNum; + } + + public void setSourceConnectedLineNum(String value) { + this.sourceConnectedLineNum = value; + } + + public String getSourceConnectedLineName() { + return this.sourceConnectedLineName; + } + + public void setSourceConnectedLineName(String value) { + this.sourceConnectedLineName = value; + } + + public String getSourceAccountCode() { + return this.sourceAccountCode; + } + + public void setSourceAccountCode(String value) { + this.sourceAccountCode = value; + } + + public String getSourceContext() { + return this.sourceContext; + } + + public void setSourceContext(String value) { + this.sourceContext = value; + } + + public String getSourceExten() { + return this.sourceExten; + } + + public void setSourceExten(String value) { + this.sourceExten = value; + } + + public Integer getSourcePriority() { + return this.sourcePriority; + } + + public void setSourcePriority(Integer value) { + this.sourcePriority = value; + } + + public String getSourceUniqueid() { + return this.sourceUniqueid; + } + + public void setSourceUniqueid(String value) { + this.sourceUniqueid = value; + } + + public String getSourceLinkedid() { + return this.sourceLinkedid; + } + + public void setSourceLinkedid(String value) { + this.sourceLinkedid = value; + } + + public String getLocalTwoLanguage() { + return localTwoLanguage; + } + + public void setLocalTwoLanguage(String localTwoLanguage) { + this.localTwoLanguage = localTwoLanguage; + } + + public String getLocalOneLanguage() { + return localOneLanguage; + } + + public void setLocalOneLanguage(String localOneLanguage) { + this.localOneLanguage = localOneLanguage; + } + + public String getSourceLanguage() { + return sourceLanguage; + } + + public void setSourceLanguage(String sourceLanguage) { + this.sourceLanguage = sourceLanguage; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/LocalOptimizationEndEvent.java b/src/main/java/org/asteriskjava/manager/event/LocalOptimizationEndEvent.java new file mode 100644 index 000000000..4d4f20d88 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/LocalOptimizationEndEvent.java @@ -0,0 +1,304 @@ +/* + * Copyright 2018 Sean Bright + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * Raised when two halves of a Local Channel have finished optimizing themselves + * out of the media path. Available since Asterisk 12 + */ +public class LocalOptimizationEndEvent extends ManagerEvent { + private static final long serialVersionUID = 0L; + + private Integer id; + private Boolean success; + + private String localOneChannel; + private String localOneChannelState; + private String localOneChannelStateDesc; + private String localOneCallerIDNum; + private String localOneCallerIDName; + private String localOneConnectedLineNum; + private String localOneConnectedLineName; + private String localOneAccountCode; + private String localOneContext; + private String localOneExten; + private Integer localOnePriority; + private String localOneUniqueid; + private String localOneLinkedid; + + private String localTwoChannel; + private String localTwoChannelState; + private String localTwoChannelStateDesc; + private String localTwoCallerIDNum; + private String localTwoCallerIDName; + private String localTwoConnectedLineNum; + private String localTwoConnectedLineName; + private String localTwoAccountCode; + private String localTwoContext; + private String localTwoExten; + private Integer localTwoPriority; + private String localTwoUniqueid; + private String localTwoLinkedid; + + private String localTwoLanguage; + private String localOneLanguage; + + public LocalOptimizationEndEvent(Object source) { + super(source); + } + + public Integer getId() { + return this.id; + } + + public void setId(Integer value) { + this.id = value; + } + + public Boolean getSuccess() { + return this.success; + } + + public void setSuccess(Boolean success) { + this.success = success; + } + + public String getLocalOneChannel() { + return this.localOneChannel; + } + + public void setLocalOneChannel(String value) { + this.localOneChannel = value; + } + + public String getLocalOneChannelState() { + return this.localOneChannelState; + } + + public void setLocalOneChannelState(String value) { + this.localOneChannelState = value; + } + + public String getLocalOneChannelStateDesc() { + return this.localOneChannelStateDesc; + } + + public void setLocalOneChannelStateDesc(String value) { + this.localOneChannelStateDesc = value; + } + + public String getLocalOneCallerIDNum() { + return this.localOneCallerIDNum; + } + + public void setLocalOneCallerIDNum(String value) { + this.localOneCallerIDNum = value; + } + + public String getLocalOneCallerIDName() { + return this.localOneCallerIDName; + } + + public void setLocalOneCallerIDName(String value) { + this.localOneCallerIDName = value; + } + + public String getLocalOneConnectedLineNum() { + return this.localOneConnectedLineNum; + } + + public void setLocalOneConnectedLineNum(String value) { + this.localOneConnectedLineNum = value; + } + + public String getLocalOneConnectedLineName() { + return this.localOneConnectedLineName; + } + + public void setLocalOneConnectedLineName(String value) { + this.localOneConnectedLineName = value; + } + + public String getLocalOneAccountCode() { + return this.localOneAccountCode; + } + + public void setLocalOneAccountCode(String value) { + this.localOneAccountCode = value; + } + + public String getLocalOneContext() { + return this.localOneContext; + } + + public void setLocalOneContext(String value) { + this.localOneContext = value; + } + + public String getLocalOneExten() { + return this.localOneExten; + } + + public void setLocalOneExten(String value) { + this.localOneExten = value; + } + + public Integer getLocalOnePriority() { + return this.localOnePriority; + } + + public void setLocalOnePriority(Integer value) { + this.localOnePriority = value; + } + + public String getLocalOneUniqueid() { + return this.localOneUniqueid; + } + + public void setLocalOneUniqueid(String value) { + this.localOneUniqueid = value; + } + + public String getLocalOneLinkedid() { + return this.localOneLinkedid; + } + + public void setLocalOneLinkedid(String value) { + this.localOneLinkedid = value; + } + + public String getLocalTwoChannel() { + return this.localTwoChannel; + } + + public void setLocalTwoChannel(String value) { + this.localTwoChannel = value; + } + + public String getLocalTwoChannelState() { + return this.localTwoChannelState; + } + + public void setLocalTwoChannelState(String value) { + this.localTwoChannelState = value; + } + + public String getLocalTwoChannelStateDesc() { + return this.localTwoChannelStateDesc; + } + + public void setLocalTwoChannelStateDesc(String value) { + this.localTwoChannelStateDesc = value; + } + + public String getLocalTwoCallerIDNum() { + return this.localTwoCallerIDNum; + } + + public void setLocalTwoCallerIDNum(String value) { + this.localTwoCallerIDNum = value; + } + + public String getLocalTwoCallerIDName() { + return this.localTwoCallerIDName; + } + + public void setLocalTwoCallerIDName(String value) { + this.localTwoCallerIDName = value; + } + + public String getLocalTwoConnectedLineNum() { + return this.localTwoConnectedLineNum; + } + + public void setLocalTwoConnectedLineNum(String value) { + this.localTwoConnectedLineNum = value; + } + + public String getLocalTwoConnectedLineName() { + return this.localTwoConnectedLineName; + } + + public void setLocalTwoConnectedLineName(String value) { + this.localTwoConnectedLineName = value; + } + + public String getLocalTwoAccountCode() { + return this.localTwoAccountCode; + } + + public void setLocalTwoAccountCode(String value) { + this.localTwoAccountCode = value; + } + + public String getLocalTwoContext() { + return this.localTwoContext; + } + + public void setLocalTwoContext(String value) { + this.localTwoContext = value; + } + + public String getLocalTwoExten() { + return this.localTwoExten; + } + + public void setLocalTwoExten(String value) { + this.localTwoExten = value; + } + + public Integer getLocalTwoPriority() { + return this.localTwoPriority; + } + + public void setLocalTwoPriority(Integer value) { + this.localTwoPriority = value; + } + + public String getLocalTwoUniqueid() { + return this.localTwoUniqueid; + } + + public void setLocalTwoUniqueid(String value) { + this.localTwoUniqueid = value; + } + + public String getLocalTwoLinkedid() { + return this.localTwoLinkedid; + } + + public void setLocalTwoLinkedid(String value) { + this.localTwoLinkedid = value; + } + + public String getLocalTwoLanguage() { + return localTwoLanguage; + } + + public void setLocalTwoLanguage(String localTwoLanguage) { + this.localTwoLanguage = localTwoLanguage; + } + + public String getLocalOneLanguage() { + return localOneLanguage; + } + + public void setLocalOneLanguage(String localOneLanguage) { + this.localOneLanguage = localOneLanguage; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/LogChannelEvent.java b/src/main/java/org/asteriskjava/manager/event/LogChannelEvent.java index f2c3a7ad1..c3c924f94 100644 --- a/src/main/java/org/asteriskjava/manager/event/LogChannelEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/LogChannelEvent.java @@ -20,13 +20,12 @@ * A LogChannelEvent is triggered when logging is turned on or off.

    * It is implemented in logger.c

    * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class LogChannelEvent extends ManagerEvent -{ +public class LogChannelEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -40,104 +39,90 @@ public class LogChannelEvent extends ManagerEvent /** * @param source */ - public LogChannelEvent(Object source) - { + public LogChannelEvent(Object source) { super(source); } /** * Returns the name of the log channel. - * + * * @return the name of the log channel. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the log channel. - * + * * @param channel the name of the log channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns if logging has been enabled or disabled. - * + * * @return Boolean.TRUE if logging has been enabled, Boolean.FALSE if it has - * been disabled. + * been disabled. */ - public Boolean getEnabled() - { + public Boolean getEnabled() { return enabled; } /** * Sets if logging has been enabled or disabled. - * + * * @param enabled Boolean.TRUE if logging has been enabled, Boolean.FALSE if - * it has been disabled. + * it has been disabled. */ - public void setEnabled(Boolean enabled) - { + public void setEnabled(Boolean enabled) { this.enabled = enabled; } /** * Returns the reason code for disabling logging. - * + * * @return the reason code for disabling logging. */ - public Integer getReason() - { + public Integer getReason() { return reason; } /** * Returns the textual representation of the reason for disabling logging. - * + * * @return the textual representation of the reason for disabling logging. */ - public String getReasonTxt() - { + public String getReasonTxt() { return reasonTxt; } /** * Sets the reason for disabling logging. - * + * * @param s the reason in the form "%d - %s". */ - public void setReason(String s) - { + public void setReason(String s) { int spaceIdx; - if (s == null) - { + if (s == null) { return; } spaceIdx = s.indexOf(' '); - if (spaceIdx <= 0) - { + if (spaceIdx <= 0) { spaceIdx = s.length(); } - try - { + try { this.reason = Integer.valueOf(s.substring(0, spaceIdx)); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return; } - if (s.length() > spaceIdx + 3) - { + if (s.length() > spaceIdx + 3) { this.reasonTxt = s.substring(spaceIdx + 3, s.length()); } } diff --git a/src/main/java/org/asteriskjava/manager/event/ManagerEvent.java b/src/main/java/org/asteriskjava/manager/event/ManagerEvent.java index c6e3d1094..1aaa100a1 100644 --- a/src/main/java/org/asteriskjava/manager/event/ManagerEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ManagerEvent.java @@ -16,30 +16,138 @@ */ package org.asteriskjava.manager.event; +import org.asteriskjava.util.AstState; +import org.asteriskjava.util.ReflectionUtil; + import java.lang.reflect.Method; import java.util.*; -import org.asteriskjava.util.ReflectionUtil; - /** * Abstract base class for all Events that can be received from the Asterisk - * server. - *

    + * server.
    * Events contain data pertaining to an event generated from within the Asterisk - * core or an extension module. - *

    - * There is one conrete subclass of ManagerEvent per each supported Asterisk + * core or an extension module.
    + * There is one concrete subclass of ManagerEvent per each supported Asterisk * Event. * * @author srt * @version $Id$ */ -public abstract class ManagerEvent extends EventObject -{ +public abstract class ManagerEvent extends EventObject { /** * Serializable version identifier. */ - static final long serialVersionUID = 2L; + private static final long serialVersionUID = 2L; + protected String connectedLineNum; + protected String connectedLineName; + protected Integer priority; + protected Integer channelState; + protected String channelStateDesc; + protected String exten; + protected String callerIdNum; + protected String callerIdName; + protected Map channelVariables = Collections.emptyMap(); + + /** + * Returns the Caller ID name of the caller's channel. + * + * @return the Caller ID name of the caller's channel or "unknown" if none + * has been set. + * @since 0.2 + */ + + public String getCallerIdName() { + return callerIdName; + } + + public void setCallerIdName(String callerIdName) { + this.callerIdName = callerIdName; + } + + public String getConnectedLineNum() { + return connectedLineNum; + } + + public void setConnectedLineNum(String connectedLineNum) { + this.connectedLineNum = connectedLineNum; + } + + public String getConnectedLineName() { + return connectedLineName; + } + + public void setConnectedLineName(String connectedLineName) { + this.connectedLineName = connectedLineName; + } + + public Integer getPriority() { + return priority; + } + + public void setPriority(Integer priority) { + this.priority = priority; + } + + public Integer getChannelState() { + return channelState == null ? AstState.str2state(channelStateDesc) : channelState; + } + + public void setChannelState(Integer channelState) { + this.channelState = channelState; + } + + public String getChannelStateDesc() { + return channelStateDesc; + } + + public void setChannelStateDesc(String channelStateDesc) { + this.channelStateDesc = channelStateDesc; + } + + public String getExten() { + return exten; + } + + public void setExten(String exten) { + this.exten = exten; + } + + public String getCallerIdNum() { + return callerIdNum; + } + + public void setCallerIdNum(String callerIdNum) { + this.callerIdNum = callerIdNum; + } + + public String getContext() { + return context; + } + + public void setContext(String context) { + this.context = context; + } + + /** + * Gets a map of channel variables sent with this manager event. + *

    + * These are only sent by Asterisk if it has been configured to do so in + * the manager configuration file (manager.conf). + * + * @return an unmodifiable map of channel variables and their values, never {@code null} + */ + public Map getChannelVariables() { + return channelVariables; + } + + public void setChanVariables(Map variables) { + if (variables == null) { + return; + } + this.channelVariables = Collections.unmodifiableMap(new HashMap<>(variables)); + } + + protected String context; /** * AMI authorization class. @@ -54,55 +162,51 @@ public abstract class ManagerEvent extends EventObject private Double timestamp; /** - * The server from which this event has been received (only used with AstManProxy). + * The server from which this event has been received (only used with + * AstManProxy). */ private String server; + private String systemName; + // AJ-213 only used when debugging is turned on private String file; private Integer line; private String func; private Integer sequenceNumber; - public ManagerEvent(Object source) - { + public ManagerEvent(Object source) { super(source); } /** * Returns the point in time this event was received from the Asterisk - * server. - *

    + * server.
    * Pseudo events that are not directly received from the asterisk server * (for example ConnectEvent and DisconnectEvent) may return * null. */ - public Date getDateReceived() - { + public Date getDateReceived() { return dateReceived; } /** * Sets the point in time this event was received from the asterisk server. */ - public void setDateReceived(Date dateReceived) - { + public void setDateReceived(Date dateReceived) { this.dateReceived = dateReceived; } /** - * Returns the AMI authorization class of this event. - *

    + * Returns the AMI authorization class of this event.
    * This is one or more of system, call, log, verbose, command, agent or - * user. Multiple privileges are separated by comma. - *

    + * user. Multiple privileges are separated by comma.
    * Note: This property is not available from Asterisk 1.0 servers. * * @since 0.2 */ - public String getPrivilege() - { + public String getPrivilege() { return privilege; } @@ -111,26 +215,23 @@ public String getPrivilege() * * @since 0.2 */ - public void setPrivilege(String privilege) - { + public void setPrivilege(String privilege) { this.privilege = privilege; } /** - * Returns the timestamp for this event. - *

    + * Returns the timestamp for this event.
    * The timestamp property is available in Asterisk since 1.4 if enabled in * manager.conf by setting timestampevents = yes. - *

    + *
    * In contains the time the event was generated in seconds since the epoch. - *

    + *
    * Example: 1159310429.569108 * * @return the timestamp for this event. * @since 0.3 */ - public final Double getTimestamp() - { + public final Double getTimestamp() { return timestamp; } @@ -140,128 +241,144 @@ public final Double getTimestamp() * @param timestamp the timestamp to set. * @since 0.3 */ - public final void setTimestamp(Double timestamp) - { + public final void setTimestamp(Double timestamp) { this.timestamp = timestamp; } /** - * Returns the name of the Asterisk server from which this event has been received. - *

    + * Returns the name of the Asterisk server from which this event has been + * received.
    * This property is only available when using to AstManProxy. * - * @return the name of the Asterisk server from which this event has been received - * or null when directly connected to an Asterisk server - * instead of AstManProxy. + * @return the name of the Asterisk server from which this event has been + * received or null when directly connected to an + * Asterisk server instead of AstManProxy. * @since 1.0.0 */ - public final String getServer() - { + public final String getServer() { return server; } /** - * Sets the name of the Asterisk server from which this event has been received. + * Sets the name of the Asterisk server from which this event has been + * received. * - * @param server the name of the Asterisk server from which this event has been received. + * @param server the name of the Asterisk server from which this event has + * been received. * @since 1.0.0 */ - public final void setServer(String server) - { + public final void setServer(String server) { this.server = server; } + public String getSystemName() { + return systemName; + } + + public void setSystemName(String systemName) { + this.systemName = systemName; + } + /** - * Returns the name of the file in Asterisk's source code that triggered this event. For example - * pbx.c.

    - * This property is only available if debugging for the Manager API has been turned on in Asterisk. This can be - * done by calling manager debug on on Asterisk's command line interface or by adding - * debug=on to Asterisk's manager.conf. This feature is availble in Asterisk since 1.6.0. + * Returns the name of the file in Asterisk's source code that triggered + * this event. For example pbx.c. + *

    + * This property is only available if debugging for the Manager API has been + * turned on in Asterisk. This can be done by calling + * manager debug on on Asterisk's command line interface or by + * adding debug=on to Asterisk's manager.conf. + * This feature is availble in Asterisk since 1.6.0. * - * @return the name of the file in that triggered this event or null if debgging is turned off. + * @return the name of the file in that triggered this event or + * null if debgging is turned off. * @see #getFunc() * @see #getLine() * @since 1.0.0 */ - public String getFile() - { + public String getFile() { return file; } - public void setFile(String file) - { + public void setFile(String file) { this.file = file; } /** - * Returns the line number in Asterisk's source code where this event was triggered.

    - * This property is only available if debugging for the Manager API has been turned on in Asterisk. This can be - * done by calling manager debug on on Asterisk's command line interface or by adding - * debug=on to Asterisk's manager.conf. This feature is availble in Asterisk since 1.6.0. + * Returns the line number in Asterisk's source code where this event was + * triggered. + *

    + * This property is only available if debugging for the Manager API has been + * turned on in Asterisk. This can be done by calling + * manager debug on on Asterisk's command line interface or by + * adding debug=on to Asterisk's manager.conf. + * This feature is availble in Asterisk since 1.6.0. * - * @return the line number where this event was triggered or null if debgging is turned off. + * @return the line number where this event was triggered or + * null if debgging is turned off. * @see #getFile() * @see #getFunc() * @since 1.0.0 */ - public Integer getLine() - { + public Integer getLine() { return line; } - public void setLine(Integer line) - { + public void setLine(Integer line) { this.line = line; } /** - * Returns the name of the C function in Asterisk's source code that triggered this event. For example - * pbx_builtin_setvar_helper

    - * This property is only available if debugging for the Manager API has been turned on in Asterisk. This can be - * done by calling manager debug on on Asterisk's command line interface or by adding - * debug=on to Asterisk's manager.conf. This feature is availble in Asterisk since 1.6.0. + * Returns the name of the C function in Asterisk's source code that + * triggered this event. For example pbx_builtin_setvar_helper + *

    + * This property is only available if debugging for the Manager API has been + * turned on in Asterisk. This can be done by calling + * manager debug on on Asterisk's command line interface or by + * adding debug=on to Asterisk's manager.conf. + * This feature is availble in Asterisk since 1.6.0. * - * @return the name of the C function that triggered this event or null if debgging is turned off. + * @return the name of the C function that triggered this event or + * null if debgging is turned off. * @see #getFile() * @see #getLine() * @since 1.0.0 */ - public String getFunc() - { + public String getFunc() { return func; } - public void setFunc(String func) - { + public void setFunc(String func) { this.func = func; } /** - * Returns the sequence numbers of this event. Sequence numbers are only incremented while debugging is enabled.

    - * This property is only available if debugging for the Manager API has been turned on in Asterisk. This can be - * done by calling manager debug on on Asterisk's command line interface or by adding - * debug=on to Asterisk's manager.conf. This feature is availble in Asterisk since 1.6.0. + * Returns the sequence numbers of this event. Sequence numbers are only + * incremented while debugging is enabled. + *

    + * This property is only available if debugging for the Manager API has been + * turned on in Asterisk. This can be done by calling + * manager debug on on Asterisk's command line interface or by + * adding debug=on to Asterisk's manager.conf. + * This feature is availble in Asterisk since 1.6.0. * - * @return the sequence number of this event or null if debgging is turned off. + * @return the sequence number of this event or null if + * debgging is turned off. * @see #getFile() * @see #getLine() * @since 1.0.0 */ - public Integer getSequenceNumber() - { + public Integer getSequenceNumber() { return sequenceNumber; } - public void setSequenceNumber(Integer sequenceNumber) - { + public void setSequenceNumber(Integer sequenceNumber) { this.sequenceNumber = sequenceNumber; } @Override - public String toString() - { - final List ignoredProperties = Arrays.asList( - "file", "func", "line", "sequenceNumber", "datereceived", "privilege", "source", "class"); + public String toString() { + final List ignoredProperties = Arrays.asList("file", "func", "line", "sequenceNumber", "datereceived", + "privilege", "source", "class"); final StringBuilder sb = new StringBuilder(getClass().getName() + "["); appendPropertyIfNotNull(sb, "file", getFile()); appendPropertyIfNotNull(sb, "func", getFunc()); @@ -271,20 +388,16 @@ public String toString() appendPropertyIfNotNull(sb, "privilege", getPrivilege()); final Map getters = ReflectionUtil.getGetters(getClass()); - for (Map.Entry entry : getters.entrySet()) - { + for (Map.Entry entry : getters.entrySet()) { final String property = entry.getKey(); - if (ignoredProperties.contains(property)) - { + if (ignoredProperties.contains(property)) { continue; } - try - { + try { final Object value = entry.getValue().invoke(this); appendProperty(sb, property, value); - } - catch (Exception e) // NOPMD + } catch (Exception e) // NOPMD { // swallow } @@ -295,23 +408,17 @@ public String toString() return sb.toString(); } - protected void appendPropertyIfNotNull(StringBuilder sb, String property, Object value) - { - if (value != null) - { + protected void appendPropertyIfNotNull(StringBuilder sb, String property, Object value) { + if (value != null) { appendProperty(sb, property, value); } } - private void appendProperty(StringBuilder sb, String property, Object value) - { + private void appendProperty(StringBuilder sb, String property, Object value) { sb.append(property).append("="); - if (value == null) - { + if (value == null) { sb.append("null"); - } - else - { + } else { sb.append("'").append(value).append("'"); } sb.append(","); diff --git a/src/main/java/org/asteriskjava/manager/event/MasqueradeEvent.java b/src/main/java/org/asteriskjava/manager/event/MasqueradeEvent.java index 264fcec49..1f2513daf 100644 --- a/src/main/java/org/asteriskjava/manager/event/MasqueradeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MasqueradeEvent.java @@ -27,8 +27,7 @@ * @version $Id$ * @since 1.0.0 */ -public class MasqueradeEvent extends ManagerEvent -{ +public class MasqueradeEvent extends ManagerEvent { static final long serialVersionUID = 1L; private String clone; @@ -36,8 +35,7 @@ public class MasqueradeEvent extends ManagerEvent private String original; private String originalStateDesc; - public MasqueradeEvent(Object source) - { + public MasqueradeEvent(Object source) { super(source); } @@ -46,13 +44,11 @@ public MasqueradeEvent(Object source) * * @return the name of the clone channel. */ - public String getClone() - { + public String getClone() { return clone; } - public void setClone(String clone) - { + public void setClone(String clone) { this.clone = clone; } @@ -62,8 +58,7 @@ public void setClone(String clone) * @return the state of the clone channel. * @see org.asteriskjava.util.AstState */ - public Integer getCloneState() - { + public Integer getCloneState() { return AstState.str2state(cloneStateDesc); } @@ -72,13 +67,11 @@ public Integer getCloneState() * * @return the state of the clone channel as a descriptive text. */ - public String getCloneStateDesc() - { + public String getCloneStateDesc() { return cloneStateDesc; } - public void setCloneState(String cloneState) - { + public void setCloneState(String cloneState) { this.cloneStateDesc = cloneState; } @@ -87,13 +80,11 @@ public void setCloneState(String cloneState) * * @return the name of the original channel. */ - public String getOriginal() - { + public String getOriginal() { return original; } - public void setOriginal(String original) - { + public void setOriginal(String original) { this.original = original; } @@ -103,8 +94,7 @@ public void setOriginal(String original) * @return the state of the original channel. * @see org.asteriskjava.util.AstState */ - public Integer getOriginalState() - { + public Integer getOriginalState() { return AstState.str2state(originalStateDesc); } @@ -113,13 +103,11 @@ public Integer getOriginalState() * * @return the state of the original channel as a descriptive text. */ - public String getOriginalStateDesc() - { + public String getOriginalStateDesc() { return originalStateDesc; } - public void setOriginalState(String originalState) - { + public void setOriginalState(String originalState) { this.originalStateDesc = originalState; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/MeetMeEndEvent.java b/src/main/java/org/asteriskjava/manager/event/MeetMeEndEvent.java index a305b4f7c..aefb5819f 100644 --- a/src/main/java/org/asteriskjava/manager/event/MeetMeEndEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MeetMeEndEvent.java @@ -25,16 +25,14 @@ * @version $Id$ * @since 1.0.0 */ -public class MeetMeEndEvent extends ManagerEvent -{ +public class MeetMeEndEvent extends ManagerEvent { private static final long serialVersionUID = 510266716726148586L; private String meetMe; /** * @param source */ - public MeetMeEndEvent(Object source) - { + public MeetMeEndEvent(Object source) { super(source); } @@ -43,13 +41,11 @@ public MeetMeEndEvent(Object source) * * @return the conference number. */ - public String getMeetMe() - { + public String getMeetMe() { return meetMe; } - public void setMeetMe(String meetMe) - { + public void setMeetMe(String meetMe) { this.meetMe = meetMe; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/MeetMeJoinEvent.java b/src/main/java/org/asteriskjava/manager/event/MeetMeJoinEvent.java index b1a26624a..23cd9d626 100644 --- a/src/main/java/org/asteriskjava/manager/event/MeetMeJoinEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MeetMeJoinEvent.java @@ -17,60 +17,41 @@ package org.asteriskjava.manager.event; /** - * A MeetMeJoinEvent is triggered if a channel joins a MeetMe conference.

    - * Channel and unqiueId properties for this event are available since Asterisk 1.0.

    + * A MeetMeJoinEvent is triggered if a channel joins a MeetMe conference. + *

    + * Channel and unqiueId properties for this event are available since Asterisk + * 1.0. + *

    * It is implemented in apps/app_meetme.c * * @author srt * @version $Id$ */ -public class MeetMeJoinEvent extends AbstractMeetMeEvent -{ +public class MeetMeJoinEvent extends AbstractMeetMeEvent { /** * Serializable version identifier. */ private static final long serialVersionUID = 0L; - private String callerIdNum; - private String callerIdName; + private Integer duration; /** * @param source */ - public MeetMeJoinEvent(Object source) - { + public MeetMeJoinEvent(Object source) { super(source); } /** - * Returns the Caller Id number. + * Returns how long the user has been in the conference. * - * @return the Caller Id number or "" if not set. - * @since 1.0.0 + * @return the duration, in seconds, the user has been in the conference */ - public String getCallerIdNum() - { - return callerIdNum; + public Integer getDuration() { + return duration; } - public void setCallerIdNum(String callerIdNum) - { - this.callerIdNum = callerIdNum; - } - - /** - * Returns the Caller Id name. - * - * @return the Caller Id name or "" if not set. - * @since 1.0.0 - */ - public String getCallerIdName() - { - return callerIdName; - } - - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; + public void setDuration(Integer duration) { + this.duration = duration; } } diff --git a/src/main/java/org/asteriskjava/manager/event/MeetMeLeaveEvent.java b/src/main/java/org/asteriskjava/manager/event/MeetMeLeaveEvent.java index 022bc99ed..aa6aa748d 100644 --- a/src/main/java/org/asteriskjava/manager/event/MeetMeLeaveEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MeetMeLeaveEvent.java @@ -17,92 +17,48 @@ package org.asteriskjava.manager.event; /** - * A MeetMeLeaveEvent is triggered if a channel leaves a MeetMe conference.

    - * Channel and unqiueId properties for this event are available since Asterisk 1.0.

    + * A MeetMeLeaveEvent is triggered if a channel leaves a MeetMe conference. + *

    + * Channel and unqiueId properties for this event are available since Asterisk + * 1.0. + *

    * It is implemented in apps/app_meetme.c - * + * * @author srt * @version $Id$ */ -public class MeetMeLeaveEvent extends AbstractMeetMeEvent -{ +public class MeetMeLeaveEvent extends AbstractMeetMeEvent { /** * Serializable version identifier. */ private static final long serialVersionUID = 7692361610793036224L; - private String callerIdNum; - private String callerIdName; private Long duration; /** * @param source */ - public MeetMeLeaveEvent(Object source) - { + public MeetMeLeaveEvent(Object source) { super(source); } /** - * Returns the Caller*ID Name of the channel that left the conference.

    - * This property is available since Asterisk 1.4. - * - * @return the Caller*ID Name of the channel that left the conference. - */ - public String getCallerIdName() - { - return callerIdName; - } - - /** - * Sets the Caller*ID Name of the channel that left the conference. - * - * @param callerIdName the Caller*ID Name of the channel that left the conference. - */ - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; - } - - /** - * Returns the Caller*ID Number of the channel that left the conference.

    - * This property is available since Asterisk 1.4. - * - * @return the Caller*ID Number of the channel that left the conference. - */ - public String getCallerIdNum() - { - return callerIdNum; - } - - /** - * Sets the Caller*ID Number of the channel that left the conference. - * - * @param callerIdNum the Caller*ID Number of the channel that left the conference. - */ - public void setCallerIdNum(String callerIdNum) - { - this.callerIdNum = callerIdNum; - } - - /** - * Returns how long the user spent in the conference.

    + * Returns how long the user spent in the conference. + *

    * This property is available since Asterisk 1.4. - * + * * @return the duration in seconds the user spent in the conference. */ - public Long getDuration() - { + public Long getDuration() { return duration; } /** * Sets how long the user spent in the conference. - * + * * @param duration the duration in seconds the user spent in the conference. */ - public void setDuration(Long duration) - { + public void setDuration(Long duration) { this.duration = duration; } } diff --git a/src/main/java/org/asteriskjava/manager/event/MeetMeMuteEvent.java b/src/main/java/org/asteriskjava/manager/event/MeetMeMuteEvent.java index 9c723b45f..ec7fcc47e 100644 --- a/src/main/java/org/asteriskjava/manager/event/MeetMeMuteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MeetMeMuteEvent.java @@ -21,46 +21,56 @@ * unmuted.

    * It is implemented in apps/app_meetme.c

    * Available since Asterisk 1.4. - * + * * @author srt * @version $Id$ */ -public class MeetMeMuteEvent extends AbstractMeetMeEvent -{ +public class MeetMeMuteEvent extends AbstractMeetMeEvent { /** * Serializable version identifier. */ - private static final long serialVersionUID = -8554403451985143184L; + private static final long serialVersionUID = 1664651272460031885L; + private Integer duration; private Boolean status; /** * @param source */ - public MeetMeMuteEvent(Object source) - { + public MeetMeMuteEvent(Object source) { super(source); } + /** + * Returns how long the user has been in the conference. + * + * @return the duration, in seconds, the user has been in the conference + */ + public Integer getDuration() { + return duration; + } + + public void setDuration(Integer duration) { + this.duration = duration; + } + /** * Returns whether the user was muted or unmuted. - * + * * @return true if ther user was muted, - * false if the user was unmuted. + * false if the user was unmuted. */ - public Boolean getStatus() - { + public Boolean getStatus() { return status; } /** * Sets whether the user was muted or unmuted. - * - * @param status true if ther user was muted, + * + * @param status true if ther user was muted, * false if the user was unmuted. */ - public void setStatus(Boolean status) - { + public void setStatus(Boolean status) { this.status = status; } } diff --git a/src/main/java/org/asteriskjava/manager/event/MeetMeStopTalkingEvent.java b/src/main/java/org/asteriskjava/manager/event/MeetMeStopTalkingEvent.java index 448b30622..11b08d74e 100644 --- a/src/main/java/org/asteriskjava/manager/event/MeetMeStopTalkingEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MeetMeStopTalkingEvent.java @@ -30,17 +30,16 @@ * @see org.asteriskjava.manager.event.MeetMeTalkingEvent * @since 0.2 * @deprecated as of 1.0.0, use {@link org.asteriskjava.manager.event.MeetMeTalkingEvent} instead and check for - * {@link MeetMeTalkingEvent#getStatus()}. + * {@link MeetMeTalkingEvent#getStatus()}. */ -@Deprecated public class MeetMeStopTalkingEvent extends MeetMeTalkingEvent -{ +@Deprecated +public class MeetMeStopTalkingEvent extends MeetMeTalkingEvent { /** * Serializable version identifier. */ private static final long serialVersionUID = 1L; - public MeetMeStopTalkingEvent(Object source) - { + public MeetMeStopTalkingEvent(Object source) { super(source); this.status = Boolean.FALSE; } diff --git a/src/main/java/org/asteriskjava/manager/event/MeetMeTalkingEvent.java b/src/main/java/org/asteriskjava/manager/event/MeetMeTalkingEvent.java index e6080190d..bd2a32413 100644 --- a/src/main/java/org/asteriskjava/manager/event/MeetMeTalkingEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MeetMeTalkingEvent.java @@ -22,26 +22,38 @@ * To enable talker detection you must pass the option 'T' to the MeetMe application.

    * It is implemented in apps/app_meetme.c

    * Available since Asterisk 1.2 - * - * @see org.asteriskjava.manager.event.MeetMeStopTalkingEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.MeetMeStopTalkingEvent * @since 0.2 */ -public class MeetMeTalkingEvent extends AbstractMeetMeEvent -{ +public class MeetMeTalkingEvent extends AbstractMeetMeEvent { /** * Serializable version identifier. */ - private static final long serialVersionUID = -8554403451985143184L; + private static final long serialVersionUID = -1749014689947720722L; + private Integer duration; protected Boolean status = Boolean.TRUE; - public MeetMeTalkingEvent(Object source) - { + public MeetMeTalkingEvent(Object source) { super(source); } + /** + * Returns how long the user has been in the conference. + * + * @return the duration, in seconds, the user has been in the conference + */ + public Integer getDuration() { + return duration; + } + + public void setDuration(Integer duration) { + this.duration = duration; + } + /** * Returns whether the user has started or stopped talking.

    * Until Asterisk 1.2 Asterisk used different events to indicate start @@ -51,18 +63,16 @@ public MeetMeTalkingEvent(Object source) * start and stop. For backwards compatibility this property defaults to * true so when used with version 1.2 of Asterisk you get * true. - * + * * @return true if ther user has started talking, - * false if the user has stopped talking. + * false if the user has stopped talking. * @since 0.3 */ - public Boolean getStatus() - { + public Boolean getStatus() { return status; } - public void setStatus(Boolean status) - { + public void setStatus(Boolean status) { this.status = status; } } diff --git a/src/main/java/org/asteriskjava/manager/event/MeetMeTalkingRequestEvent.java b/src/main/java/org/asteriskjava/manager/event/MeetMeTalkingRequestEvent.java index 4a968b3d2..95729b194 100644 --- a/src/main/java/org/asteriskjava/manager/event/MeetMeTalkingRequestEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MeetMeTalkingRequestEvent.java @@ -16,49 +16,63 @@ */ package org.asteriskjava.manager.event; +import org.asteriskjava.manager.AsteriskMapping; + /** - * A MeetMeTalkingEvent is triggered when a muted user requests talking in a meet me - * conference.

    - * To enable talker detection you must pass the option 'T' to the MeetMe application.

    - * It is implemented in apps/app_meetme.c

    - * Available since Asterisk 1.6 + * A MeetMeTalkRequestEvent is triggered when a muted user requests talking in + * a MeetMe conference. * * @author srt * @version $Id$ * @since 1.0.0 */ -public class MeetMeTalkingRequestEvent extends AbstractMeetMeEvent -{ +@AsteriskMapping("MeetMeTalkRequest") +public class MeetMeTalkingRequestEvent extends AbstractMeetMeEvent { /** * Serializable version identifier. */ - private static final long serialVersionUID = 0L; + private static final long serialVersionUID = 1L; private Boolean status; + private Integer duration; /** - * @param source + * Constructs a MeetMeTalkingRequestEvent + * + * @param source The object on which the Event initially occurred. + * @throws IllegalArgumentException if source is null. */ - public MeetMeTalkingRequestEvent(Object source) - { + public MeetMeTalkingRequestEvent(Object source) { super(source); } // see http://bugs.digium.com/view.php?id=9418 /** - * Returns whether the user has started or stopped requesting talking. + * The length of time (in seconds) that the MeetMe user has been in the + * conference at the time of this event + * + * @return the number of seconds this user has been in the conference. + */ + public Integer getDuration() { + return duration; + } + + public void setDuration(Integer duration) { + this.duration = duration; + } + + /** + * Returns whether the user has started or stopped requesting talking * - * @return true if ther user has started requesting talking, - * false if the user has stopped requesting talking. + * @return {@code true} if the user has started requesting talking, + * {@code false} if the user has stopped requesting talking. */ - public Boolean getStatus() - { + public Boolean getStatus() { return status; } - public void setStatus(Boolean status) - { + public void setStatus(Boolean status) { this.status = status; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/MemoryLimitEvent.java b/src/main/java/org/asteriskjava/manager/event/MemoryLimitEvent.java new file mode 100644 index 000000000..6b086fbe1 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/MemoryLimitEvent.java @@ -0,0 +1,7 @@ +package org.asteriskjava.manager.event; + +public final class MemoryLimitEvent extends AbstractSecurityEvent { + public MemoryLimitEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/MessageWaitingEvent.java b/src/main/java/org/asteriskjava/manager/event/MessageWaitingEvent.java index 2e8910722..f2a9bb532 100644 --- a/src/main/java/org/asteriskjava/manager/event/MessageWaitingEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MessageWaitingEvent.java @@ -19,12 +19,11 @@ /** * A MessageWaitingEvent is triggered when someone leaves voicemail.

    * It is implemented in apps/app_voicemail.c - * + * * @author srt * @version $Id$ */ -public class MessageWaitingEvent extends ManagerEvent -{ +public class MessageWaitingEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -37,8 +36,7 @@ public class MessageWaitingEvent extends ManagerEvent /** * @param source */ - public MessageWaitingEvent(Object source) - { + public MessageWaitingEvent(Object source) { super(source); } @@ -46,81 +44,77 @@ public MessageWaitingEvent(Object source) * Returns the name of the mailbox that has waiting messages.

    * The name of the mailbox is of the form numberOfMailbox@context, e.g. * 1234@default. - * + * * @return the name of the mailbox that has waiting messages */ - public String getMailbox() - { + public String getMailbox() { return mailbox; } /** * Sets the name of the mailbox that has waiting messages. - * + * * @param mailbox the name of the mailbox that has waiting messages */ - public void setMailbox(String mailbox) - { + public void setMailbox(String mailbox) { this.mailbox = mailbox; } /** * Returns the number of new messages in the mailbox. - * + * * @return the number of new messages in the mailbox */ - public Integer getWaiting() - { + public Integer getWaiting() { return waiting; } /** * Sets the number of new messages in the mailbox. - * + * * @param waiting the number of new messages in the mailbox */ - public void setWaiting(Integer waiting) - { + public void setWaiting(Integer waiting) { this.waiting = waiting; } /** * Returns the number of new messages in this mailbox. + * * @return the number of new messages in this mailbox. * @since 0.2 */ - public Integer getNew() - { + public Integer getNew() { return newMessages; } /** * Sets the number of new messages in this mailbox. + * * @param newMessages the number of new messages in this mailbox. * @since 0.2 */ - public void setNew(Integer newMessages) - { + public void setNew(Integer newMessages) { this.newMessages = newMessages; } /** * Returns the number of old messages in this mailbox. + * * @return the number of old messages in this mailbox. * @since 0.2 */ - public Integer getOld() - { + public Integer getOld() { return oldMessages; } /** * Sets the number of old messages in this mailbox. + * * @param oldMessages the number of old messages in this mailbox. * @since 0.2 */ - public void setOld(Integer oldMessages) - { + public void setOld(Integer oldMessages) { this.oldMessages = oldMessages; } } diff --git a/src/main/java/org/asteriskjava/manager/event/MixMonitorStartEvent.java b/src/main/java/org/asteriskjava/manager/event/MixMonitorStartEvent.java new file mode 100644 index 000000000..10129d513 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/MixMonitorStartEvent.java @@ -0,0 +1,15 @@ +package org.asteriskjava.manager.event; + +/** + * A MixMonitorStartEvent indicates that monitoring was started on a channel.

    + * + * @see org.asteriskjava.manager.event.MixMonitorStopEvent + * @since 3.13.0 + */ +public class MixMonitorStartEvent extends AbstractMixMonitorEvent { + private static final long serialVersionUID = 1L; + + public MixMonitorStartEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/MixMonitorStopEvent.java b/src/main/java/org/asteriskjava/manager/event/MixMonitorStopEvent.java new file mode 100644 index 000000000..8a138390a --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/MixMonitorStopEvent.java @@ -0,0 +1,15 @@ +package org.asteriskjava.manager.event; + +/** + * A MixMonitorStopEvent indicates that monitoring was stopped on a channel.

    + * + * @see org.asteriskjava.manager.event.MixMonitorStartEvent + * @since 3.13.0 + */ +public class MixMonitorStopEvent extends AbstractMixMonitorEvent { + private static final long serialVersionUID = 1L; + + public MixMonitorStopEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ModuleLoadReportEvent.java b/src/main/java/org/asteriskjava/manager/event/ModuleLoadReportEvent.java index 9dfe7e87b..0ec7547ce 100644 --- a/src/main/java/org/asteriskjava/manager/event/ModuleLoadReportEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ModuleLoadReportEvent.java @@ -24,8 +24,7 @@ * @version $Id$ * @since 1.0.0 */ -public class ModuleLoadReportEvent extends ManagerEvent -{ +public class ModuleLoadReportEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -40,8 +39,7 @@ public class ModuleLoadReportEvent extends ManagerEvent private String moduleSelection; private Integer moduleCount; - public ModuleLoadReportEvent(Object source) - { + public ModuleLoadReportEvent(Object source) { super(source); } @@ -51,41 +49,35 @@ public ModuleLoadReportEvent(Object source) * @return the load status. * @see #MODULE_LOAD_STATUS_DONE */ - public String getModuleLoadStatus() - { + public String getModuleLoadStatus() { return moduleLoadStatus; } - public void setModuleLoadStatus(String moduleLoadStatus) - { + public void setModuleLoadStatus(String moduleLoadStatus) { this.moduleLoadStatus = moduleLoadStatus; } /** * Returns whether loading the pre-load modules has been completed or all modules - * have been loaded. + * have been loaded. * * @return "Preload" or "All" * @see #MODULE_SELECTION_PRELOAD * @see #MODULE_SELECTION_ALL */ - public String getModuleSelection() - { + public String getModuleSelection() { return moduleSelection; } - public boolean isPreload() - { + public boolean isPreload() { return MODULE_SELECTION_PRELOAD.equals(moduleSelection); } - public boolean isAll() - { + public boolean isAll() { return MODULE_SELECTION_ALL.equals(moduleSelection); } - public void setModuleSelection(String moduleSelection) - { + public void setModuleSelection(String moduleSelection) { this.moduleSelection = moduleSelection; } @@ -94,13 +86,11 @@ public void setModuleSelection(String moduleSelection) * * @return the number of modules that have been loaded. */ - public Integer getModuleCount() - { + public Integer getModuleCount() { return moduleCount; } - public void setModuleCount(Integer moduleCount) - { + public void setModuleCount(Integer moduleCount) { this.moduleCount = moduleCount; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/MonitorStartEvent.java b/src/main/java/org/asteriskjava/manager/event/MonitorStartEvent.java index 60ca3aefe..79a9261fd 100644 --- a/src/main/java/org/asteriskjava/manager/event/MonitorStartEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MonitorStartEvent.java @@ -23,14 +23,13 @@ * * @author srt * @version $Id$ - * @since 1.0.0 * @see org.asteriskjava.manager.event.MonitorStopEvent + * @since 1.0.0 */ -public class MonitorStartEvent extends AbstractMonitorEvent -{ +public class MonitorStartEvent extends AbstractMonitorEvent { private static final long serialVersionUID = 253533286571341499L; - public MonitorStartEvent(Object source) - { + + public MonitorStartEvent(Object source) { super(source); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/MonitorStopEvent.java b/src/main/java/org/asteriskjava/manager/event/MonitorStopEvent.java index 61cbfd846..ca6ec377a 100644 --- a/src/main/java/org/asteriskjava/manager/event/MonitorStopEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MonitorStopEvent.java @@ -23,14 +23,13 @@ * * @author srt * @version $Id$ - * @since 1.0.0 * @see org.asteriskjava.manager.event.MonitorStartEvent + * @since 1.0.0 */ -public class MonitorStopEvent extends AbstractMonitorEvent -{ +public class MonitorStopEvent extends AbstractMonitorEvent { private static final long serialVersionUID = -2605389608972504362L; - public MonitorStopEvent(Object source) - { + + public MonitorStopEvent(Object source) { super(source); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/MusicOnHoldEvent.java b/src/main/java/org/asteriskjava/manager/event/MusicOnHoldEvent.java index eb7791bcd..ffeb20d57 100644 --- a/src/main/java/org/asteriskjava/manager/event/MusicOnHoldEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MusicOnHoldEvent.java @@ -17,27 +17,31 @@ package org.asteriskjava.manager.event; /** - * A MusicOnHoldEvent is triggered when music on hold starts or stops on a channel.

    - * It is implemented in res/res_musiconhold.c.

    + * A MusicOnHoldEvent is triggered when music on hold starts or stops on a + * channel. + *

    + * It is implemented in res/res_musiconhold.c. + *

    * Available since Asterisk 1.6 * * @author srt - * @version $Id$ * @since 1.0.0 */ -public class MusicOnHoldEvent extends ManagerEvent -{ - private static final long serialVersionUID = 0L; +public class MusicOnHoldEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; public static final String STATE_START = "Start"; public static final String STATE_STOP = "Stop"; private String channel; + private String className; private String uniqueId; private String state; + private String accountCode; + private String linkedId; + private String language; - public MusicOnHoldEvent(Object source) - { + public MusicOnHoldEvent(Object source) { super(source); } @@ -46,8 +50,7 @@ public MusicOnHoldEvent(Object source) * * @return channel the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -56,18 +59,24 @@ public String getChannel() * * @param channel the name of the channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } + public String getClassName() { + return this.className; + } + + public void setClazz(String className) { + this.className = className; + } + /** * Returns the unique id of the channel. * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -76,48 +85,71 @@ public String getUniqueId() * * @param uniqueId the unique id of the channel. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } /** - * Returns the state. This is either "Start" or "Stop" depending on whether music on hold - * started or stopped on the channel. + * Returns the state. This is either "Start" or "Stop" depending on whether + * music on hold started or stopped on the channel. * - * @return "Start" if music on hold started or "Stop" if music on hold stopped on the channel. + * @return "Start" if music on hold started or "Stop" if music on hold + * stopped on the channel. * @see #STATE_START * @see #STATE_STOP * @see #isStart() * @see #isStop() */ - public String getState() - { + public String getState() { return state; } - public void setState(String state) - { + public void setState(String state) { this.state = state; } /** * Returns whether this is a start event. * - * @return true if this a start event, false otherwise. + * @return true if this a start event, false + * otherwise. */ - public boolean isStart() - { + public boolean isStart() { return STATE_START.equals(state); } /** * Returns whether this is a stop event. * - * @return true if this an stop event, false otherwise. + * @return true if this an stop event, false + * otherwise. */ - public boolean isStop() - { + public boolean isStop() { return STATE_STOP.equals(state); } -} \ No newline at end of file + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStartEvent.java b/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStartEvent.java new file mode 100644 index 000000000..82d88f2b2 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStartEvent.java @@ -0,0 +1,16 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public class MusicOnHoldStartEvent extends MusicOnHoldEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + + public MusicOnHoldStartEvent(Object source) { + super(source); + setState(STATE_START); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStopEvent.java b/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStopEvent.java new file mode 100644 index 000000000..fd49673ba --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStopEvent.java @@ -0,0 +1,16 @@ +package org.asteriskjava.manager.event; + +/** + * Created by Alexander Polakov on 1/26/15. + */ +public class MusicOnHoldStopEvent extends MusicOnHoldEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + + public MusicOnHoldStopEvent(Object source) { + super(source); + setState(STATE_STOP); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/NewAccountCodeEvent.java b/src/main/java/org/asteriskjava/manager/event/NewAccountCodeEvent.java index c774eeba1..58d6fb41f 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewAccountCodeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewAccountCodeEvent.java @@ -26,19 +26,19 @@ * @version $Id$ * @since 1.0.0 */ -public class NewAccountCodeEvent extends ManagerEvent -{ +public class NewAccountCodeEvent extends ManagerEvent { private static final long serialVersionUID = -1786512014173534223L; private String channel; private String uniqueId; private String accountCode; private String oldAccountCode; + private String language; + private String linkedId; /** * @param source */ - public NewAccountCodeEvent(Object source) - { + public NewAccountCodeEvent(Object source) { super(source); } @@ -47,13 +47,11 @@ public NewAccountCodeEvent(Object source) * * @return the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -62,13 +60,11 @@ public void setChannel(String channel) * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -77,13 +73,11 @@ public void setUniqueId(String uniqueId) * * @return the new account code. */ - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } @@ -92,13 +86,29 @@ public void setAccountCode(String accountCode) * * @return the old account code. */ - public String getOldAccountCode() - { + public String getOldAccountCode() { return oldAccountCode; } - public void setOldAccountCode(String oldAccountCode) - { + public void setOldAccountCode(String oldAccountCode) { this.oldAccountCode = oldAccountCode; } -} \ No newline at end of file + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/NewCallerIdEvent.java b/src/main/java/org/asteriskjava/manager/event/NewCallerIdEvent.java index 3fe85e7ad..e7e8a3a08 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewCallerIdEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewCallerIdEvent.java @@ -20,12 +20,11 @@ /** * A NewCallerIdEvent is triggered when the caller id of a channel changes.

    * It is implemented in channel.c - * + * * @author srt * @version $Id$ */ -public class NewCallerIdEvent extends AbstractChannelEvent -{ +public class NewCallerIdEvent extends AbstractChannelEvent { /** * Serializable version identifier. */ @@ -36,67 +35,75 @@ public class NewCallerIdEvent extends AbstractChannelEvent */ private Integer cidCallingPres; private String cidCallingPresTxt; + private String language; + private String linkedId; - public NewCallerIdEvent(Object source) - { + public NewCallerIdEvent(Object source) { super(source); } + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + /** * Returns the CallerId presentation/screening. - * + * * @return the CallerId presentation/screening. * @since 0.2 */ - public Integer getCidCallingPres() - { + public Integer getCidCallingPres() { return cidCallingPres; } /** * Returns the textual respresentation of the CallerId presentation/screening. - * + * * @return the textual respresentation of the CallerId presentation/screening. * @since 0.2 */ - public String getCidCallingPresTxt() - { + public String getCidCallingPresTxt() { return cidCallingPresTxt; } /** * Sets the CallerId presentation/screening in the form "%d (%s)". - * + * * @param s the CallerId presentation/screening in the form "%d (%s)". * @since 0.2 */ - public void setCidCallingPres(String s) - { + public void setCidCallingPres(String s) { int spaceIdx; - if (s == null) - { + if (s == null) { return; } spaceIdx = s.indexOf(' '); - if (spaceIdx <= 0) - { + if (spaceIdx <= 0) { spaceIdx = s.length(); } - try - { + try { this.cidCallingPres = Integer.valueOf(s.substring(0, spaceIdx)); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return; } - if (s.length() > spaceIdx + 3) - { + if (s.length() > spaceIdx + 3) { this.cidCallingPresTxt = s.substring(spaceIdx + 2, s.length() - 1); } } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/NewChannelEvent.java b/src/main/java/org/asteriskjava/manager/event/NewChannelEvent.java index 37892fe50..b57e74e17 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewChannelEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewChannelEvent.java @@ -17,94 +17,40 @@ package org.asteriskjava.manager.event; /** - * A NewChannelEvent is triggered when a new channel is created.

    + * A NewChannelEvent is triggered when a new channel is created. + *

    * It is implemented in channel.c * * @author srt * @version $Id$ */ -public class NewChannelEvent extends AbstractChannelStateEvent -{ +public class NewChannelEvent extends AbstractChannelStateEvent { /** * Serializable version identifier. */ static final long serialVersionUID = 1L; + private String language; + private String linkedid; - private String accountCode; - private String context; - private String exten; - - public NewChannelEvent(Object source) - { + public NewChannelEvent(Object source) { super(source); } - /** - * Returns the account code of the new channel.

    - * This property is available since Asterisk 1.6. - * - * @return the account code of the new channel. - * @since 1.0.0 - */ - public String getAccountCode() - { - return accountCode; + public String getLanguage() { + return language; } - /** - * Sets the account code of the new channel. - * - * @param accountCode the account code of the new channel. - * @since 1.0.0 - */ - public void setAccountCode(String accountCode) - { - this.accountCode = accountCode; + public void setLanguage(String language) { + this.language = language; } - /** - * Returns the context of the dialplan entry the channel started at.

    - * This property is available since Asterisk 1.6. - * - * @return the context of the dialplan entry the channel started at. - * @since 1.0.0 - */ - public String getContext() - { - return context; + public String getLinkedid() { + return linkedid; } - /** - * Sets the context of the dialplan entry the channel started at. - * - * @param context the context of the dialplan entry the channel started at. - * @since 1.0.0 - */ - public void setContext(String context) - { - this.context = context; + public void setLinkedid(String linkedid) { + this.linkedid = linkedid; } - /** - * Returns the extension of the dialplan entry the channel started at.

    - * This property is available since Asterisk 1.6. - * - * @return the extension of the dialplan entry the channel started at. - * @since 1.0.0 - */ - public String getExten() - { - return exten; - } - /** - * Sets the extension of the dialplan entry the channel started at. - * - * @param exten the extension of the dialplan entry the channel started at. - * @since 1.0.0 - */ - public void setExten(String exten) - { - this.exten = exten; - } } diff --git a/src/main/java/org/asteriskjava/manager/event/NewConnectedLineEvent.java b/src/main/java/org/asteriskjava/manager/event/NewConnectedLineEvent.java new file mode 100644 index 000000000..c145f5c76 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/NewConnectedLineEvent.java @@ -0,0 +1,62 @@ +package org.asteriskjava.manager.event; + +/** + * Created by plhk on 1/15/15. + */ +public class NewConnectedLineEvent extends ManagerEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + private String channel; + private String uniqueId; + private String language; + private String accountCode; + private String linkedId; + + public NewConnectedLineEvent(Object source) { + super(source); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/NewExtenEvent.java b/src/main/java/org/asteriskjava/manager/event/NewExtenEvent.java index f51996684..ddf71a982 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewExtenEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewExtenEvent.java @@ -17,145 +17,128 @@ package org.asteriskjava.manager.event; /** - * A NewExtenEvent is triggered when a channel is connected to a new extension.

    + * A NewExtenEvent is triggered when a channel is connected to a new extension. + *

    * It is implemented in pbx.c - * + * * @author srt * @version $Id$ */ -public class NewExtenEvent extends ManagerEvent -{ +public class NewExtenEvent extends ManagerEvent { /** * Serializable version identifier */ static final long serialVersionUID = -467486409866099387L; private String uniqueId; - private String context; private String extension; private String application; private String appData; - private Integer priority; private String channel; + private String language; + private String accountCode; + private String linkedId; /** * @param source */ - public NewExtenEvent(Object source) - { + public NewExtenEvent(Object source) { super(source); } + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + /** * Returns the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } /** * Sets the unique id of the channel. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } /** * Returns the name of the application that is executed. */ - public String getApplication() - { + public String getApplication() { return application; } /** * Sets the name of the application that is executed. */ - public void setApplication(String application) - { + public void setApplication(String application) { this.application = application; } /** - * Returns the parameters passed to the application that is executed. The parameters are - * separated by a '|' character. + * Returns the parameters passed to the application that is executed. The + * parameters are separated by a '|' character. */ - public String getAppData() - { + public String getAppData() { return appData; } /** * Sets the parameters passed to the application that is executed. */ - public void setAppData(String appData) - { + public void setAppData(String appData) { this.appData = appData; } /** * Returns the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - /** - * Returns the name of the context of the connected extension. - */ - public String getContext() - { - return context; - } - - /** - * Sets the name of the context of the connected extension. - */ - public void setContext(String context) - { - this.context = context; - } - /** * Returns the extension. */ - public String getExtension() - { + public String getExtension() { return extension; } /** * Sets the extension. */ - public void setExtension(String extension) - { + public void setExtension(String extension) { this.extension = extension; } - /** - * Returns the priority. - */ - public Integer getPriority() - { - return priority; + public String getAccountCode() { + return accountCode; } - /** - * Sets the priority. - */ - public void setPriority(Integer priority) - { - this.priority = priority; + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + } diff --git a/src/main/java/org/asteriskjava/manager/event/NewStateEvent.java b/src/main/java/org/asteriskjava/manager/event/NewStateEvent.java index 628b84012..b6f71f738 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewStateEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewStateEvent.java @@ -19,19 +19,35 @@ /** * A NewStateEvent is triggered when the state of a channel has changed.

    * It is implemented in channel.c - * + * * @author srt * @version $Id$ */ -public class NewStateEvent extends AbstractChannelStateEvent -{ +public class NewStateEvent extends AbstractChannelStateEvent { /** * Serializable version identifier. */ static final long serialVersionUID = -0L; + private String language; + private String linkedId; - public NewStateEvent(Object source) - { + public NewStateEvent(Object source) { super(source); } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/OriginateFailureEvent.java b/src/main/java/org/asteriskjava/manager/event/OriginateFailureEvent.java index f18af74c5..57cb93493 100644 --- a/src/main/java/org/asteriskjava/manager/event/OriginateFailureEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/OriginateFailureEvent.java @@ -20,15 +20,15 @@ * An OriginateFailureEvent is triggered when the execution of an * OriginateAction failed.

    * Deprecated since Asterisk 1.4. - * + * + * @author srt + * @version $Id$ * @see org.asteriskjava.manager.action.OriginateAction * @see OriginateResponseEvent * @deprecated - * @author srt - * @version $Id$ */ -@Deprecated public class OriginateFailureEvent extends OriginateResponseEvent -{ +@Deprecated +public class OriginateFailureEvent extends OriginateResponseEvent { /** * Serializable version identifier */ @@ -37,8 +37,7 @@ /** * @param source */ - public OriginateFailureEvent(Object source) - { + public OriginateFailureEvent(Object source) { super(source); setResponse("Failure"); } diff --git a/src/main/java/org/asteriskjava/manager/event/OriginateResponseEvent.java b/src/main/java/org/asteriskjava/manager/event/OriginateResponseEvent.java index d2086e005..93bf466ee 100644 --- a/src/main/java/org/asteriskjava/manager/event/OriginateResponseEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/OriginateResponseEvent.java @@ -18,174 +18,108 @@ /** * Response to an OriginateAction. - * - * @see org.asteriskjava.manager.action.OriginateAction + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.OriginateAction */ -public class OriginateResponseEvent extends ResponseEvent -{ +public class OriginateResponseEvent extends ResponseEvent { /** * Serial version identifier. */ private static final long serialVersionUID = 910724860608259687L; private String response; private String channel; - private String context; - private String exten; private String uniqueId; private Integer reason; - private String callerIdNum; - private String callerIdName; + private String data; + private String application; /** * @param source */ - public OriginateResponseEvent(Object source) - { + public OriginateResponseEvent(Object source) { super(source); } /** * Returns the result of the corresponding Originate action. - * + * * @return "Success" or "Failure" */ - public String getResponse() - { + public String getResponse() { return response; } /** * Sets the result of the corresponding Originate action. - * + * * @param response "Success" or "Failure" */ - public void setResponse(String response) - { + public void setResponse(String response) { this.response = response; } - - public boolean isSuccess() - { + + public boolean isSuccess() { return "Success".equalsIgnoreCase(response); } /** * Returns the name of the channel to connect to the outgoing call. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel to connect to the outgoing call. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - /** - * Returns the name of the context of the extension to connect to. - */ - public String getContext() - { - return context; - } - - /** - * Sets the name of the context of the extension to connect to. - */ - public void setContext(String context) - { - this.context = context; - } - - /** - * Returns the the extension to connect to. - */ - public String getExten() - { - return exten; - } - - /** - * Sets the the extension to connect to. - */ - public void setExten(String exten) - { - this.exten = exten; - } - - public Integer getReason() - { + public Integer getReason() { return reason; } - public void setReason(Integer reason) - { + public void setReason(Integer reason) { this.reason = reason; } /** * Returns the unique id of the originated channel. - * + * * @return the unique id of the originated channel or "<null>" if none - * is available. + * is available. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } - /** - * Returns the Caller*ID Number of the originated channel. - *

    - * Available sind Asterisk 1.4. - * - * @return the Caller*ID Number of the originated channel or null if none was set. - * @since 0.3 - */ - public String getCallerIdNum() - { - return callerIdNum; + // for backward compatibility only + public void setCallerId(String callerId) { + if (getCallerIdNum() == null) { + setCallerIdNum(callerId); + } } - public void setCallerIdNum(String callerId) - { - this.callerIdNum = callerId; + public String getData() { + return data; } - // for backward compatibility only - public void setCallerId(String callerId) - { - if (this.callerIdNum == null) - { - this.callerIdNum = callerId; - } + public void setData(String data) { + this.data = data; } - /** - * Returns the Caller*ID Name of the originated channel. - *

    - * Available sind Asterisk 1.4. - * - * @return the Caller*ID Name of the originated channel or null if none was set. - */ - public String getCallerIdName() - { - return callerIdName; + public String getApplication() { + return application; } - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; + public void setApplication(String application) { + this.application = application; } } diff --git a/src/main/java/org/asteriskjava/manager/event/OriginateSuccessEvent.java b/src/main/java/org/asteriskjava/manager/event/OriginateSuccessEvent.java index d3f92c4aa..7bfea6206 100644 --- a/src/main/java/org/asteriskjava/manager/event/OriginateSuccessEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/OriginateSuccessEvent.java @@ -20,15 +20,15 @@ * An OriginateSuccessEvent is triggered when the execution of an * OriginateAction succeeded.

    * Deprecated since Asterisk 1.4. - * + * + * @author srt + * @version $Id$ * @see org.asteriskjava.manager.action.OriginateAction * @see OriginateResponseEvent * @deprecated - * @author srt - * @version $Id$ */ -@Deprecated public class OriginateSuccessEvent extends OriginateResponseEvent -{ +@Deprecated +public class OriginateSuccessEvent extends OriginateResponseEvent { /** * Serializable version identifier */ @@ -37,8 +37,7 @@ /** * @param source */ - public OriginateSuccessEvent(Object source) - { + public OriginateSuccessEvent(Object source) { super(source); setResponse("Success"); } diff --git a/src/main/java/org/asteriskjava/manager/event/ParkedCallEvent.java b/src/main/java/org/asteriskjava/manager/event/ParkedCallEvent.java index 310e75fd8..aef32c1d1 100644 --- a/src/main/java/org/asteriskjava/manager/event/ParkedCallEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ParkedCallEvent.java @@ -18,72 +18,67 @@ /** * A ParkedCallEvent is triggered when a channel is parked (in this case no - * action id is set) and in response to a ParkedCallsAction.

    + * action id is set) and in response to a ParkedCallsAction. + *

    * It is implemented in res/res_features.c - * - * @see org.asteriskjava.manager.action.ParkedCallsAction + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.ParkedCallsAction */ -public class ParkedCallEvent extends AbstractParkedCallEvent -{ +public class ParkedCallEvent extends AbstractParkedCallEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 0L; - - private String from; + private Integer timeout; - + private String parkeelinkedid; /** * @param source */ - public ParkedCallEvent(Object source) - { + public ParkedCallEvent(Object source) { super(source); } /** - * Returns the name of the channel that parked the call. + * Returns the number of seconds this call will be parked. + *

    + * This corresponds to the parkingtime option in + * features.conf. */ - public String getFrom() - { - return from; + public Integer getTimeout() { + return timeout; } /** - * Sets the name of the channel that parked the call. + * Sets the number of seconds this call will be parked. */ - public void setFrom(String from) - { - this.from = from; + public void setTimeout(Integer timeout) { + this.timeout = timeout; } /** - * Returns the number of seconds this call will be parked.

    - * This corresponds to the parkingtime option in - * features.conf. + * Sets the unique id of the parked channel as a workaround for a typo in + * asterisk manager event. */ - public Integer getTimeout() - { - return timeout; + public void setUnqiueId(String unqiueId) { + setUniqueId(unqiueId); } /** - * Sets the number of seconds this call will be parked. + * @param parkeelinkedid the parkeelinkedid to set */ - public void setTimeout(Integer timeout) - { - this.timeout = timeout; + public void setParkeelinkedid(String parkeelinkedid) { + this.parkeelinkedid = parkeelinkedid; } - + /** - * Sets the unique id of the parked channel as a - * workaround for a typo in asterisk manager event. + * @return the parkeelinkedid */ - public void setUnqiueId(String unqiueId) - { - setUniqueId(unqiueId); + public String getParkeelinkedid() { + return parkeelinkedid; } + } diff --git a/src/main/java/org/asteriskjava/manager/event/ParkedCallGiveUpEvent.java b/src/main/java/org/asteriskjava/manager/event/ParkedCallGiveUpEvent.java index 944f8dd52..1d0e998ef 100644 --- a/src/main/java/org/asteriskjava/manager/event/ParkedCallGiveUpEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ParkedCallGiveUpEvent.java @@ -18,16 +18,17 @@ /** * A ParkedCallGiveUpEvent is triggered when a channel that has been parked is - * hung up.

    - * It is implemented in res/res_features.c

    + * hung up. + *

    + * It is implemented in res/res_features.c + *

    * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class ParkedCallGiveUpEvent extends AbstractParkedCallEvent -{ +public class ParkedCallGiveUpEvent extends AbstractUnParkedEvent { /** * Serializable version identifier */ @@ -36,8 +37,7 @@ public class ParkedCallGiveUpEvent extends AbstractParkedCallEvent /** * @param source */ - public ParkedCallGiveUpEvent(Object source) - { + public ParkedCallGiveUpEvent(Object source) { super(source); } } diff --git a/src/main/java/org/asteriskjava/manager/event/ParkedCallTimeOutEvent.java b/src/main/java/org/asteriskjava/manager/event/ParkedCallTimeOutEvent.java index 4b241547f..644b6dd0f 100644 --- a/src/main/java/org/asteriskjava/manager/event/ParkedCallTimeOutEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ParkedCallTimeOutEvent.java @@ -18,16 +18,17 @@ /** * A ParkedCallTimeOutEvent is triggered when call parking times out for a given - * channel.

    - * It is implemented in res/res_features.c

    + * channel. + *

    + * It is implemented in res/res_features.c + *

    * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class ParkedCallTimeOutEvent extends AbstractParkedCallEvent -{ +public class ParkedCallTimeOutEvent extends AbstractUnParkedEvent { /** * Serializable version identifier */ @@ -36,8 +37,7 @@ public class ParkedCallTimeOutEvent extends AbstractParkedCallEvent /** * @param source */ - public ParkedCallTimeOutEvent(Object source) - { + public ParkedCallTimeOutEvent(Object source) { super(source); } } diff --git a/src/main/java/org/asteriskjava/manager/event/ParkedCallsCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/ParkedCallsCompleteEvent.java index 254cbab6a..a00d9e10f 100644 --- a/src/main/java/org/asteriskjava/manager/event/ParkedCallsCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ParkedCallsCompleteEvent.java @@ -17,17 +17,15 @@ package org.asteriskjava.manager.event; /** - * A ParkedCallsCompleteEvent is triggered after all parked calls have been reported in response to - * a ParkedCallsAction. - * - * @see org.asteriskjava.manager.action.ParkedCallsAction - * @see org.asteriskjava.manager.event.ParkedCallEvent - * + * A ParkedCallsCompleteEvent is triggered after all parked calls have been + * reported in response to a ParkedCallsAction. + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.ParkedCallsAction + * @see org.asteriskjava.manager.event.ParkedCallEvent */ -public class ParkedCallsCompleteEvent extends ResponseEvent -{ +public class ParkedCallsCompleteEvent extends ResponseEvent { /** * Serializable version identifier */ @@ -36,8 +34,7 @@ public class ParkedCallsCompleteEvent extends ResponseEvent /** * @param source */ - public ParkedCallsCompleteEvent(Object source) - { + public ParkedCallsCompleteEvent(Object source) { super(source); } } diff --git a/src/main/java/org/asteriskjava/manager/event/PausedEvent.java b/src/main/java/org/asteriskjava/manager/event/PausedEvent.java new file mode 100644 index 000000000..b073f8a03 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/PausedEvent.java @@ -0,0 +1,35 @@ +package org.asteriskjava.manager.event; + +public class PausedEvent extends UserEvent { + + public PausedEvent(Object source) { + super(source); + } + + /** + * + */ + private static final long serialVersionUID = 7181269530090027203L; + + private String header; + + private String extension; + + public String getHeader() { + return header; + } + + public void setHeader(String header) { + this.header = header; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java b/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java index 5a67336e0..45244f669 100644 --- a/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java @@ -17,17 +17,20 @@ package org.asteriskjava.manager.event; /** - * A PeerEntryEvent is triggered in response to a {@link org.asteriskjava.manager.action.SipPeersAction}, - * {@link org.asteriskjava.manager.action.SipShowPeerAction} or {@link org.asteriskjava.manager.action.IaxPeerListAction} - * and contains information about a SIP or IAX peer.

    - * It is implemented in channels/chan_sip.c and channels/chan_iax.c + * A PeerEntryEvent is triggered in response to a + * {@link org.asteriskjava.manager.action.SipPeersAction}, + * {@link org.asteriskjava.manager.action.SipShowPeerAction} or + * {@link org.asteriskjava.manager.action.IaxPeerListAction} and contains + * information about a SIP or IAX peer. + *

    + * It is implemented in channels/chan_sip.c and + * channels/chan_iax.c * * @author srt * @version $Id$ * @since 0.2 */ -public class PeerEntryEvent extends ResponseEvent -{ +public class PeerEntryEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -44,6 +47,7 @@ public class PeerEntryEvent extends ResponseEvent private Integer port; private Boolean dynamic; private Boolean natSupport; + private Boolean forceRport; private Boolean videoSupport; private Boolean textSupport; private Boolean acl; @@ -51,14 +55,18 @@ public class PeerEntryEvent extends ResponseEvent private String realtimeDevice; private Boolean trunk; private String encryption; + private String autoComedia; + private String autoForcerport; + private String comedia; + private String description; + private String accountcode; /** * Creates a new instance. * * @param source */ - public PeerEntryEvent(Object source) - { + public PeerEntryEvent(Object source) { super(source); } @@ -69,23 +77,19 @@ public PeerEntryEvent(Object source) * @see #CHANNEL_TYPE_SIP * @see #CHANNEL_TYPE_IAX */ - public String getChannelType() - { + public String getChannelType() { return channelType; } - public void setChannelType(String channelType) - { + public void setChannelType(String channelType) { this.channelType = channelType; } - public String getObjectName() - { + public String getObjectName() { return objectName; } - public void setObjectName(String objectName) - { + public void setObjectName(String objectName) { this.objectName = objectName; } @@ -93,13 +97,11 @@ public void setObjectName(String objectName) * @return * @since 1.0.0 */ - public String getObjectUserName() - { + public String getObjectUserName() { return objectUserName; } - public void setObjectUserName(String objectUserName) - { + public void setObjectUserName(String objectUserName) { this.objectUserName = objectUserName; } @@ -108,13 +110,11 @@ public void setObjectUserName(String objectUserName) * * @return "peer" or "user". */ - public String getChanObjectType() - { + public String getChanObjectType() { return chanObjectType; } - public void setChanObjectType(String chanObjectType) - { + public void setChanObjectType(String chanObjectType) { this.chanObjectType = chanObjectType; } @@ -123,8 +123,7 @@ public void setChanObjectType(String chanObjectType) * * @return the IP address of the peer or "-none-" if none is available. */ - public String getIpAddress() - { + public String getIpAddress() { return ipAddress; } @@ -133,8 +132,7 @@ public String getIpAddress() * * @param ipAddress the IP address of the peer. */ - public void setIpAddress(String ipAddress) - { + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } @@ -144,13 +142,12 @@ public void setIpAddress(String ipAddress) * @return the port of the peer. * @deprecated since 1.0.0, use {@link #getPort()} instead. */ - @Deprecated public Integer getIpPort() - { + @Deprecated + public Integer getIpPort() { return port; } - public void setIpPort(Integer ipPort) - { + public void setIpPort(Integer ipPort) { this.port = ipPort; } @@ -160,43 +157,52 @@ public void setIpPort(Integer ipPort) * @return the port of the peer. * @since 1.0.0 */ - public Integer getPort() - { + public Integer getPort() { return port; } - public void setPort(Integer port) - { + public void setPort(Integer port) { this.port = port; } - public Boolean getDynamic() - { + public Boolean getDynamic() { return dynamic; } - public void setDynamic(Boolean dynamic) - { + public void setDynamic(Boolean dynamic) { this.dynamic = dynamic; } - public Boolean getNatSupport() - { + public Boolean getNatSupport() { return natSupport; } - public void setNatSupport(Boolean natSupport) - { + public void setNatSupport(Boolean natSupport) { this.natSupport = natSupport; } + /** + * Returns whether the nat option is set to force_rport.
    + * Available since Asterisk 1.8 + * + * @return true if the nat option is set to + * force_rport, false otherwise or + * null if not supported by Asterisk. + */ + public Boolean getForceRport() { + return forceRport; + } + + public void setForceRport(Boolean forceRport) { + this.forceRport = forceRport; + } + /** * Available since Asterisk 1.4. * * @since 0.3 */ - public Boolean getVideoSupport() - { + public Boolean getVideoSupport() { return videoSupport; } @@ -205,41 +211,39 @@ public Boolean getVideoSupport() * * @since 0.3 */ - public void setVideoSupport(Boolean videoSupport) - { + public void setVideoSupport(Boolean videoSupport) { this.videoSupport = videoSupport; } /** - * Returns whether the peer supports text messages.

    + * Returns whether the peer supports text messages. + *

    * Available since Asterisk 1.6. * - * @return true if the peer supports text messages, false otherwise or - * null if the property is not set (i.e. for Asterisk prior to 1.6). + * @return true if the peer supports text messages, + * false otherwise or null if the property + * is not set (i.e. for Asterisk prior to 1.6). * @since 1.0.0 */ - public Boolean getTextSupport() - { + public Boolean getTextSupport() { return textSupport; } - public void setTextSupport(Boolean textSupport) - { + public void setTextSupport(Boolean textSupport) { this.textSupport = textSupport; } - public Boolean getAcl() - { + public Boolean getAcl() { return acl; } - public void setAcl(Boolean acl) - { + public void setAcl(Boolean acl) { this.acl = acl; } /** - * Returns the status of this peer.

    + * Returns the status of this peer. + *

    * For SIP peers this is one of: *

    *
    "UNREACHABLE"
    @@ -256,8 +260,7 @@ public void setAcl(Boolean acl) * * @return the status of this peer. */ - public String getStatus() - { + public String getStatus() { return status; } @@ -266,8 +269,7 @@ public String getStatus() * * @param status the status of this peer. */ - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } @@ -276,8 +278,7 @@ public void setStatus(String status) * * @since 0.3 */ - public String getRealtimeDevice() - { + public String getRealtimeDevice() { return realtimeDevice; } @@ -286,35 +287,103 @@ public String getRealtimeDevice() * * @since 0.3 */ - public void setRealtimeDevice(String realtimeDevice) - { + public void setRealtimeDevice(String realtimeDevice) { this.realtimeDevice = realtimeDevice; } /** - * Returns whether to use IAX2 trunking with this peer.

    + * Returns whether to use IAX2 trunking with this peer. + *

    * Available since Asterisk 1.6. * - * @return true if trunking is used, false if not or null if not set. + * @return true if trunking is used, false if not + * or null if not set. * @since 1.0.0 */ - public Boolean getTrunk() - { + public Boolean getTrunk() { return trunk; } - public void setTrunk(Boolean trunk) - { + public void setTrunk(Boolean trunk) { this.trunk = trunk; } - public String getEncryption() - { + public String getEncryption() { return encryption; } - public void setEncryption(String encryption) - { + public void setEncryption(String encryption) { this.encryption = encryption; } + + /** + * @return the autoComedia + */ + public String getAutoComedia() { + return autoComedia; + } + + /** + * @param autoComedia the autoComedia to set + */ + public void setAutoComedia(String autoComedia) { + this.autoComedia = autoComedia; + } + + /** + * @return the autoForcerport + */ + public String getAutoForcerport() { + return autoForcerport; + } + + /** + * @param autoForcerport the autoForcerport to set + */ + public void setAutoForcerport(String autoForcerport) { + this.autoForcerport = autoForcerport; + } + + /** + * @return the comedia + */ + public String getComedia() { + return comedia; + } + + /** + * @param comedia the comedia to set + */ + public void setComedia(String comedia) { + this.comedia = comedia; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @param the description to set + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the accountcode + */ + public String getAccountcode() { + return accountcode; + } + + /** + * @param the accountcode to set + */ + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } + } diff --git a/src/main/java/org/asteriskjava/manager/event/PeerStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/PeerStatusEvent.java index cce7bb057..3fd689d25 100644 --- a/src/main/java/org/asteriskjava/manager/event/PeerStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/PeerStatusEvent.java @@ -25,8 +25,7 @@ * @author srt * @version $Id$ */ -public class PeerStatusEvent extends ManagerEvent -{ +public class PeerStatusEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -50,8 +49,7 @@ public class PeerStatusEvent extends ManagerEvent /** * @param source */ - public PeerStatusEvent(Object source) - { + public PeerStatusEvent(Object source) { super(source); } @@ -63,8 +61,7 @@ public PeerStatusEvent(Object source) * @return the type of channel that registers. * @since 1.0.0 */ - public String getChannelType() - { + public String getChannelType() { return channelType; } @@ -74,8 +71,7 @@ public String getChannelType() * @param channelType the type of channel that registers * @since 1.0.0 */ - public void setChannelType(String channelType) - { + public void setChannelType(String channelType) { this.channelType = channelType; } @@ -83,21 +79,19 @@ public void setChannelType(String channelType) * Returns the name of the peer that registered.

    * The peer name includes the channel type prefix. So if you receive a PeerStatusEvent for a * SIP peer defined as "john" in sip.conf this method returns "SIP/john". - *

    + *
    * Peer names for IAX clients start with "IAX2/", peer names for SIP clients start with "SIP/". * * @return the peer's name including the channel type. */ - public String getPeer() - { + public String getPeer() { return peer; } /** * Sets the name of the peer that registered. */ - public void setPeer(String peer) - { + public void setPeer(String peer) { this.peer = peer; } @@ -113,16 +107,14 @@ public void setPeer(String peer) *

  • Rejected (IAX only)
  • * */ - public String getPeerStatus() - { + public String getPeerStatus() { return peerStatus; } /** * Sets the registration state. */ - public void setPeerStatus(String peerStatus) - { + public void setPeerStatus(String peerStatus) { this.peerStatus = peerStatus; } @@ -134,16 +126,14 @@ public void setPeerStatus(String peerStatus) * * @return the cause of a rejection or unregistration. */ - public String getCause() - { + public String getCause() { return cause; } /** * Sets the cause of the rejection or unregistration. */ - public void setCause(String cause) - { + public void setCause(String cause) { this.cause = cause; } @@ -152,13 +142,11 @@ public void setCause(String cause) * equals "Unreachable" it returns how long the last response took (in ms) for IAX peers or -1 * for SIP peers. */ - public Integer getTime() - { + public Integer getTime() { return time; } - public void setTime(Integer time) - { + public void setTime(Integer time) { this.time = time; } @@ -169,13 +157,11 @@ public void setTime(Integer time) * @return the IP address of the peer that registered or null if not available. * @since 1.0.0 */ - public String getAddress() - { + public String getAddress() { return address; } - public void setAddress(String address) - { + public void setAddress(String address) { this.address = address; } @@ -186,13 +172,11 @@ public void setAddress(String address) * @return the port of the peer that registered or null if not available. * @since 1.0.0 */ - public Integer getPort() - { + public Integer getPort() { return port; } - public void setPort(Integer port) - { + public void setPort(Integer port) { this.port = port; } } diff --git a/src/main/java/org/asteriskjava/manager/event/PeerlistCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/PeerlistCompleteEvent.java index c98e42ace..f81453328 100644 --- a/src/main/java/org/asteriskjava/manager/event/PeerlistCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/PeerlistCompleteEvent.java @@ -20,16 +20,15 @@ * A PeerlistCompleteEvent is triggered after the details of all peers has been reported in response * to an SIPPeersAction or SIPShowPeerAction.

    * Available since Asterisk 1.2 - * + * + * @author srt + * @version $Id$ * @see org.asteriskjava.manager.event.PeerEntryEvent * @see org.asteriskjava.manager.action.SipPeersAction * @see org.asteriskjava.manager.action.SipShowPeerAction - * @author srt - * @version $Id$ * @since 0.2 */ -public class PeerlistCompleteEvent extends ResponseEvent -{ +public class PeerlistCompleteEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -39,31 +38,28 @@ public class PeerlistCompleteEvent extends ResponseEvent /** * Creates a new instance. - * + * * @param source */ - public PeerlistCompleteEvent(Object source) - { + public PeerlistCompleteEvent(Object source) { super(source); } /** * Returns the number of PeerEvents that have been reported. - * + * * @return the number of PeerEvents that have been reported. */ - public Integer getListItems() - { + public Integer getListItems() { return listItems; } /** * Sets the number of PeerEvents that have been reported. - * + * * @param listItems the number of PeerEvents that have been reported. */ - public void setListItems(Integer listItems) - { + public void setListItems(Integer listItems) { this.listItems = listItems; } @@ -74,13 +70,11 @@ public void setListItems(Integer listItems) * @return always returns "Complete" confirming that all PeerEntry events have been sent. * @since 1.0.0 */ - public String getEventList() - { + public String getEventList() { return eventList; } - public void setEventList(String eventList) - { + public void setEventList(String eventList) { this.eventList = eventList; } } diff --git a/src/main/java/org/asteriskjava/manager/event/PeersEvent.java b/src/main/java/org/asteriskjava/manager/event/PeersEvent.java new file mode 100644 index 000000000..5a4ed9f11 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/PeersEvent.java @@ -0,0 +1,58 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +import java.util.List; + +/** + * A PeersEvent is triggered in response to a {@link org.asteriskjava.manager.action.SipPeersAction}, + * {@link org.asteriskjava.manager.action.SipShowPeerAction} or {@link org.asteriskjava.manager.action.IaxPeerListAction} + * and contains information about a SIP or IAX peers.

    + * It is implemented in channels/chan_sip.c and channels/chan_iax.c + * + * @author ddpaul + * @version $Id$ + * @since 0.2 + */ +public class PeersEvent extends ResponseEvent { + /** + * Serial version identifier. + */ + private static final long serialVersionUID = 0L; + + /** + * This field holds actual information about SIP/IAX peers + */ + private List childEvents; + + /** + * Creates a new instance. + * + * @param source + */ + public PeersEvent(Object source) { + super(source); + } + + public List getChildEvents() { + return childEvents; + } + + public void setChildEvents(List childEvents) { + this.childEvents = childEvents; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/PickupEvent.java b/src/main/java/org/asteriskjava/manager/event/PickupEvent.java new file mode 100644 index 000000000..13e47466e --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/PickupEvent.java @@ -0,0 +1,184 @@ +package org.asteriskjava.manager.event; + +public class PickupEvent extends ManagerEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + private String accountcode; + private String channel; + private String language; + private String linkedid; + private String targetaccountcode; + private String targetcalleridname; + private String targetcalleridnum; + private String targetchannel; + private String targetchannelstate; + private String targetchannelstatedesc; + private String targetconnectedlinename; + private String targetconnectedlinenum; + private String targetcontext; + private String targetexten; + private String targetlanguage; + private String targetlinkedid; + private String targetpriority; + private String targetuniqueid; + private String uniqueid; + + public PickupEvent(Object source) { + super(source); + } + + public String getAccountcode() { + return accountcode; + } + + public String getChannel() { + return channel; + } + + public String getLanguage() { + return language; + } + + public String getLinkedid() { + return linkedid; + } + + public String getTargetaccountcode() { + return targetaccountcode; + } + + public String getTargetcalleridname() { + return targetcalleridname; + } + + public String getTargetcalleridnum() { + return targetcalleridnum; + } + + public String getTargetchannel() { + return targetchannel; + } + + public String getTargetchannelstate() { + return targetchannelstate; + } + + public String getTargetchannelstatedesc() { + return targetchannelstatedesc; + } + + public String getTargetconnectedlinename() { + return targetconnectedlinename; + } + + public String getTargetconnectedlinenum() { + return targetconnectedlinenum; + } + + public String getTargetcontext() { + return targetcontext; + } + + public String getTargetexten() { + return targetexten; + } + + public String getTargetlanguage() { + return targetlanguage; + } + + public String getTargetlinkedid() { + return targetlinkedid; + } + + public String getTargetpriority() { + return targetpriority; + } + + public String getTargetuniqueid() { + return targetuniqueid; + } + + public String getUniqueid() { + return uniqueid; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public void setLanguage(String language) { + this.language = language; + } + + public void setLinkedid(String linkedid) { + this.linkedid = linkedid; + } + + public void setTargetaccountcode(String targetaccountcode) { + this.targetaccountcode = targetaccountcode; + } + + public void setTargetcalleridname(String targetcalleridname) { + this.targetcalleridname = targetcalleridname; + } + + public void setTargetcalleridnum(String targetcalleridnum) { + this.targetcalleridnum = targetcalleridnum; + } + + public void setTargetchannel(String targetchannel) { + this.targetchannel = targetchannel; + } + + public void setTargetchannelstate(String targetchannelstate) { + this.targetchannelstate = targetchannelstate; + } + + public void setTargetchannelstatedesc(String targetchannelstatedesc) { + this.targetchannelstatedesc = targetchannelstatedesc; + } + + public void setTargetconnectedlinename(String targetconnectedlinename) { + this.targetconnectedlinename = targetconnectedlinename; + } + + public void setTargetconnectedlinenum(String targetconnectedlinenum) { + this.targetconnectedlinenum = targetconnectedlinenum; + } + + public void setTargetcontext(String targetcontext) { + this.targetcontext = targetcontext; + } + + public void setTargetexten(String targetexten) { + this.targetexten = targetexten; + } + + public void setTargetlanguage(String targetlanguage) { + this.targetlanguage = targetlanguage; + } + + public void setTargetlinkedid(String targetlinkedid) { + this.targetlinkedid = targetlinkedid; + } + + public void setTargetpriority(String targetpriority) { + this.targetpriority = targetpriority; + } + + public void setTargetuniqueid(String targetuniqueid) { + this.targetuniqueid = targetuniqueid; + } + + public void setUniqueid(String uniqueid) { + this.uniqueid = uniqueid; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/PriEventEvent.java b/src/main/java/org/asteriskjava/manager/event/PriEventEvent.java index 3b82cc4ba..47908969e 100644 --- a/src/main/java/org/asteriskjava/manager/event/PriEventEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/PriEventEvent.java @@ -8,16 +8,14 @@ * @version $Id$ * @since 1.0.0 */ -public class PriEventEvent extends ManagerEvent -{ - private static final long serialVersionUID = 3257069450639290810L; - private String priEvent; +public class PriEventEvent extends ManagerEvent { + private static final long serialVersionUID = 3257069450639290810L; + private String priEvent; private Integer priEventCode; private String dChannel; private Integer span; - public PriEventEvent(Object source) - { + public PriEventEvent(Object source) { super(source); } @@ -48,13 +46,11 @@ public PriEventEvent(Object source) * @return the textual representation of the event code. * @see #getPriEventCode() */ - public String getPriEvent() - { + public String getPriEvent() { return priEvent; } - public void setPriEvent(String priEvent) - { + public void setPriEvent(String priEvent) { this.priEvent = priEvent; } @@ -64,13 +60,11 @@ public void setPriEvent(String priEvent) * @return the numerical pri event code. * @see #getPriEvent() */ - public Integer getPriEventCode() - { + public Integer getPriEventCode() { return priEventCode; } - public void setPriEventCode(Integer priEventCode) - { + public void setPriEventCode(Integer priEventCode) { this.priEventCode = priEventCode; } @@ -79,13 +73,11 @@ public void setPriEventCode(Integer priEventCode) * * @return the D-Channel the event occurred on. */ - public String getDChannel() - { + public String getDChannel() { return dChannel; } - public void setDChannel(String dChannel) - { + public void setDChannel(String dChannel) { this.dChannel = dChannel; } @@ -94,13 +86,11 @@ public void setDChannel(String dChannel) * * @return the span the event occurred on. */ - public Integer getSpan() - { + public Integer getSpan() { return span; } - public void setSpan(Integer span) - { + public void setSpan(Integer span) { this.span = span; } } diff --git a/src/main/java/org/asteriskjava/manager/event/ProtocolIdentifierReceivedEvent.java b/src/main/java/org/asteriskjava/manager/event/ProtocolIdentifierReceivedEvent.java index fa45bf69f..381f3960d 100644 --- a/src/main/java/org/asteriskjava/manager/event/ProtocolIdentifierReceivedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ProtocolIdentifierReceivedEvent.java @@ -17,17 +17,16 @@ package org.asteriskjava.manager.event; /** - * A ProtocolIdentifierReceivedEvent is triggered when the network connection to the Asterisk + * A ProtocolIdentifierReceivedEvent is triggered when the network connection to the Asterisk * server has been established and the protocol identifier has been sent.

    * It is a pseudo event not directly related to an Asterisk generated event.

    * The ProtocolIdentifierReceivedEvent is not dispatched to clients so you will * probably never see it. - * + * * @author srt * @version $Id$ */ -public class ProtocolIdentifierReceivedEvent extends ManagerEvent -{ +public class ProtocolIdentifierReceivedEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -41,28 +40,25 @@ public class ProtocolIdentifierReceivedEvent extends ManagerEvent /** * @param source */ - public ProtocolIdentifierReceivedEvent(Object source) - { + public ProtocolIdentifierReceivedEvent(Object source) { super(source); } /** * Returns the version of the protocol. - * + * * @return the version of the protocol. */ - public String getProtocolIdentifier() - { + public String getProtocolIdentifier() { return protocolIdentifier; } /** * Sets the version of the protocol. - * + * * @param protocolIdentifier the version of the protocol. */ - public void setProtocolIdentifier(String protocolIdentifier) - { + public void setProtocolIdentifier(String protocolIdentifier) { this.protocolIdentifier = protocolIdentifier; } } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueCallerAbandonEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueCallerAbandonEvent.java index 06346d8f3..56780e21b 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueCallerAbandonEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueCallerAbandonEvent.java @@ -23,11 +23,10 @@ * It is implemented in apps/app_queue.c *

    * Available since Asterisk 1.4. - * + * * @author martins */ -public class QueueCallerAbandonEvent extends QueueEvent -{ +public class QueueCallerAbandonEvent extends QueueEvent { /** * Serializable version identifier */ @@ -36,61 +35,82 @@ public class QueueCallerAbandonEvent extends QueueEvent private Integer position; private Integer originalPosition; private Integer holdTime; + private String linkedId; + private String language; + + private String accountcode; /** * @param source */ - public QueueCallerAbandonEvent(Object source) - { + public QueueCallerAbandonEvent(Object source) { super(source); } /** * @return the amount of time in seconds the caller was on hold */ - public Integer getHoldTime() - { + public Integer getHoldTime() { return holdTime; } /** * @param holdTime the amount of time in seconds the caller was on hold */ - public void setHoldTime(Integer holdTime) - { + public void setHoldTime(Integer holdTime) { this.holdTime = holdTime; } /** * @return the original position of the caller in the queue */ - public Integer getOriginalPosition() - { + public Integer getOriginalPosition() { return originalPosition; } /** * @param originalPosition the original position of the caller in the queue */ - public void setOriginalPosition(Integer originalPosition) - { + public void setOriginalPosition(Integer originalPosition) { this.originalPosition = originalPosition; } /** * @return the position of the caller at the time they abandoned the queue */ - public Integer getPosition() - { + public Integer getPosition() { return position; } /** * @param position the position of the caller at the time they abandoned the - * queue + * queue */ - public void setPosition(Integer position) - { + public void setPosition(Integer position) { this.position = position; } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueCallerJoinEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueCallerJoinEvent.java new file mode 100644 index 000000000..121df3ff5 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/QueueCallerJoinEvent.java @@ -0,0 +1,88 @@ +/* + * Copyright 2004-2007 Stefan Reuter and others + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A QueueCallerJoinEvent is triggered when a caller join a queue before + * getting connected with an agent. + *

    + * It is implemented in apps/app_queue.c + *

    + * Available since Asterisk 1.4. + * + * @author Leonardo de Souza + */ +public class QueueCallerJoinEvent extends QueueEvent { + + /** + * Serializable version identifier + */ + private static final long serialVersionUID = 812069706662063872L; + + private Integer position; + private String linkedId; + private String language; + private String accountcode; + + /** + * @param source + */ + public QueueCallerJoinEvent(Object source) { + super(source); + } + + /** + * @return the position of the caller at the time they abandoned the queue + */ + public Integer getPosition() { + return position; + } + + /** + * @param position the position of the caller at the time they abandoned the + * queue + */ + public void setPosition(Integer position) { + this.position = position; + } + + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/QueueCallerLeaveEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueCallerLeaveEvent.java new file mode 100644 index 000000000..56e8862cf --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/QueueCallerLeaveEvent.java @@ -0,0 +1,87 @@ +/* + * Copyright 2004-2007 Stefan Reuter and others + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A QueueCallerLeaveEvent is triggered when a caller leave a queue before + * getting connected with an agent. + *

    + * It is implemented in apps/app_queue.c + *

    + * Available since Asterisk 1.4. + * + * @author Leonardo de Souza + */ +public class QueueCallerLeaveEvent extends QueueEvent { + + /** + * Serializable version identifier + */ + private static final long serialVersionUID = 812069706662063871L; + + private Integer position; + private String language; + private String linkedId; + + private String accountcode; + + /** + * @param source + */ + public QueueCallerLeaveEvent(Object source) { + super(source); + } + + /** + * @return the position of the caller at the time they abandoned the queue + */ + public Integer getPosition() { + return position; + } + + /** + * @param position the position of the caller at the time they abandoned the + * queue + */ + public void setPosition(Integer position) { + this.position = position; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = accountcode; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/QueueEntryEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueEntryEvent.java index a9543ab1e..b48c923e4 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueEntryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueEntryEvent.java @@ -18,15 +18,15 @@ /** * A QueueEntryEvent is triggered in response to a QueueStatusAction and - * contains information about an entry in a queue.

    + * contains information about an entry in a queue. + *

    * It is implemented in apps/app_queue.c * * @author srt * @version $Id: QueueEntryEvent.java 1360 2009-09-04 01:08:57Z srt $ * @see org.asteriskjava.manager.action.QueueStatusAction */ -public class QueueEntryEvent extends ResponseEvent -{ +public class QueueEntryEvent extends ResponseEvent { /** * Serializable version identifier */ @@ -36,72 +36,63 @@ public class QueueEntryEvent extends ResponseEvent private String uniqueId; private String channel; private String callerId; - private String callerIdName; - private String callerIdNum; private Long wait; /** * @param source */ - public QueueEntryEvent(Object source) - { + public QueueEntryEvent(Object source) { super(source); } /** * Returns the name of the queue that contains this entry. */ - public String getQueue() - { + public String getQueue() { return queue; } /** * Sets the name of the queue that contains this entry. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } /** * Returns the position of this entry in the queue. */ - public Integer getPosition() - { + public Integer getPosition() { return position; } /** * Sets the position of this entry in the queue. */ - public void setPosition(Integer position) - { + public void setPosition(Integer position) { this.position = position; } /** * Returns the name of the channel of this entry. */ - public String getChannel() - { + public String getChannel() { return channel; } /** - * Returns the unique id of the channel of this entry.

    + * Returns the unique id of the channel of this entry. + *

    * Available since Asterisk 1.6. * * @return the unique id of the channel of this entry. * @since 1.0.0 */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -110,88 +101,40 @@ public void setUniqueId(String uniqueId) * * @param channel the name of the channel of this entry. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - /** + /** * Returns the the Caller*ID number of this entry. * * @return the the Caller*ID number of this entry. */ - public String getCallerId() - { - return callerId; - } + public String getCallerId() { + return callerId; + } /** * Sets the the Caller*ID number of this entry. * * @param callerId the the Caller*ID number of this entry. */ - public void setCallerId(String callerId) - { - this.callerId = callerId; - } - - /** - * Returns the Caller*ID name of this entry. - * - * @return the Caller*ID name of this entry. - * @since 0.2 - */ - public String getCallerIdName() - { - return callerIdName; - } - - /** - * Sets the Caller*ID name of this entry. - * - * @param callerIdName the Caller*ID name of this entry. - * @since 0.2 - */ - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; - } - - /** - * Gets the Caller*ID num of this entry. - * - * @return the Caller*ID num of this entry. - * @since 1.0.0 - */ - public String getCallerIdNum() - { - return callerIdNum; - } - - /** - * Sets the Caller*ID num of this entry. - * - * @param callerIdNum the Caller*ID num of this entry. - * @since 1.0.0 - */ - public void setCallerIdNum(String callerIdNum) - { - this.callerIdNum = callerIdNum; + public void setCallerId(String callerId) { + this.callerId = callerId; } /** * Returns the number of seconds this entry has spent in the queue. */ - public Long getWait() - { + public Long getWait() { return wait; } /** * Sets the number of seconds this entry has spent in the queue. */ - public void setWait(Long wait) - { + public void setWait(Long wait) { this.wait = wait; } + } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueEvent.java index 862c6ca1a..c733fc0a4 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueEvent.java @@ -18,12 +18,11 @@ /** * Abstract base class providing common properties for JoinEvent and LeaveEvent. - * + * * @author srt * @version $Id$ */ -public abstract class QueueEvent extends ManagerEvent -{ +public abstract class QueueEvent extends ManagerEvent { /** * Serializable version identifier */ @@ -37,8 +36,7 @@ public abstract class QueueEvent extends ManagerEvent /** * @param source */ - public QueueEvent(Object source) - { + public QueueEvent(Object source) { super(source); } @@ -47,40 +45,36 @@ public QueueEvent(Object source) * This property is only available since Asterisk 1.4. Up to Asterisk 1.2 * this method always returns null.

    * See Asterisk issues 6458 and 7002. - * + * * @return the unique id of the channel that joines or leaves the queue or - * null if not supported by your Asterisk server. + * null if not supported by your Asterisk server. * @since 0.3 */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } /** * Sets the unique id of the channel that joines or leaves the queue. - * + * * @param uniqueId the unique id of the channel that joines or leaves the queue. * @since 0.3 */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } /** * Returns the name of the channel that joines or leaves the queue. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel that joines or leaves the queue. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -88,32 +82,28 @@ public void setChannel(String channel) * Returns the number of elements in the queue, i.e. the number of calls waiting to be answered * by an agent. */ - public Integer getCount() - { + public Integer getCount() { return count; } /** * Sets the number of elements in the queue. */ - public void setCount(Integer count) - { + public void setCount(Integer count) { this.count = count; } /** * Returns the name of the queue. */ - public String getQueue() - { + public String getQueue() { return queue; } /** * Sets the name of the queue. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueMemberAddedEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueMemberAddedEvent.java index 6b2500f87..9bf217bc7 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueMemberAddedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberAddedEvent.java @@ -20,13 +20,12 @@ * A QueueMemberAddedEvent is triggered when a queue member is added to a queue.

    * It is implemented in apps/app_queue.c.

    * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class QueueMemberAddedEvent extends AbstractQueueMemberEvent -{ +public class QueueMemberAddedEvent extends AbstractQueueMemberEvent { /** * Serial version identifier. */ @@ -39,95 +38,92 @@ public class QueueMemberAddedEvent extends AbstractQueueMemberEvent private Integer status; private Boolean paused; - public QueueMemberAddedEvent(Object source) - { + private String stateinterface; + private Boolean ringinuse; + private Integer logintime; + private Integer wrapuptime; + private Integer lastpause; + + public QueueMemberAddedEvent(Object source) { super(source); } /** * Returns if the added member is a dynamic or static queue member. - * + * * @return "dynamic" if the added member is a dynamic queue member, "static" - * if the added member is a static queue member. + * if the added member is a static queue member. */ - public String getMembership() - { + public String getMembership() { return membership; } /** * Sets if the added member is a dynamic or static queue member. - * + * * @param membership "dynamic" if the added member is a dynamic queue - * member, "static" if the added member is a static queue member. + * member, "static" if the added member is a static queue member. */ - public void setMembership(String membership) - { + public void setMembership(String membership) { this.membership = membership; } /** * Returns the penalty for the added member. When calls are distributed * members with higher penalties are considered last. - * + * * @return the penalty for the added member. */ - public Integer getPenalty() - { + public Integer getPenalty() { return penalty; } /** * Sets the penalty for this member. - * + * * @param penalty the penalty for this member. */ - public void setPenalty(Integer penalty) - { + public void setPenalty(Integer penalty) { this.penalty = penalty; } /** * Returns the number of calls answered by the member. - * + * * @return the number of calls answered by the member. */ - public Integer getCallsTaken() - { + public Integer getCallsTaken() { return callsTaken; } /** * Sets the number of calls answered by the added member. - * + * * @param callsTaken the number of calls answered by the added member. */ - public void setCallsTaken(Integer callsTaken) - { + public void setCallsTaken(Integer callsTaken) { this.callsTaken = callsTaken; } /** * Returns the time the last successful call answered by the added member * was hungup. - * + * * @return the time (in seconds since 01/01/1970) the last successful call - * answered by the added member was hungup. + * answered by the added member was hungup. */ - public Long getLastCall() - { + public Long getLastCall() { return lastCall; } /** * Sets the time the last successful call answered by this member was * hungup. - * + * * @param lastCall the time (in seconds since 01/01/1970) the last - * successful call answered by the added member was hungup. + * successful call answered by the added member was hungup. */ - public void setLastCall(Long lastCall) - { + public void setLastCall(Long lastCall) { this.lastCall = lastCall; } @@ -148,43 +144,79 @@ public void setLastCall(Long lastCall) *

    AST_DEVICE_UNAVAILABLE (5)
    *
    ?
    *
    - * + * * @return the status of this queue member. */ - public Integer getStatus() - { + public Integer getStatus() { return status; } /** * Sets the status of this queue member. - * + * * @param status the status of this queue member */ - public void setStatus(Integer status) - { + public void setStatus(Integer status) { this.status = status; } /** * Returns if this queue member is paused (not accepting calls).

    - * + * * @return Boolean.TRUE if this member has been paused or - * Boolean.FALSE if not. + * Boolean.FALSE if not. */ - public Boolean getPaused() - { + public Boolean getPaused() { return paused; } /** * Sets if this member is paused. - * + * * @param paused Boolean.TRUE if this member has been paused - * or Boolean.FALSE if not. + * or Boolean.FALSE if not. */ - public void setPaused(Boolean paused) - { + public void setPaused(Boolean paused) { this.paused = paused; } + + public String getStateinterface() { + return stateinterface; + } + + public void setStateinterface(String stateinterface) { + this.stateinterface = stateinterface; + } + + public Boolean getRinginuse() { + return ringinuse; + } + + public void setRinginuse(Boolean ringinuse) { + this.ringinuse = ringinuse; + } + + public Integer getLoginTime() { + return logintime; + } + + public void setLoginTime(Integer logintime) { + this.logintime = logintime; + } + + public Integer getWrapupTime() { + return wrapuptime; + } + + public void setWrapupTime(Integer wrapuptime) { + this.wrapuptime = wrapuptime; + } + + public Integer getLastPause() { + return lastpause; + } + + public void setLastPause(Integer lastpause) { + this.lastpause = lastpause; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueMemberEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueMemberEvent.java index 2b5bfa791..04f92ecd7 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueMemberEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberEvent.java @@ -21,13 +21,12 @@ * contains information about a member of a queue. *

    * It is implemented in apps/app_queue.c - * - * @see org.asteriskjava.manager.action.QueueStatusAction + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.QueueStatusAction */ -public class QueueMemberEvent extends ResponseEvent -{ +public class QueueMemberEvent extends ResponseEvent { public static final int AST_DEVICE_UNKNOWN = 0; /** @@ -50,180 +49,217 @@ public class QueueMemberEvent extends ResponseEvent */ private static final long serialVersionUID = 0L; private String queue; + @SuppressWarnings("unused") private String location; private String membership; private String name; private Integer penalty; private Integer callsTaken; private Long lastCall; + private Long lastPause; private Integer status; private Boolean paused; + private String stateinterface; + private Integer incall; + private String pausedreason; + private Integer wrapuptime; + private String _interface; + private Integer logintime; /** * @param source */ - public QueueMemberEvent(Object source) - { + public QueueMemberEvent(Object source) { super(source); } /** * Returns the name of the queue. - * + * * @return the name of the queue. */ - public String getQueue() - { + public String getQueue() { return queue; } /** * Sets the name of the queue. - * + * * @param queue the name of the queue. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } /** * Returns the name of the member's interface. *

    - * E.g. the channel name or agent group (for example "Agent/@1"). - * + * E.g. the channel name or agent group. + * * @return the name of the member's interface. */ - public String getLocation() - { - return location; + final public String getInterface() { + return _interface; } /** * Sets the name of the member's interface. - * - * @param location the name of the member's interface. + * + * @param member the name of the member's interface. + */ + final public void setInterface(String _interface) { + this._interface = _interface; + } + + /** + * Returns the name of the member's interface. + *

    + * E.g. the channel name or agent group. + * + * @return the name of the member's interface. + * @deprecated since Asterisk 12 */ - public void setLocation(String location) - { - this.location = location; + @Deprecated + final public String getLocation() { + return _interface; + } + + /** + * Sets the name of the member's interface. + * + * @param member the name of the member's interface. + * @deprecated since Asterisk 12 + */ + @Deprecated + final public void setLocation(String _interface) { + if ((_interface != null) && (!"null".equals(_interface))) { // Location is not in use since asterisk 12 + this._interface = _interface; + } } /** * Returns if this member has been dynamically added by the QueueAdd command * (in the dialplan or via the Manager API) or if this member is has been * statically defined in queues.conf. - * + * * @return "dynamic" if the added member is a dynamic queue member, "static" - * if the added member is a static queue member. + * if the added member is a static queue member. */ - public String getMembership() - { + public String getMembership() { return membership; } /** * Convenience method that checks whether this member has been statically * defined in queues.conf. - * + * * @return true if this member has been statically defined in - * queues.conf, false otherwise. + * queues.conf, false otherwise. * @since 0.3 */ - public boolean isStatic() - { + public boolean isStatic() { return MEMBERSHIP_STATIC.equals(membership); } /** * Convenience method that checks whether this member has been dynamically * added by the QueueAdd command. - * + * * @return true if this member has been dynamically added by - * the QueueAdd command, false otherwise. + * the QueueAdd command, false otherwise. * @since 0.3 */ - public boolean isDynamic() - { + public boolean isDynamic() { return MEMBERSHIP_DYNAMIC.equals(membership); } /** * Sets if this member has been dynamically or statically added. - * + * * @param membership "dynamic" if the added member is a dynamic queue - * member, "static" if the added member is a static queue member. + * member, "static" if the added member is a static queue member. */ - public void setMembership(String membership) - { + public void setMembership(String membership) { this.membership = membership; } /** * Returns the penalty for the added member. When calls are distributed * members with higher penalties are considered last. - * + * * @return the penalty for the added member. */ - public Integer getPenalty() - { + public Integer getPenalty() { return penalty; } /** * Sets the penalty for this member. - * + * * @param penalty the penalty for this member. */ - public void setPenalty(Integer penalty) - { + public void setPenalty(Integer penalty) { this.penalty = penalty; } /** * Returns the number of calls answered by the member. - * + * * @return the number of calls answered by the member. */ - public Integer getCallsTaken() - { + public Integer getCallsTaken() { return callsTaken; } /** * Sets the number of calls answered by the added member. - * + * * @param callsTaken the number of calls answered by the added member. */ - public void setCallsTaken(Integer callsTaken) - { + public void setCallsTaken(Integer callsTaken) { this.callsTaken = callsTaken; } /** * Returns the time the last successful call answered by the added member * was hungup. - * + * * @return the time (in seconds since 01/01/1970) the last successful call - * answered by the added member was hungup. + * answered by the added member was hungup. */ - public Long getLastCall() - { + public Long getLastCall() { return lastCall; } /** * Sets the time the last successful call answered by this member was * hungup. - * + * * @param lastCall the time (in seconds since 01/01/1970) the last - * successful call answered by the added member was hungup. + * successful call answered by the added member was hungup. */ - public void setLastCall(Long lastCall) - { + public void setLastCall(Long lastCall) { this.lastCall = lastCall; } + /** + * The time when started last pause for queue member. + * + * @return the time (in seconds since 01/01/1970) + */ + public Long getLastPause() { + return lastPause; + } + + /** + * Sets the time when started last pause for queue member. + * + * @param lastPause the time (in seconds since 01/01/1970) + */ + public void setLastPause(Long lastPause) { + this.lastPause = lastPause; + } + /** * Returns the status of this queue member. *

    @@ -249,26 +285,23 @@ public void setLastCall(Long lastCall) *

    Device is ringing and in use
    *
    AST_DEVICE_ONHOLD (8)
    *
    Device is on hold
    - * - * + * * @return the status of this queue member or null if this - * attribute is not supported by your version of Asterisk. + * attribute is not supported by your version of Asterisk. * @since 0.2 */ - public Integer getStatus() - { + public Integer getStatus() { return status; } /** * Sets the status of this queue member. - * + * * @param status the status of this queue member * @since 0.2 */ - public void setStatus(Integer status) - { + public void setStatus(Integer status) { this.status = status; } @@ -276,57 +309,100 @@ public void setStatus(Integer status) * Is this queue member paused (not accepting calls)? *

    * Available since Asterisk 1.2. - * + * * @return Boolean.TRUE if this member has been paused, - * Boolean.FALSE if not or null if - * pausing is not supported by your version of Asterisk. + * Boolean.FALSE if not or null if pausing + * is not supported by your version of Asterisk. * @since 0.2 */ - public Boolean getPaused() - { + public Boolean getPaused() { return paused; } /** * Sets if this member has been paused. - * + * * @since 0.2 */ - public void setPaused(Boolean paused) - { + public void setPaused(Boolean paused) { this.paused = paused; } /** * Returns the name of the member. * - * @return the name of the member supplied for logging when the member is added + * @return the name of the member supplied for logging when the member is + * added * @since 1.0.0 */ - public String getName() - { + public String getName() { return name; } - public void setName(String name) - { + public void setName(String name) { this.name = name; } /** * Returns the name of the member. * - * @return the name of the member supplied for logging when the member is added + * @return the name of the member supplied for logging when the member is + * added * @deprecated since 1.0.0. Use {@link #getName()} instead. */ - @Deprecated public String getMemberName() - { + @Deprecated + public String getMemberName() { return name; } // Renamed to "name" in Asterisk 1.6 - public void setMemberName(String memberName) - { + public void setMemberName(String memberName) { this.name = memberName; } + + /** + * @return Name of the interface where device state is taken from. + */ + public String getStateinterface() { + return stateinterface; + } + + public void setStateinterface(String stateinterface) { + this.stateinterface = stateinterface; + } + + /** + * @return 1 if is incall 0 if not + */ + public Integer getIncall() { + return incall; + } + + public void setIncall(Integer incall) { + this.incall = incall; + } + + public String getPausedreason() { + return pausedreason; + } + + public void setPausedreason(String pausedreason) { + this.pausedreason = pausedreason; + } + + public Integer getWrapuptime() { + return wrapuptime; + } + + public void setWrapuptime(Integer wrapuptime) { + this.wrapuptime = wrapuptime; + } + + public Integer getLogintime() { + return logintime; + } + + public void setLogintime(Integer logintime) { + this.logintime = logintime; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueMemberPauseEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueMemberPauseEvent.java new file mode 100644 index 000000000..80eb1be30 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberPauseEvent.java @@ -0,0 +1,203 @@ +package org.asteriskjava.manager.event; + +/** + * A QueueMemberPauseEvent is triggered when a queue member is paused or + * unpaused. + *

    + * Before the release of Asterisk 12, this event was called + * {@code QueueMemberPaused} but was erroneously changed in commit a2d02edc to + * {@code QueueMemberPause}. + */ +public class QueueMemberPauseEvent extends QueueMemberPausedEvent { + private static final long serialVersionUID = 5184794168561845630L; + + // Logger logger = LogManager.getLogger(); + String membership; + Long lastcall; + Long lastpause; + Integer callsTaken; + Integer penalty; + Integer status; + Boolean ringinuse; + String stateInterface; + Integer incall; + String pausedreason; + Integer logintime; + Integer wrapuptime; + + public QueueMemberPauseEvent(Object source) { + super(source); + // TODO Auto-generated constructor stub + } + + /** + * @return the membership + */ + public String getMembership() { + return membership; + } + + /** + * @param membership the membership to set + */ + public void setMembership(String membership) { + this.membership = membership; + } + + /** + * @return the lastcall + */ + public Long getLastcall() { + return lastcall; + } + + /** + * @param lastcall the lastcall to set + */ + public void setLastcall(Long lastcall) { + this.lastcall = lastcall; + } + + /** + * @return the lastpause time in seconds + */ + public Long getLastpause() { + return lastpause; + } + + /** + * @param lastpause the lastpause time in seconds to set + */ + public void setLastpause(Long lastpause) { + this.lastpause = lastpause; + } + + /** + * @return the callsTaken + */ + public Integer getCallsTaken() { + return callsTaken; + } + + /** + * @param callsTaken the callsTaken to set + */ + public void setCallsTaken(Integer callsTaken) { + this.callsTaken = callsTaken; + } + + /** + * @return the penalty + */ + public Integer getPenalty() { + return penalty; + } + + /** + * @param penalty the penalty to set + */ + public void setPenalty(Integer penalty) { + this.penalty = penalty; + } + + /** + * @return the status + */ + public Integer getStatus() { + return status; + } + + /** + * @param status the status to set + */ + public void setStatus(Integer status) { + this.status = status; + } + + /** + * @return the ringinuse + */ + public Boolean getRinginuse() { + return ringinuse; + } + + /** + * @param ringinuse the ringinuse to set + */ + public void setRinginuse(Boolean ringinuse) { + this.ringinuse = ringinuse; + } + + + /** + * @return the stateInterface + */ + public String getStateInterface() { + return stateInterface; + } + + /** + * @param stateInterface the stateInterface to set + */ + public void setStateInterface(String stateInterface) { + this.stateInterface = stateInterface; + } + + /** + * @return get Incall + */ + public Integer getIncall() { + return incall; + } + + /** + * @param setIncall the incall to set + */ + public void setIncall(Integer incall) { + this.incall = incall; + } + + public String getPausedreason() { + return pausedreason; + } + + public void setPausedreason(String pausedreason) { + this.pausedreason = pausedreason; + } + + /** + * Gets the login time + * + * @return the login time of the agent as a UNIX timestamp + */ + public Integer getLoginTime() { + return logintime; + } + + /** + * Sets the login time + * + * @param logintime the login time of the agent as a UNIX timestamp + */ + public void setLoginTime(Integer logintime) { + this.logintime = logintime; + } + + /** + * Gets the agent's wrap up time + * + * @return the agent's wrap up time (in seconds) + */ + public Integer getWrapupTime() { + return wrapuptime; + } + + /** + * Sets the agent's wrap up time + * + * @param wrapuptime the agent's wrap up time (in seconds) + */ + public void setWrapupTime(Integer wrapuptime) { + this.wrapuptime = wrapuptime; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/QueueMemberPausedEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueMemberPausedEvent.java index 66b0e5ec3..694117f29 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueMemberPausedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberPausedEvent.java @@ -26,8 +26,7 @@ * @version $Id$ * @since 0.2 */ -public class QueueMemberPausedEvent extends AbstractQueueMemberEvent -{ +public class QueueMemberPausedEvent extends AbstractQueueMemberEvent { /** * Serial version identifier. */ @@ -40,8 +39,7 @@ public class QueueMemberPausedEvent extends AbstractQueueMemberEvent */ private String reason; - public QueueMemberPausedEvent(Object source) - { + public QueueMemberPausedEvent(Object source) { super(source); } @@ -49,10 +47,9 @@ public QueueMemberPausedEvent(Object source) * Returns if this queue member is paused (not accepting calls).

    * * @return Boolean.TRUE if this member has been paused or - * Boolean.FALSE if not. + * Boolean.FALSE if not. */ - public Boolean getPaused() - { + public Boolean getPaused() { return paused; } @@ -62,8 +59,7 @@ public Boolean getPaused() * @param paused Boolean.TRUE if this member has been paused * or Boolean.FALSE if not. */ - public void setPaused(Boolean paused) - { + public void setPaused(Boolean paused) { this.paused = paused; } @@ -74,8 +70,7 @@ public void setPaused(Boolean paused) * * @return the reason specified for the pause. */ - public String getReason() - { + public String getReason() { return reason; } @@ -84,8 +79,7 @@ public String getReason() * * @param reason the reason why the queue member has been paused. */ - public void setReason(String reason) - { + public void setReason(String reason) { this.reason = reason; } } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueMemberPenaltyEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueMemberPenaltyEvent.java index d16723dca..054a7cfcb 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueMemberPenaltyEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberPenaltyEvent.java @@ -26,33 +26,280 @@ * @version $Id$ * @since 1.0.0 */ -public class QueueMemberPenaltyEvent extends ManagerEvent -{ +public class QueueMemberPenaltyEvent extends ManagerEvent { /** * Serializable version identifier. */ - private static final long serialVersionUID = 0L; + private static final long serialVersionUID = 2361464012968723903L; + private String queue; private String location; private Integer penalty; + private Boolean paused; + private Integer wrapuptime; + private Integer lastpause; + private String stateinterface; + private String pausedreason; + private Integer incall; + private String membership; + private String _interface; + private Integer callstaken; + private Integer ringinuse; + private Integer lastcall; + private String membername; + private Integer status; + private Integer logintime; /** * Creates a new instance. * * @param source */ - public QueueMemberPenaltyEvent(Object source) - { + public QueueMemberPenaltyEvent(Object source) { super(source); } + /** + * Returns if the member is pause + * + * @return if the member is pause + */ + public Boolean getPaused() { + return paused; + } + + /** + * Sets if member is paused or not + * + * @param paused if paused + */ + public void setPaused(Boolean paused) { + this.paused = paused; + } + + /** + * Returns wrapuptime + * + * @return Returns wrapuptime + */ + public Integer getWrapuptime() { + return wrapuptime; + } + + /** + * Sets wrapuptime + * + * @param wrapuptime the wrapuptime + */ + public void setWrapuptime(Integer wrapuptime) { + this.wrapuptime = wrapuptime; + } + + /** + * Returns time in seconds when started last paused the queue member + * + * @return Returns time in seconds when started last paused the queue member + */ + public Integer getLastpause() { + return lastpause; + } + + /** + * Sets time in seconds when started last paused the queue member + * + * @param lastpause time in seconds when started last paused the queue member + */ + public void setLastpause(Integer lastpause) { + this.lastpause = lastpause; + } + + /** + * Returns the queue member's tech or location state + * + * @return the queue member's tech or location state + */ + public String getStateinterface() { + return stateinterface; + } + + /** + * Sets channel technology or location from which the member device changed + * + * @param stateinterface channel technology or location from which the member device changed + */ + public void setStateinterface(String stateinterface) { + this.stateinterface = stateinterface; + } + + /** + * Returns reason if set when paused + * + * @return reason if set when paused + */ + public String getPausedreason() { + return pausedreason; + } + + /** + * Sets reason if set when paused + * + * @param pausedreason reason if set when paused + */ + public void setPausedreason(String pausedreason) { + this.pausedreason = pausedreason; + } + + /** + * Returns if member is in call when event is raised + * + * @return if member is in call when event is raised + */ + public Integer getIncall() { + return incall; + } + + /** + * Sets if member is in call when event is raised + * + * @param incall if member is in call when event is raised + */ + public void setIncall(Integer incall) { + this.incall = incall; + } + + /** + * Returns membership in queue + * E.g. dynamic, realtime, static + * + * @return membership in queue + */ + public String getMembership() { + return membership; + } + + /** + * Sets membership in queue + * + * @param membership membership in queue + */ + public void setMembership(String membership) { + this.membership = membership; + } + + /** + * Returns queue member's tech or location name + * + * @return queue member's tech or location name + */ + public String getInterface() { + return _interface; + } + + /** + * Sets queue member's tech or location name + * + * @param _interface queue member's tech or location name + */ + public void setInterface(String _interface) { + this._interface = _interface; + } + + /** + * Returns number of calls this queue member has serviced + * + * @return number of calls this queue member has serviced + */ + public Integer getCallstaken() { + return callstaken; + } + + /** + * Sets number of calls this queue member has serviced + * + * @param callstaken number of calls this queue member has serviced + */ + public void setCallstaken(Integer callstaken) { + this.callstaken = callstaken; + } + + /** + * Returns member's ring in use setup + * + * @return member's ring in use setup + */ + public Integer getRinginuse() { + return ringinuse; + } + + /** + * Sets member's ring in use setup + * + * @param ringinuse member's ring in use setup + */ + public void setRinginuse(Integer ringinuse) { + this.ringinuse = ringinuse; + } + + /** + * Returns time this member last took a call, expressed in seconds + * + * @return time this member last took a call, expressed in seconds + */ + public Integer getLastcall() { + return lastcall; + } + + /** + * Sets time this member last took a call, expressed in seconds + * + * @param lastcall time this member last took a call, expressed in seconds + */ + public void setLastcall(Integer lastcall) { + this.lastcall = lastcall; + } + + /** + * Returns name of the queue member. + * + * @return name of the queue member. + */ + public String getMembername() { + return membername; + } + + /** + * Sets name of the queue member. + * + * @param membername name of the queue member. + */ + public void setMembername(String membername) { + this.membername = membername; + } + + /** + * Returns numeric device state status of the queue member + * + * @return numeric device state status of the queue member + */ + public Integer getStatus() { + return status; + } + + /** + * Sets numeric device state status of the queue member + * + * @param status numeric device state status of the queue member + */ + public void setStatus(Integer status) { + this.status = status; + } + /** * Returns the name of the queue. * * @return the name of the queue. */ - public String getQueue() - { + public String getQueue() { return queue; } @@ -61,8 +308,7 @@ public String getQueue() * * @param queue the name of the queue. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } @@ -72,8 +318,7 @@ public void setQueue(String queue) * * @return the name of the member's interface. */ - public String getLocation() - { + public String getLocation() { return location; } @@ -82,8 +327,7 @@ public String getLocation() * * @param member the name of the member's interface. */ - public void setLocation(String member) - { + public void setLocation(String member) { this.location = member; } @@ -92,8 +336,7 @@ public void setLocation(String member) * * @return the new penalty. */ - public Integer getPenalty() - { + public Integer getPenalty() { return penalty; } @@ -102,8 +345,25 @@ public Integer getPenalty() * * @param penalty the new penalty. */ - public void setPenalty(Integer penalty) - { + public void setPenalty(Integer penalty) { this.penalty = penalty; } -} \ No newline at end of file + + /** + * Gets the login time (as a UNIX timestamp) + * + * @return the login time of the agent + */ + public Integer getLoginTime() { + return logintime; + } + + /** + * Sets the login time (as a UNIX timestamp) + * + * @param logintime the login time of the agent + */ + public void setLoginTime(Integer logintime) { + this.logintime = logintime; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/QueueMemberRemovedEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueMemberRemovedEvent.java index 59ca7b243..9d9da69ba 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueMemberRemovedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberRemovedEvent.java @@ -21,20 +21,134 @@ * queue.

    * It is implemented in apps/app_queue.c.

    * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class QueueMemberRemovedEvent extends AbstractQueueMemberEvent -{ +public class QueueMemberRemovedEvent extends AbstractQueueMemberEvent { /** * Serial version identifier. */ private static final long serialVersionUID = 2108033737226142194L; - public QueueMemberRemovedEvent(Object source) - { + Boolean paused; + Integer penalty; + String stateinterface; + String membership; + Long callstaken; + Boolean ringinuse; + Long lastcall; + Integer status; + Integer logintime; + Integer wrapuptime; + Integer lastpause; + + + public QueueMemberRemovedEvent(Object source) { super(source); } + + + public Boolean getPaused() { + return paused; + } + + + public void setPaused(Boolean paused) { + this.paused = paused; + } + + + public Integer getPenalty() { + return penalty; + } + + + public void setPenalty(Integer penalty) { + this.penalty = penalty; + } + + + public String getStateinterface() { + return stateinterface; + } + + + public void setStateinterface(String stateinterface) { + this.stateinterface = stateinterface; + } + + + public String getMembership() { + return membership; + } + + + public void setMembership(String membership) { + this.membership = membership; + } + + public Long getCallstaken() { + return callstaken; + } + + + public void setCallstaken(Long callstaken) { + this.callstaken = callstaken; + } + + + public Boolean getRinginuse() { + return ringinuse; + } + + + public void setRinginuse(Boolean ringinuse) { + this.ringinuse = ringinuse; + } + + + public Long getLastcall() { + return lastcall; + } + + + public void setLastcall(Long lastcall) { + this.lastcall = lastcall; + } + + + public Integer getStatus() { + return status; + } + + + public void setStatus(Integer status) { + this.status = status; + } + + public Integer getLoginTime() { + return logintime; + } + + public void setLoginTime(Integer logintime) { + this.logintime = logintime; + } + + public Integer getWrapupTime() { + return wrapuptime; + } + + public void setWrapupTime(Integer wrapuptime) { + this.wrapuptime = wrapuptime; + } + + public Integer getLastPause() { + return lastpause; + } + + public void setLastPause(Integer lastpause) { + this.lastpause = lastpause; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueMemberRingInUseEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueMemberRingInUseEvent.java new file mode 100644 index 000000000..4d70cc714 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberRingInUseEvent.java @@ -0,0 +1,321 @@ +package org.asteriskjava.manager.event; + +public class QueueMemberRingInUseEvent extends ManagerEvent { + private static final long serialVersionUID = -631622399932926664L; + + private String queue; + private String memberName; + private String _interface; + private String stateInterface; + private String membership; + private Integer penalty; + private Integer callsTaken; + private Integer lastCall; + private Integer lastPause; + private Integer loginTime; + private Integer inCall; + private Integer status; + private Boolean paused; + private String pausedReason; + private Integer ringInUse; + private Integer wrapUpTime; + + /** + * Constructs a QueueMemberRingInUseEvent + * + * @param source The object on which the Event initially occurred. + * @throws IllegalArgumentException if source is null. + */ + public QueueMemberRingInUseEvent(Object source) { + super(source); + } + + /** + * Returns if the member is paused + * + * @return if the member is paused + */ + public Boolean getPaused() { + return paused; + } + + /** + * Sets if member is paused or not + * + * @param paused if paused + */ + public void setPaused(Boolean paused) { + this.paused = paused; + } + + /** + * Returns wrapuptime + * + * @return Returns wrapuptime + */ + public Integer getWrapuptime() { + return wrapUpTime; + } + + /** + * Sets wrapuptime + * + * @param wrapuptime the wrapuptime + */ + public void setWrapuptime(Integer wrapuptime) { + this.wrapUpTime = wrapuptime; + } + + /** + * Returns time in seconds when started last paused the queue member + * + * @return Returns time in seconds when started last paused the queue member + */ + public Integer getLastpause() { + return lastPause; + } + + /** + * Sets time in seconds when started last paused the queue member + * + * @param lastpause time in seconds when started last paused the queue member + */ + public void setLastpause(Integer lastpause) { + this.lastPause = lastpause; + } + + /** + * Returns the queue member's tech or location state + * + * @return the queue member's tech or location state + */ + public String getStateinterface() { + return stateInterface; + } + + /** + * Sets channel technology or location from which the member device changed + * + * @param stateinterface channel technology or location from which the member device changed + */ + public void setStateinterface(String stateinterface) { + this.stateInterface = stateinterface; + } + + /** + * Returns reason if set when paused + * + * @return reason if set when paused + */ + public String getPausedreason() { + return pausedReason; + } + + /** + * Sets reason if set when paused + * + * @param pausedreason reason if set when paused + */ + public void setPausedreason(String pausedreason) { + this.pausedReason = pausedreason; + } + + /** + * Returns if member is in call when event is raised + * + * @return if member is in call when event is raised + */ + public Integer getIncall() { + return inCall; + } + + /** + * Sets if member is in call when event is raised + * + * @param incall if member is in call when event is raised + */ + public void setIncall(Integer incall) { + this.inCall = incall; + } + + /** + * Returns membership in queue + * E.g. dynamic, realtime, static + * + * @return membership in queue + */ + public String getMembership() { + return membership; + } + + /** + * Sets membership in queue + * + * @param membership membership in queue + */ + public void setMembership(String membership) { + this.membership = membership; + } + + /** + * Returns queue member's tech or location name + * + * @return queue member's tech or location name + */ + public String getInterface() { + return _interface; + } + + /** + * Sets queue member's tech or location name + * + * @param _interface queue member's tech or location name + */ + public void setInterface(String _interface) { + this._interface = _interface; + } + + /** + * Returns number of calls this queue member has serviced + * + * @return number of calls this queue member has serviced + */ + public Integer getCallstaken() { + return callsTaken; + } + + /** + * Sets number of calls this queue member has serviced + * + * @param callstaken number of calls this queue member has serviced + */ + public void setCallstaken(Integer callstaken) { + this.callsTaken = callstaken; + } + + /** + * Returns member's ring in use setup + * + * @return member's ring in use setup + */ + public Integer getRinginuse() { + return ringInUse; + } + + /** + * Sets member's ring in use setup + * + * @param ringinuse member's ring in use setup + */ + public void setRinginuse(Integer ringinuse) { + this.ringInUse = ringinuse; + } + + /** + * Returns time this member last took a call, expressed in seconds + * + * @return time this member last took a call, expressed in seconds + */ + public Integer getLastcall() { + return lastCall; + } + + /** + * Sets time this member last took a call, expressed in seconds + * + * @param lastcall time this member last took a call, expressed in seconds + */ + public void setLastcall(Integer lastcall) { + this.lastCall = lastcall; + } + + /** + * Returns name of the queue member. + * + * @return name of the queue member. + */ + public String getMembername() { + return memberName; + } + + /** + * Sets name of the queue member. + * + * @param membername name of the queue member. + */ + public void setMembername(String membername) { + this.memberName = membername; + } + + /** + * Returns numeric device state status of the queue member + * + * @return numeric device state status of the queue member + */ + public Integer getStatus() { + return status; + } + + /** + * Sets numeric device state status of the queue member + * + * @param status numeric device state status of the queue member + */ + public void setStatus(Integer status) { + this.status = status; + } + + /** + * Returns the name of the queue. + * + * @return the name of the queue. + */ + public String getQueue() { + return queue; + } + + /** + * Sets the name of the queue. + * + * @param queue the name of the queue. + */ + public void setQueue(String queue) { + this.queue = queue; + } + + /** + * Returns the new penalty. + * + * @return the new penalty. + */ + public Integer getPenalty() { + return penalty; + } + + /** + * Sets the new penalty. + * + * @param penalty the new penalty. + */ + public void setPenalty(Integer penalty) { + this.penalty = penalty; + } + + /** + * Gets the login time + * + * @return the login time of the agent as a UNIX timestamp + */ + public Integer getLoginTime() { + return loginTime; + } + + /** + * Sets the login time + * + * @param logintime the login time of the agent as a UNIX timestamp + */ + public void setLoginTime(Integer logintime) { + this.loginTime = logintime; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/QueueMemberStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueMemberStatusEvent.java index 6c6062189..1529654c1 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueMemberStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberStatusEvent.java @@ -18,22 +18,45 @@ /** * A QueueMemberStatusEvent shows the status of a QueueMemberEvent - * - * @author Asteria Solutions Group, Inc. + * + * @author Asteria Solutions Group, Inc. http://www.asteriasgi.com/ * @version $Id$ */ -public class QueueMemberStatusEvent extends QueueMemberEvent -{ +public class QueueMemberStatusEvent extends QueueMemberEvent { /** * Serializable version identifier */ private static final long serialVersionUID = -2293926744791895763L; + private String ringinuse; + private Integer wrapuptime; + /** * @param source */ - public QueueMemberStatusEvent(Object source) - { + public QueueMemberStatusEvent(Object source) { super(source); } + + /** + * @return the ringinuse + */ + public String getRinginuse() { + return ringinuse; + } + + /** + * @param ringinuse the ringinuse to set + */ + public void setRinginuse(String ringinuse) { + this.ringinuse = ringinuse; + } + + public Integer getWrapuptime() { + return wrapuptime; + } + + public void setWrapuptime(Integer wrapuptime) { + this.wrapuptime = wrapuptime; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueParamsEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueParamsEvent.java index 6ff935b62..bca9afffe 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueParamsEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueParamsEvent.java @@ -25,8 +25,7 @@ * @version $Id$ * @see org.asteriskjava.manager.action.QueueStatusAction */ -public class QueueParamsEvent extends ResponseEvent -{ +public class QueueParamsEvent extends ResponseEvent { /** * Serializable version identifier. */ @@ -41,20 +40,20 @@ public class QueueParamsEvent extends ResponseEvent private Integer abandoned; private Integer serviceLevel; private Double serviceLevelPerf; + private Double serviceLevelPerf2; private Integer weight; - public QueueParamsEvent(Object source) - { + public QueueParamsEvent(Object source) { super(source); } + /** * Returns the name of the queue. * * @return the name of the queue. */ - public String getQueue() - { + public String getQueue() { return queue; } @@ -63,8 +62,7 @@ public String getQueue() * * @param queue the name of the queue. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } @@ -74,8 +72,7 @@ public void setQueue(String queue) * * @return the maximum number of people waiting in the queue or 0 for unlimited. */ - public Integer getMax() - { + public Integer getMax() { return max; } @@ -84,8 +81,7 @@ public Integer getMax() * * @param max the maximum number of people waiting in the queue or 0 for unlimited. */ - public void setMax(Integer max) - { + public void setMax(Integer max) { this.max = max; } @@ -105,8 +101,7 @@ public void setMax(Integer max) * @return the strategy used for this queue. * @since 1.0.0 */ - public String getStrategy() - { + public String getStrategy() { return strategy; } @@ -116,8 +111,7 @@ public String getStrategy() * @param strategy the strategy used for this queue. * @since 1.0.0 */ - public void setStrategy(String strategy) - { + public void setStrategy(String strategy) { this.strategy = strategy; } @@ -126,8 +120,7 @@ public void setStrategy(String strategy) * * @return the number of calls currently waiting in the queue. */ - public Integer getCalls() - { + public Integer getCalls() { return calls; } @@ -136,8 +129,7 @@ public Integer getCalls() * * @param calls the number of calls currently waiting in the queue. */ - public void setCalls(Integer calls) - { + public void setCalls(Integer calls) { this.calls = calls; } @@ -146,8 +138,7 @@ public void setCalls(Integer calls) * * @return the current average holdtime for this queue (in seconds). */ - public Integer getHoldTime() - { + public Integer getHoldTime() { return holdTime; } @@ -156,8 +147,7 @@ public Integer getHoldTime() * * @param holdTime the current average holdtime for this queue (in seconds). */ - public void setHoldTime(Integer holdTime) - { + public void setHoldTime(Integer holdTime) { this.holdTime = holdTime; } @@ -167,8 +157,7 @@ public void setHoldTime(Integer holdTime) * @return the current avarage talk time for this queue. * @since 1.0.0 */ - public Integer getTalkTime() - { + public Integer getTalkTime() { return talkTime; } @@ -178,8 +167,7 @@ public Integer getTalkTime() * @param talkTime the current avarage talk time for this queue. * @since 1.0.0 */ - public void setTalkTime(Integer talkTime) - { + public void setTalkTime(Integer talkTime) { this.talkTime = talkTime; } @@ -188,8 +176,7 @@ public void setTalkTime(Integer talkTime) * * @return the number of completed calls. */ - public Integer getCompleted() - { + public Integer getCompleted() { return completed; } @@ -198,8 +185,7 @@ public Integer getCompleted() * * @param complete the number of completed calls. */ - public void setCompleted(Integer complete) - { + public void setCompleted(Integer complete) { this.completed = complete; } @@ -208,8 +194,7 @@ public void setCompleted(Integer complete) * * @return the number of abandoned calls. */ - public Integer getAbandoned() - { + public Integer getAbandoned() { return abandoned; } @@ -218,8 +203,7 @@ public Integer getAbandoned() * * @param abandoned the number of abandoned calls. */ - public void setAbandoned(Integer abandoned) - { + public void setAbandoned(Integer abandoned) { this.abandoned = abandoned; } @@ -229,8 +213,7 @@ public void setAbandoned(Integer abandoned) * * @return the service level (in seconds). */ - public Integer getServiceLevel() - { + public Integer getServiceLevel() { return serviceLevel; } @@ -239,8 +222,7 @@ public Integer getServiceLevel() * * @param serviceLevel the service level (in seconds). */ - public void setServiceLevel(Integer serviceLevel) - { + public void setServiceLevel(Integer serviceLevel) { this.serviceLevel = serviceLevel; } @@ -249,10 +231,9 @@ public void setServiceLevel(Integer serviceLevel) * calls (in percent). * * @return the ratio of calls answered within the specified service level per total completed - * calls (in percent). + * calls (in percent). */ - public Double getServiceLevelPerf() - { + public Double getServiceLevelPerf() { return serviceLevelPerf; } @@ -263,8 +244,7 @@ public Double getServiceLevelPerf() * @param serviceLevelPerf the ratio of calls answered within the specified service level per total completed * calls (in percent). */ - public void setServiceLevelPerf(Double serviceLevelPerf) - { + public void setServiceLevelPerf(Double serviceLevelPerf) { this.serviceLevelPerf = serviceLevelPerf; } @@ -277,11 +257,10 @@ public void setServiceLevelPerf(Double serviceLevelPerf) * Available since Asterisk 1.2 * * @return the weight of this queue or null if not - * supported by your version of Asterisk + * supported by your version of Asterisk * @since 0.2 */ - public Integer getWeight() - { + public Integer getWeight() { return weight; } @@ -291,8 +270,17 @@ public Integer getWeight() * @param weight the weight of this queue * @since 0.2 */ - public void setWeight(Integer weight) - { + public void setWeight(Integer weight) { this.weight = weight; } + + public Double getServiceLevelPerf2() { + return serviceLevelPerf2; + } + + public void setServiceLevelPerf2(Double serviceLevelPerf2) { + this.serviceLevelPerf2 = serviceLevelPerf2; + } + + } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueStatusCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueStatusCompleteEvent.java index c17437d9f..44ab073e8 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueStatusCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueStatusCompleteEvent.java @@ -20,25 +20,42 @@ * A QueueStatusCompleteEvent is triggered after the state of all queues has been reported in response * to a QueueStatusAction.

    * Since Asterisk 1.2 - * - * @see org.asteriskjava.manager.action.QueueStatusAction - * + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.QueueStatusAction * @since 0.2 */ -public class QueueStatusCompleteEvent extends ResponseEvent -{ +public class QueueStatusCompleteEvent extends ResponseEvent { /** * Serial version identifier */ - private static final long serialVersionUID = -1177773673509373296L; + private static final long serialVersionUID = -1177773673509373297L; + + private Integer listItems; + private String eventList; /** * @param source */ - public QueueStatusCompleteEvent(Object source) - { + public QueueStatusCompleteEvent(Object source) { super(source); } + + public Integer getListItems() { + return listItems; + } + + public void setListItems(Integer listItems) { + this.listItems = listItems; + } + + public String getEventList() { + return eventList; + } + + public void setEventList(String eventList) { + this.eventList = eventList; + } + } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueSummaryCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueSummaryCompleteEvent.java index ed1dd6843..2c2e72d66 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueSummaryCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueSummaryCompleteEvent.java @@ -5,22 +5,70 @@ /** * A QueueSummaryCompleteEvent is triggered after the summary for all requested * queues has been reported in response to a QueueSummaryAction. - * - * @see QueueSummaryAction - * @see QueueSummaryEvent + * * @author srt * @version $Id$ + * @see QueueSummaryAction + * @see QueueSummaryEvent * @since 0.3 */ -public class QueueSummaryCompleteEvent extends ResponseEvent -{ +public class QueueSummaryCompleteEvent extends ResponseEvent { /** * Serial version identifier. */ private static final long serialVersionUID = -5044247858568827143L; - public QueueSummaryCompleteEvent(Object source) - { + /** + * ?? + */ + private String eventList; + + /** + * The number of listed items from queueSummaryAction. + */ + private Integer listItems; + + public QueueSummaryCompleteEvent(Object source) { super(source); } + + /** + * Returns eventList variable. + * + * @return String value. + */ + + public String getEventlist() { + return eventList; + } + + /** + * Sets eventList variable. + * + * @param eventList variable + */ + + public void setEventlist(String eventList) { + this.eventList = eventList; + } + + /** + * Returns the number of listed items. + * + * @return listItems size. + */ + + public Integer getListitems() { + return listItems; + } + + /** + * Sets the returnItems value. + * + * @param listItems variable. + */ + + public void setListitems(Integer listItems) { + this.listItems = listItems; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueSummaryEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueSummaryEvent.java index 08c821e60..723c51aab 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueSummaryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueSummaryEvent.java @@ -5,9 +5,9 @@ /** * A QueueSummaryEvent is triggered in response to a QueueSummaryAction and * contains a summary of the current state of a queue. - *

    + *
    * Available in Asterisk post-1.4. - *

    + *
    * It is implemented in apps/app_queue.c * * @author srt @@ -16,8 +16,7 @@ * @see QueueSummaryAction * @since 0.3 */ -public class QueueSummaryEvent extends ResponseEvent -{ +public class QueueSummaryEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -30,8 +29,7 @@ public class QueueSummaryEvent extends ResponseEvent private Integer talkTime; private Integer longestHoldTime; - public QueueSummaryEvent(Object source) - { + public QueueSummaryEvent(Object source) { super(source); } @@ -40,8 +38,7 @@ public QueueSummaryEvent(Object source) * * @return the name of queue. */ - public String getQueue() - { + public String getQueue() { return queue; } @@ -50,8 +47,7 @@ public String getQueue() * * @param queue the name of queue. */ - public void setQueue(String queue) - { + public void setQueue(String queue) { this.queue = queue; } @@ -60,8 +56,7 @@ public void setQueue(String queue) * * @return the number of members logged in. */ - public Integer getLoggedIn() - { + public Integer getLoggedIn() { return loggedIn; } @@ -70,20 +65,18 @@ public Integer getLoggedIn() * * @param loggedIn the number of members logged in. */ - public void setLoggedIn(Integer loggedIn) - { + public void setLoggedIn(Integer loggedIn) { this.loggedIn = loggedIn; } /** * Returns the number of members logged in and not in a call. - *

    + *
    * This is the number of queue members currently available for calls. * * @return the number of members logged in and not in a call. */ - public Integer getAvailable() - { + public Integer getAvailable() { return available; } @@ -92,8 +85,7 @@ public Integer getAvailable() * * @param available the number of members logged in and not in a call. */ - public void setAvailable(Integer available) - { + public void setAvailable(Integer available) { this.available = available; } @@ -102,8 +94,7 @@ public void setAvailable(Integer available) * * @return the number of callers currently waiting in the queue. */ - public Integer getCallers() - { + public Integer getCallers() { return callers; } @@ -112,8 +103,7 @@ public Integer getCallers() * * @param callers the number of callers currently waiting in the queue. */ - public void setCallers(Integer callers) - { + public void setCallers(Integer callers) { this.callers = callers; } @@ -122,8 +112,7 @@ public void setCallers(Integer callers) * * @return the current avarage hold time for this queue. */ - public Integer getHoldTime() - { + public Integer getHoldTime() { return holdTime; } @@ -132,8 +121,7 @@ public Integer getHoldTime() * * @param holdTime the current avarage hold time for this queue. */ - public void setHoldTime(Integer holdTime) - { + public void setHoldTime(Integer holdTime) { this.holdTime = holdTime; } @@ -143,8 +131,7 @@ public void setHoldTime(Integer holdTime) * @return the current avarage talk time for this queue. * @since 1.0.0 */ - public Integer getTalkTime() - { + public Integer getTalkTime() { return talkTime; } @@ -154,8 +141,7 @@ public Integer getTalkTime() * @param talkTime the current avarage talk time for this queue. * @since 1.0.0 */ - public void setTalkTime(Integer talkTime) - { + public void setTalkTime(Integer talkTime) { this.talkTime = talkTime; } @@ -165,8 +151,7 @@ public void setTalkTime(Integer talkTime) * @return the longest hold time of the a queue entry currently in the queue. * @since 1.0.0 */ - public Integer getLongestHoldTime() - { + public Integer getLongestHoldTime() { return longestHoldTime; } @@ -176,8 +161,7 @@ public Integer getLongestHoldTime() * @param longestHoldTime the longest hold time of the a queue entry currently in the queue. * @since 1.0.0 */ - public void setLongestHoldTime(Integer longestHoldTime) - { + public void setLongestHoldTime(Integer longestHoldTime) { this.longestHoldTime = longestHoldTime; } } diff --git a/src/main/java/org/asteriskjava/manager/event/ReceiveFaxEvent.java b/src/main/java/org/asteriskjava/manager/event/ReceiveFaxEvent.java index 7796fb1af..a38c571e8 100644 --- a/src/main/java/org/asteriskjava/manager/event/ReceiveFaxEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ReceiveFaxEvent.java @@ -3,12 +3,9 @@ /** * A ReceiveFaxEvent is an event of Digium's Fax For Asterisk add-on. */ -public class ReceiveFaxEvent extends ManagerEvent -{ +public class ReceiveFaxEvent extends ManagerEvent { private static final long serialVersionUID = 0L; private String channel; - private String context; - private String exten; private String callerId; private String remoteStationId; private String localStationId; @@ -17,108 +14,108 @@ public class ReceiveFaxEvent extends ManagerEvent private Integer transferRate; private String fileName; - public ReceiveFaxEvent(Object source) - { + private String language; + private String accountCode; + private String linkedId; + private String uniqueId; + + public ReceiveFaxEvent(Object source) { super(source); } - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - public String getContext() - { - return context; - } - - public void setContext(String context) - { - this.context = context; - } - - public String getExten() - { - return exten; - } - - public void setExten(String exten) - { - this.exten = exten; - } - - public String getCallerId() - { + public String getCallerId() { return callerId; } - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } - public String getRemoteStationId() - { + public String getRemoteStationId() { return remoteStationId; } - public void setRemoteStationId(String remoteStationId) - { + public void setRemoteStationId(String remoteStationId) { this.remoteStationId = remoteStationId; } - public String getLocalStationId() - { + public String getLocalStationId() { return localStationId; } - public void setLocalStationId(String localStationId) - { + public void setLocalStationId(String localStationId) { this.localStationId = localStationId; } - public Integer getPagesTransferred() - { + public Integer getPagesTransferred() { return pagesTransferred; } - public void setPagesTransferred(Integer pagesTransferred) - { + public void setPagesTransferred(Integer pagesTransferred) { this.pagesTransferred = pagesTransferred; } - public String getResolution() - { + public String getResolution() { return resolution; } - public void setResolution(String resolution) - { + public void setResolution(String resolution) { this.resolution = resolution; } - public Integer getTransferRate() - { + public Integer getTransferRate() { return transferRate; } - public void setTransferRate(Integer transferRate) - { + public void setTransferRate(Integer transferRate) { this.transferRate = transferRate; } - public String getFileName() - { + public String getFileName() { return fileName; } - public void setFileName(String fileName) - { + public void setFileName(String fileName) { this.fileName = fileName; } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/RegistrationsCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/RegistrationsCompleteEvent.java index f13f2d951..f79103c89 100644 --- a/src/main/java/org/asteriskjava/manager/event/RegistrationsCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RegistrationsCompleteEvent.java @@ -27,21 +27,19 @@ * @see org.asteriskjava.manager.action.SipShowRegistryAction * @since 1.0.0 */ -public class RegistrationsCompleteEvent extends ResponseEvent -{ +public class RegistrationsCompleteEvent extends ResponseEvent { /** - * - */ - private static final long serialVersionUID = 6269829662009989518L; - private Integer listItems; + * + */ + private static final long serialVersionUID = 6269829662009989518L; + private Integer listItems; private String eventList; /** * Creates a new RegistrationsCompleteEvent. */ - public RegistrationsCompleteEvent(Object source) - { + public RegistrationsCompleteEvent(Object source) { super(source); } @@ -50,8 +48,7 @@ public RegistrationsCompleteEvent(Object source) * * @return the number of SIP registrations that have been reported. */ - public Integer getListItems() - { + public Integer getListItems() { return listItems; } @@ -60,8 +57,7 @@ public Integer getListItems() * * @param listItems the number of SIP registrations that have been reported. */ - public void setListItems(Integer listItems) - { + public void setListItems(Integer listItems) { this.listItems = listItems; } @@ -70,14 +66,12 @@ public void setListItems(Integer listItems) * * @return always returns "Complete" confirming that all RegistryEntry events have been sent. */ - public String getEventList() - { + public String getEventList() { return eventList; } - public void setEventList(String eventList) - { + public void setEventList(String eventList) { this.eventList = eventList; } diff --git a/src/main/java/org/asteriskjava/manager/event/RegistryEntryEvent.java b/src/main/java/org/asteriskjava/manager/event/RegistryEntryEvent.java index 94d956f58..1280e86e7 100644 --- a/src/main/java/org/asteriskjava/manager/event/RegistryEntryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RegistryEntryEvent.java @@ -25,13 +25,12 @@ * @version $Id$ * @since 1.0.0 */ -public class RegistryEntryEvent extends ResponseEvent -{ +public class RegistryEntryEvent extends ResponseEvent { /** - * - */ - private static final long serialVersionUID = -7158046719541054868L; - private Integer port; + * + */ + private static final long serialVersionUID = -7158046719541054868L; + private Integer port; private String username; private String state; private Integer refresh; @@ -43,8 +42,7 @@ public class RegistryEntryEvent extends ResponseEvent * * @param source */ - public RegistryEntryEvent(Object source) - { + public RegistryEntryEvent(Object source) { super(source); } @@ -53,8 +51,7 @@ public RegistryEntryEvent(Object source) * * @return epoch since the last registration. */ - public Long getRegistrationTime() - { + public Long getRegistrationTime() { return registrationTime; } @@ -64,8 +61,7 @@ public Long getRegistrationTime() * * @param registrationTime the epoch of the last registration. */ - public void setRegistrationTime(String registrationTime) - { + public void setRegistrationTime(String registrationTime) { this.registrationTime = Long.valueOf(registrationTime); } @@ -74,8 +70,7 @@ public void setRegistrationTime(String registrationTime) * * @return the port number. */ - public Integer getPort() - { + public Integer getPort() { return port; } @@ -84,8 +79,7 @@ public Integer getPort() * * @param port the port number. */ - public void setPort(Integer port) - { + public void setPort(Integer port) { this.port = port; } @@ -94,8 +88,7 @@ public void setPort(Integer port) * * @return the username. */ - public String getUsername() - { + public String getUsername() { return username; } @@ -104,8 +97,7 @@ public String getUsername() * * @param username the username. */ - public void setUsername(String username) - { + public void setUsername(String username) { this.username = username; } @@ -114,8 +106,7 @@ public void setUsername(String username) * * @return the IP address or the hostname. */ - public String getHost() - { + public String getHost() { return host; } @@ -124,8 +115,7 @@ public String getHost() * * @param host IP address or hostname. */ - public void setHost(String host) - { + public void setHost(String host) { this.host = host; } @@ -134,8 +124,7 @@ public void setHost(String host) * * @return the value of state */ - public String getState() - { + public String getState() { return state; } @@ -144,8 +133,7 @@ public String getState() * * @param state new value of state */ - public void setState(String state) - { + public void setState(String state) { this.state = state; } @@ -154,8 +142,7 @@ public void setState(String state) * * @return the value of refresh. */ - public Integer getRefresh() - { + public Integer getRefresh() { return refresh; } @@ -164,8 +151,7 @@ public Integer getRefresh() * * @param refresh new value of refresh */ - public void setRefresh(Integer refresh) - { + public void setRefresh(Integer refresh) { this.refresh = refresh; } } diff --git a/src/main/java/org/asteriskjava/manager/event/RegistryEvent.java b/src/main/java/org/asteriskjava/manager/event/RegistryEvent.java index 2f5e86063..90b842413 100644 --- a/src/main/java/org/asteriskjava/manager/event/RegistryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RegistryEvent.java @@ -25,8 +25,7 @@ * @author srt * @version $Id$ */ -public class RegistryEvent extends ManagerEvent -{ +public class RegistryEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -46,12 +45,12 @@ public class RegistryEvent extends ManagerEvent private String username; private String status; private String cause; + private String trunkname; /** * @param source */ - public RegistryEvent(Object source) - { + public RegistryEvent(Object source) { super(source); } @@ -62,8 +61,7 @@ public RegistryEvent(Object source) * @return the type of channel that is registered. * @since 1.0.0 */ - public String getChannelType() - { + public String getChannelType() { return channelType; } @@ -73,8 +71,7 @@ public String getChannelType() * @param channelType the type of channel that is registered. * @since 1.0.0 */ - public void setChannelType(String channelType) - { + public void setChannelType(String channelType) { this.channelType = channelType; } @@ -86,8 +83,8 @@ public void setChannelType(String channelType) * @since 0.3 * @deprecated */ - @Deprecated public String getChannelDriver() - { + @Deprecated + public String getChannelDriver() { return channelType; } @@ -98,8 +95,8 @@ public void setChannelType(String channelType) * @since 0.3 * @deprecated */ - @Deprecated public void setChannelDriver(String channelDriver) - { + @Deprecated + public void setChannelDriver(String channelDriver) { this.channelType = channelDriver; } @@ -110,8 +107,8 @@ public void setChannelType(String channelType) * @see #getChannelType() * @deprecated */ - @Deprecated public String getChannel() - { + @Deprecated + public String getChannel() { return channelType; } @@ -121,8 +118,8 @@ public void setChannelType(String channelType) * @see #setChannelType(String) * @deprecated */ - @Deprecated public void setChannel(String channel) - { + @Deprecated + public void setChannel(String channel) { this.channelType = channel; } @@ -133,8 +130,7 @@ public void setChannelType(String channelType) * * @return the domain or host name of the SIP or IAX2 server. */ - public String getDomain() - { + public String getDomain() { return domain; } @@ -143,8 +139,7 @@ public String getDomain() * * @param domain the domain or host name of the SIP or IAX2 server. */ - public void setDomain(String domain) - { + public void setDomain(String domain) { this.domain = domain; } @@ -155,8 +150,7 @@ public void setDomain(String domain) * * @return the username used for registration. */ - public String getUsername() - { + public String getUsername() { return username; } @@ -165,8 +159,7 @@ public String getUsername() * * @param username the username used for registration. */ - public void setUsername(String username) - { + public void setUsername(String username) { this.username = username; } @@ -175,10 +168,10 @@ public void setUsername(String username) * * @see #setUsername(String) * @deprecated Please do not use this method it is a workaround for Asterisk - * 1.0.x servers. See Asterisk bug 4916. + * 1.0.x servers. See Asterisk bug 4916. */ - @Deprecated public void setUser(String username) - { + @Deprecated + public void setUser(String username) { this.username = username; } @@ -204,8 +197,7 @@ public void setUsername(String username) * * @return the registration state. */ - public String getStatus() - { + public String getStatus() { return status; } @@ -214,8 +206,7 @@ public String getStatus() * * @param status the registration state. */ - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } @@ -225,8 +216,7 @@ public void setStatus(String status) * @return the cause of a rejected registration or null if the cause is unknown. * @since 0.2 */ - public String getCause() - { + public String getCause() { return cause; } @@ -236,9 +226,15 @@ public String getCause() * @param cause the cause of a rejected registration. * @since 0.2 */ - public void setCause(String cause) - { + public void setCause(String cause) { this.cause = cause; } + public String getTrunkname() { + return trunkname; + } + + public void setTrunkname(String trunkname) { + this.trunkname = trunkname; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/ReloadEvent.java b/src/main/java/org/asteriskjava/manager/event/ReloadEvent.java index 087ece01f..6bc8f6824 100644 --- a/src/main/java/org/asteriskjava/manager/event/ReloadEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ReloadEvent.java @@ -24,8 +24,7 @@ * @author srt * @version $Id$ */ -public class ReloadEvent extends ManagerEvent -{ +public class ReloadEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -44,8 +43,7 @@ public class ReloadEvent extends ManagerEvent private String status; private String message; - public ReloadEvent(Object source) - { + public ReloadEvent(Object source) { super(source); } @@ -56,8 +54,7 @@ public ReloadEvent(Object source) * @return the name of the module that has been reloaded. * @since 1.0.0 */ - public String getModule() - { + public String getModule() { return module; } @@ -67,8 +64,7 @@ public String getModule() * @param module the name of the module that has been reloaded. * @since 1.0.0 */ - public void setModule(String module) - { + public void setModule(String module) { this.module = module; } @@ -77,14 +73,13 @@ public void setModule(String module) * Available since Asterisk 1.6. * * @return "Enabled" if the module is endabled, "Disabled" if it is disabled. - * @since 1.0.0 * @see #STATUS_ENABLED * @see #STATUS_DISABLED * @see #isEnabled() * @see #isDisabled() + * @since 1.0.0 */ - public String getStatus() - { + public String getStatus() { return status; } @@ -94,18 +89,15 @@ public String getStatus() * @param status "Enabled" if the module is endabled, "Disabled" if it is disabled. * @since 1.0.0 */ - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } - public String getMessage() - { + public String getMessage() { return message; } - public void setMessage(String message) - { + public void setMessage(String message) { this.message = message; } @@ -114,13 +106,12 @@ public void setMessage(String message) * Available since Asterisk 1.6. * * @return true the module is now enabled, false if it is disabled. - * For Asterisk versions up to 1.4 that do not support the "Status" property false is returned. + * For Asterisk versions up to 1.4 that do not support the "Status" property false is returned. * @see #getStatus() * @since 1.0.0 */ - public boolean isEnabled() - { - return status != null && STATUS_ENABLED.equalsIgnoreCase(status); + public boolean isEnabled() { + return STATUS_ENABLED.equalsIgnoreCase(status); } /** @@ -128,12 +119,11 @@ public boolean isEnabled() * Available since Asterisk 1.6. * * @return true the module is now disabled, false if it is enabled. - * For Asterisk versions up to 1.4 that do not support the "Status" property false is returned. + * For Asterisk versions up to 1.4 that do not support the "Status" property false is returned. * @see #getStatus() * @since 1.0.0 */ - public boolean isDisabled() - { - return status != null && STATUS_DISABLED.equalsIgnoreCase(status); + public boolean isDisabled() { + return STATUS_DISABLED.equalsIgnoreCase(status); } } diff --git a/src/main/java/org/asteriskjava/manager/event/RenameEvent.java b/src/main/java/org/asteriskjava/manager/event/RenameEvent.java index 4ae0e8c14..6bab2bfc9 100644 --- a/src/main/java/org/asteriskjava/manager/event/RenameEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RenameEvent.java @@ -20,12 +20,11 @@ * A RenameEvent is triggered when the name of a channel is changed. *

    * It is implemented in channel.c - * + * * @author srt * @version $Id$ */ -public class RenameEvent extends ManagerEvent -{ +public class RenameEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -51,28 +50,25 @@ public class RenameEvent extends ManagerEvent */ protected String uniqueId; - public RenameEvent(Object source) - { + public RenameEvent(Object source) { super(source); } /** * Returns the new name of the channel. - * + * * @return the new name of the channel. */ - public final String getNewname() - { + public final String getNewname() { return newname; } /** * Sets the new name of the channel. - * + * * @param newname the new name of the channel. */ - public final void setNewname(final String newname) - { + public final void setNewname(final String newname) { this.newname = newname; } @@ -82,8 +78,7 @@ public final void setNewname(final String newname) * @return the old name of the channel. * @since 1.0.0 */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -94,19 +89,18 @@ public String getChannel() * @param channel the old name of the channel. * @since 1.0.0 */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the old name of the channel. - * + * * @return the old name of the channel. - * @deprecated use {@link @getChannel} instead. + * @deprecated use {@link #getChannel} instead. */ - @Deprecated public final String getOldname() - { + @Deprecated + public final String getOldname() { return channel; } @@ -114,31 +108,28 @@ public void setChannel(String channel) * Sets the old name of the channel.

    * The "Oldchannel" property is used by Asterisk up to 1.4 and has been renamed to "Channel" * as of Asterisk 1.6. - * + * * @param oldname the old name of the channel. */ - public final void setOldname(final String oldname) - { + public final void setOldname(final String oldname) { this.channel = oldname; } /** * Returns the unique id of the channel. - * + * * @return the unique id of the channel. */ - public final String getUniqueId() - { + public final String getUniqueId() { return uniqueId; } /** * Sets the unique id of the channel. - * + * * @param uniqueId the unique id of the channel. */ - public final void setUniqueId(final String uniqueId) - { + public final void setUniqueId(final String uniqueId) { this.uniqueId = uniqueId; } @@ -149,12 +140,11 @@ public final void setUniqueId(final String uniqueId) *

    * The purpose of this property is unclear as the unique id is supposed to * never change. - * + * * @return the new unique id of the channel. * @since 0.3 */ - public final String getNewUniqueId() - { + public final String getNewUniqueId() { return newUniqueId; } @@ -165,12 +155,11 @@ public final String getNewUniqueId() *

    * The purpose of this property is unclear as the unique id is supposed to * never change. - * + * * @param newUniqueId the new unique id of the channel. * @since 0.3 */ - public final void setNewUniqueId(final String newUniqueId) - { + public final void setNewUniqueId(final String newUniqueId) { this.newUniqueId = newUniqueId; } } diff --git a/src/main/java/org/asteriskjava/manager/event/RequestBadFormatEvent.java b/src/main/java/org/asteriskjava/manager/event/RequestBadFormatEvent.java new file mode 100644 index 000000000..6895fbf47 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/RequestBadFormatEvent.java @@ -0,0 +1,137 @@ +package org.asteriskjava.manager.event; + +/** + * A RequestBadFormatEvent is triggered when bad format of request. + */ + +public class RequestBadFormatEvent extends ManagerEvent { + + /** + * Serializable version identifier. + */ + private final static long serialVersionUID = -4626589852577838795L; + + private String severity; + + private Integer eventversion; + + private String sessiontv; + + private String eventtv; + + private String sessionid; + + private String localaddress; + + private String accountid; + + private String requesttype; + + private String service; + + private String remoteaddress; + + private String module; + + private String requestparams; + + public RequestBadFormatEvent(Object source) { + super(source); + } + + public String getSeverity() { + return severity; + } + + public void setSeverity(String severity) { + this.severity = severity; + } + + public Integer getEventversion() { + return eventversion; + } + + public void setEventversion(Integer eventversion) { + this.eventversion = eventversion; + } + + public String getSessiontv() { + return sessiontv; + } + + public void setSessiontv(String sessiontv) { + this.sessiontv = sessiontv; + } + + public String getEventtv() { + return eventtv; + } + + public void setEventtv(String eventtv) { + this.eventtv = eventtv; + } + + public String getSessionid() { + return sessionid; + } + + public void setSessionid(String sessionid) { + this.sessionid = sessionid; + } + + public String getLocaladdress() { + return localaddress; + } + + public void setLocaladdress(String localaddress) { + this.localaddress = localaddress; + } + + public String getAccountid() { + return accountid; + } + + public void setAccountid(String accountid) { + this.accountid = accountid; + } + + public String getRequesttype() { + return requesttype; + } + + public void setRequesttype(String requesttype) { + this.requesttype = requesttype; + } + + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } + + public String getRemoteaddress() { + return remoteaddress; + } + + public void setRemoteaddress(String remoteaddress) { + this.remoteaddress = remoteaddress; + } + + public String getModule() { + return module; + } + + public void setModule(String module) { + this.module = module; + } + + public String getRequestparams() { + return requestparams; + } + + public void setRequestparams(String requestparams) { + this.requestparams = requestparams; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/RequestNotAllowedEvent.java b/src/main/java/org/asteriskjava/manager/event/RequestNotAllowedEvent.java new file mode 100644 index 000000000..5aa323670 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/RequestNotAllowedEvent.java @@ -0,0 +1,26 @@ +package org.asteriskjava.manager.event; + +public final class RequestNotAllowedEvent extends AbstractSecurityEvent { + private String requestParams; + private String requestType; + + public RequestNotAllowedEvent(Object source) { + super(source); + } + + public Object getRequestParams() { + return requestParams; + } + + public void setRequestParams(String value) { + this.requestParams = value; + } + + public Object getRequestType() { + return requestType; + } + + public void setRequestType(String value) { + this.requestType = value; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/RequestNotSupportedEvent.java b/src/main/java/org/asteriskjava/manager/event/RequestNotSupportedEvent.java new file mode 100644 index 000000000..e84aa6245 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/RequestNotSupportedEvent.java @@ -0,0 +1,17 @@ +package org.asteriskjava.manager.event; + +public final class RequestNotSupportedEvent extends AbstractSecurityEvent { + private String requestType; + + public RequestNotSupportedEvent(Object source) { + super(source); + } + + public String getRequestType() { + return requestType; + } + + public void setRequestType(String value) { + this.requestType = value; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ResponseEvent.java b/src/main/java/org/asteriskjava/manager/event/ResponseEvent.java index f979e0d61..cd7f1312a 100644 --- a/src/main/java/org/asteriskjava/manager/event/ResponseEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ResponseEvent.java @@ -17,7 +17,8 @@ package org.asteriskjava.manager.event; /** - * Abstract base class for events triggered in response to a ManagerAction.

    + * Abstract base class for events triggered in response to a ManagerAction. + *

    * All ResponseEvents contain an additional action id property that links the * event to the action that caused it. * @@ -25,28 +26,25 @@ * @version $Id$ * @see org.asteriskjava.manager.action.ManagerAction */ -public abstract class ResponseEvent extends ManagerEvent -{ - private static final long serialVersionUID = 1L; - private String actionId; +public abstract class ResponseEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + protected String actionId; private String internalActionId; - public ResponseEvent(Object source) - { + public ResponseEvent(Object source) { super(source); } /** - * Returns the user provided action id of the ManagerAction that caused - * this event. If the application did not set an action id this method - * returns null. + * Returns the user provided action id of the ManagerAction that caused this + * event. If the application did not set an action id this method returns + * null. * * @return the action id of the ManagerAction that caused this event or - * null if none was set. + * null if none was set. * @see org.asteriskjava.manager.action.ManagerAction#setActionId(String) */ - public final String getActionId() - { + public final String getActionId() { return actionId; } @@ -56,23 +54,22 @@ public final String getActionId() * @param actionId the action id of the ManagerAction that caused this * event. */ - public final void setActionId(String actionId) - { + public final void setActionId(String actionId) { this.actionId = actionId; } /** * Returns the internal action id of the ManagerAction that caused this - * event.

    + * event. + *

    * Warning: This method is internal to Asterisk-Java and should never be * used in application code. * * @return the internal action id of the ManagerAction that caused this - * event. + * event. * @since 0.2 */ - public final String getInternalActionId() - { + public final String getInternalActionId() { return internalActionId; } @@ -83,8 +80,7 @@ public final String getInternalActionId() * caused this event. * @since 0.2 */ - public final void setInternalActionId(String internalActionId) - { + public final void setInternalActionId(String internalActionId) { this.internalActionId = internalActionId; } } diff --git a/src/main/java/org/asteriskjava/manager/event/RtcpReceivedEvent.java b/src/main/java/org/asteriskjava/manager/event/RtcpReceivedEvent.java index 5acc954fa..11681ebae 100644 --- a/src/main/java/org/asteriskjava/manager/event/RtcpReceivedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RtcpReceivedEvent.java @@ -27,9 +27,8 @@ * @version $Id$ * @since 1.0.0 */ -public class RtcpReceivedEvent extends AbstractRtcpEvent -{ - private static final long serialVersionUID = 1L; +public class RtcpReceivedEvent extends AbstractRtcpEvent { + private static final long serialVersionUID = 2L; /** * Payload identifier for a sender report. @@ -51,10 +50,33 @@ public class RtcpReceivedEvent extends AbstractRtcpEvent private Long highestSequence; private Long sequenceNumberCycles; private Double lastSr; - private Long rtt; + private Double rtt; - public RtcpReceivedEvent(Object source) - { + private String channel; + private String language; + private String report0SequenceNumberCycles; + private String ssrc; + private String linkedId; + private String report0lsr; + private Long sentOctets; + private String report0Sourcessrc; + private Double report0dlsr; + private String uniqueid; + private Integer reportCount; + private Integer report0CumulativeLost; + private Integer report0FractionLost; + private Long report0iaJitter; + private Integer report0HighestSequence; + private InetAddress toAddress; + private Integer toPort; + private String sentntp; + private Long sentPackets; + private Long sentrtp; + private String accountCode; + private Double mes; + + + public RtcpReceivedEvent(Object source) { super(source); } @@ -63,8 +85,7 @@ public RtcpReceivedEvent(Object source) * * @return the IP address the RTCP message has been received from. */ - public InetAddress getFromAddress() - { + public InetAddress getFromAddress() { return fromAddress; } @@ -73,18 +94,31 @@ public InetAddress getFromAddress() * * @return the port of the RTCP message has been received from. */ - public Integer getFromPort() - { + public Integer getFromPort() { return fromPort; } - public void setFrom(String from) - { + public void setFrom(String from) { // Format is "%s:%d" this.fromAddress = stringToAddress(from); this.fromPort = stringToPort(from); } + /** + * Returns the port the RTCP message has been sent to. + * + * @return the port the RTCP message has been sent to. + */ + public Integer getToPort() { + return toPort; + } + + public void setTo(String to) { + // Format is "%s:%d" + this.toAddress = stringToAddress(to); + this.toPort = stringToPort(to); + } + /** * Indicates the format of the payload, typical values are 200 for sender reports and * 201 for receiver reports. @@ -93,37 +127,34 @@ public void setFrom(String from) * @see #PT_SENDER_REPORT * @see #PT_RECEIVER_REPORT */ - public Long getPt() - { + public Long getPt() { return pt; } - public void setPt(String ptString) - { + public void setPt(String ptString) { // Format is "PT: %d(%s)" - if (ptString == null || ptString.length() == 0) - { + if (ptString == null || ptString.length() == 0) { this.pt = null; return; } - if (ptString.indexOf('(') > 0) - { - this.pt = Long.parseLong(ptString.substring(0, ptString.indexOf('('))); - } - else - { - this.pt = Long.parseLong(ptString); + try { + if (ptString.indexOf('(') > 0) { + this.pt = Long.parseLong(ptString.substring(0, ptString.indexOf('('))); + } else { + this.pt = Long.parseLong(ptString); + } + + } catch (NumberFormatException e) { + throw new NumberFormatException(String.format("Input string [%s] is not a parsable long", ptString)); } } - public Long getReceptionReports() - { + public Long getReceptionReports() { return receptionReports; } - public void setReceptionReports(Long receptionReports) - { + public void setReceptionReports(Long receptionReports) { this.receptionReports = receptionReports; } @@ -132,13 +163,11 @@ public void setReceptionReports(Long receptionReports) * * @return the synchronization source identifier of the sender. */ - public Long getSenderSsrc() - { + public Long getSenderSsrc() { return senderSsrc; } - public void setSenderSsrc(Long senderSsrc) - { + public void setSenderSsrc(Long senderSsrc) { this.senderSsrc = senderSsrc; } @@ -147,43 +176,35 @@ public void setSenderSsrc(Long senderSsrc) * * @return the number of packets lost. */ - public Long getPacketsLost() - { + public Long getPacketsLost() { return packetsLost; } - public void setPacketsLost(Long packetsLost) - { + public void setPacketsLost(Long packetsLost) { this.packetsLost = packetsLost; } - public Long getHighestSequence() - { + public Long getHighestSequence() { return highestSequence; } - public void setHighestSequence(Long highestSequence) - { + public void setHighestSequence(Long highestSequence) { this.highestSequence = highestSequence; } - public Long getSequenceNumberCycles() - { + public Long getSequenceNumberCycles() { return sequenceNumberCycles; } - public void setSequenceNumberCycles(Long sequenceNumberCycles) - { + public void setSequenceNumberCycles(Long sequenceNumberCycles) { this.sequenceNumberCycles = sequenceNumberCycles; } - public Double getLastSr() - { + public Double getLastSr() { return lastSr; } - public void setLastSr(Double lastSr) - { + public void setLastSr(Double lastSr) { this.lastSr = lastSr; } @@ -192,13 +213,179 @@ public void setLastSr(Double lastSr) * * @return the round trip time in seconds, may be null. */ - public Long getRtt() - { + public Double getRtt() { return rtt; } - public void setRtt(String rttString) - { - this.rtt = secStringToLong(rttString); + public void setRtt(String rttString) { + this.rtt = secStringToDouble(rttString); + } + + public Long getRttAsMillseconds() { + return (long) (rtt * 1000); + } + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getReport0SequenceNumberCycles() { + return report0SequenceNumberCycles; + } + + public void setReport0SequenceNumberCycles(String report0SequenceNumberCycles) { + this.report0SequenceNumberCycles = report0SequenceNumberCycles; + } + + public String getSsrc() { + return ssrc; + } + + public void setSsrc(String ssrc) { + this.ssrc = ssrc; + } + + public String getReport0lsr() { + return report0lsr; + } + + public void setReport0lsr(String report0lsr) { + this.report0lsr = report0lsr; + } + + public Long getSentOctets() { + return sentOctets; + } + + public void setSentOctets(Long sentOctets) { + this.sentOctets = sentOctets; + } + + public String getReport0Sourcessrc() { + return report0Sourcessrc; + } + + public void setReport0Sourcessrc(String report0Sourcessrc) { + this.report0Sourcessrc = report0Sourcessrc; + } + + public Double getReport0dlsr() { + return report0dlsr; + } + + public void setReport0dlsr(Double report0dlsr) { + this.report0dlsr = report0dlsr; + } + + public String getUniqueid() { + return uniqueid; + } + + public void setUniqueid(String uniqueid) { + this.uniqueid = uniqueid; + } + + public Integer getReport0CumulativeLost() { + return report0CumulativeLost; + } + + public void setReport0CumulativeLost(Integer report0CumulativeLost) { + this.report0CumulativeLost = report0CumulativeLost; + } + + public Integer getReport0FractionLost() { + return report0FractionLost; + } + + public void setReport0FractionLost(Integer report0FractionLost) { + this.report0FractionLost = report0FractionLost; + } + + public Long getReport0iaJitter() { + return report0iaJitter; + } + + public void setReport0iaJitter(Long report0iaJitter) { + this.report0iaJitter = report0iaJitter; + } + + public InetAddress getToAddress() { + return toAddress; + } + + public String getSentntp() { + return sentntp; + } + + public void setSentntp(String sentntp) { + this.sentntp = sentntp; + } + + public Long getSentrtp() { + return sentrtp; + } + + public void setSentrtp(Long sentrtp) { + this.sentrtp = sentrtp; + } + + public Integer getReportCount() { + return reportCount; + } + + public void setReportCount(Integer reportCount) { + this.reportCount = reportCount; + } + + public Integer getReport0HighestSequence() { + return report0HighestSequence; + } + + public void setReport0HighestSequence(Integer report0HighestSequence) { + this.report0HighestSequence = report0HighestSequence; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public Long getSentPackets() { + return sentPackets; + } + + public void setSentPackets(Long sentPackets) { + this.sentPackets = sentPackets; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public Double getMes() { + return mes; + } + + public void setMes(Double mes) { + this.mes = mes; } } diff --git a/src/main/java/org/asteriskjava/manager/event/RtcpSentEvent.java b/src/main/java/org/asteriskjava/manager/event/RtcpSentEvent.java index 399616821..188a7bf00 100644 --- a/src/main/java/org/asteriskjava/manager/event/RtcpSentEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RtcpSentEvent.java @@ -27,10 +27,12 @@ * @version $Id$ * @since 1.0.0 */ -public class RtcpSentEvent extends AbstractRtcpEvent -{ +public class RtcpSentEvent extends AbstractRtcpEvent { private static final long serialVersionUID = 1L; + private InetAddress fromAddress; + private Integer fromPort; + private Long pt; private InetAddress toAddress; private Integer toPort; private Long ourSsrc; @@ -41,18 +43,84 @@ public class RtcpSentEvent extends AbstractRtcpEvent private Long cumulativeLoss; private Long theirLastSr; - public RtcpSentEvent(Object source) - { + private String channel; + private String language; + private String report0SequenceNumberCycles; + private String ssrc; + private String linkedId; + private String report0lsr; + private String report0Sourcessrc; + private Double report0dlsr; + private String uniqueid; + private Integer reportCount; + private Integer report0CumulativeLost; + private Integer report0FractionLost; + private Integer report0iaJitter; + private Integer report0HighestSequence; + private String accountCode; + private Double mes; + + public RtcpSentEvent(Object source) { super(source); } + /** + * Returns the IP address the RTCP message has been received from. + * + * @return the IP address the RTCP message has been received from. + */ + public InetAddress getFromAddress() { + return fromAddress; + } + + /** + * Returns the port of the RTCP message has been received from. + * + * @return the port of the RTCP message has been received from. + */ + public Integer getFromPort() { + return fromPort; + } + + public void setFrom(String from) { + // Format is "%s:%d" + this.fromAddress = stringToAddress(from); + this.fromPort = stringToPort(from); + } + + /** + * Indicates the format of the payload, typical values are 200 for sender reports and + * 201 for receiver reports. + * + * @return the format of the payload. + * @see #RtcpReceivedEvent.PT_SENDER_REPORT + * @see #RtcpReceivedEvent.PT_RECEIVER_REPORT + */ + public Long getPt() { + return pt; + } + + public void setPt(String ptString) { + // Format is "PT: %d(%s)" + if (ptString == null || ptString.length() == 0) { + this.pt = null; + return; + } + + if (ptString.indexOf('(') > 0) { + this.pt = Long.parseLong(ptString.substring(0, ptString.indexOf('('))); + } else { + this.pt = Long.parseLong(ptString); + } + } + + /** * Returns the IP address the RTCP message has been sent to. * * @return the IP address the RTCP message has been sent to. */ - public InetAddress getToAddress() - { + public InetAddress getToAddress() { return toAddress; } @@ -61,13 +129,11 @@ public InetAddress getToAddress() * * @return the port the RTCP message has been sent to. */ - public Integer getToPort() - { + public Integer getToPort() { return toPort; } - public void setTo(String to) - { + public void setTo(String to) { // Format is "%s:%d" this.toAddress = stringToAddress(to); this.toPort = stringToPort(to); @@ -75,35 +141,30 @@ public void setTo(String to) /** * Returns our synchronization source identifier that uniquely identifies the source of a stream. + * * @return our synchronization source identifier. */ - public Long getOurSsrc() - { + public Long getOurSsrc() { return ourSsrc; } - public void setOurSsrc(Long ourSsrc) - { + public void setOurSsrc(Long ourSsrc) { this.ourSsrc = ourSsrc; } - public Double getSentNtp() - { + public Double getSentNtp() { return sentNtp; } - public void setSentNtp(Double sentNtp) - { + public void setSentNtp(Double sentNtp) { this.sentNtp = sentNtp; } - public Long getSentRtp() - { + public Long getSentRtp() { return sentRtp; } - public void setSentRtp(Long sentRtp) - { + public void setSentRtp(Long sentRtp) { this.sentRtp = sentRtp; } @@ -112,13 +173,11 @@ public void setSentRtp(Long sentRtp) * * @return the number of packets sent. */ - public Long getSentPackets() - { + public Long getSentPackets() { return sentPackets; } - public void setSentPackets(Long sentPackets) - { + public void setSentPackets(Long sentPackets) { this.sentPackets = sentPackets; } @@ -127,33 +186,155 @@ public void setSentPackets(Long sentPackets) * * @return the number of octets (bytes) sent. */ - public Long getSentOctets() - { + public Long getSentOctets() { return sentOctets; } - public void setSentOctets(Long sentOctets) - { + public void setSentOctets(Long sentOctets) { this.sentOctets = sentOctets; } - public Long getCumulativeLoss() - { + public Long getCumulativeLoss() { return cumulativeLoss; } - public void setCumulativeLoss(Long cumulativeLoss) - { + public void setCumulativeLoss(Long cumulativeLoss) { this.cumulativeLoss = cumulativeLoss; } - public Long getTheirLastSr() - { + public Long getTheirLastSr() { return theirLastSr; } - public void setTheirLastSr(Long theirLastSr) - { + public void setTheirLastSr(Long theirLastSr) { this.theirLastSr = theirLastSr; } -} \ No newline at end of file + + public String getChannel() { + return channel; + } + + public void setChannel(String channel) { + this.channel = channel; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getReport0SequenceNumberCycles() { + return report0SequenceNumberCycles; + } + + public void setReport0SequenceNumberCycles(String report0SequenceNumberCycles) { + this.report0SequenceNumberCycles = report0SequenceNumberCycles; + } + + public String getSsrc() { + return ssrc; + } + + public void setSsrc(String ssrc) { + this.ssrc = ssrc; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getReport0lsr() { + return report0lsr; + } + + public void setReport0lsr(String report0lsr) { + this.report0lsr = report0lsr; + } + + public String getReport0Sourcessrc() { + return report0Sourcessrc; + } + + public void setReport0Sourcessrc(String report0Sourcessrc) { + this.report0Sourcessrc = report0Sourcessrc; + } + + public Double getReport0dlsr() { + return report0dlsr; + } + + public void setReport0dlsr(Double report0dlsr) { + this.report0dlsr = report0dlsr; + } + + public String getUniqueid() { + return uniqueid; + } + + public void setUniqueid(String uniqueid) { + this.uniqueid = uniqueid; + } + + public Integer getReportCount() { + return reportCount; + } + + public void setReportCount(Integer reportCount) { + this.reportCount = reportCount; + } + + public Integer getReport0CumulativeLost() { + return report0CumulativeLost; + } + + public void setReport0CumulativeLost(Integer report0CumulativeLost) { + this.report0CumulativeLost = report0CumulativeLost; + } + + public Integer getReport0FractionLost() { + return report0FractionLost; + } + + public void setReport0FractionLost(Integer report0FractionLost) { + this.report0FractionLost = report0FractionLost; + } + + public Integer getReport0iaJitter() { + return report0iaJitter; + } + + public void setReport0iaJitter(Integer report0iaJitter) { + this.report0iaJitter = report0iaJitter; + } + + public Integer getReport0HighestSequence() { + return report0HighestSequence; + } + + public void setReport0HighestSequence(Integer report0HighestSequence) { + this.report0HighestSequence = report0HighestSequence; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public Double getMes() { + return mes; + } + + public void setMes(Double mes) { + this.mes = mes; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/RtpReceiverStatEvent.java b/src/main/java/org/asteriskjava/manager/event/RtpReceiverStatEvent.java index ce607334e..e31aeab88 100644 --- a/src/main/java/org/asteriskjava/manager/event/RtpReceiverStatEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RtpReceiverStatEvent.java @@ -26,16 +26,15 @@ * @version $Id$ * @since 1.0.0 */ -public class RtpReceiverStatEvent extends AbstractRtpStatEvent -{ +public class RtpReceiverStatEvent extends AbstractRtpStatEvent { private static final long serialVersionUID = 1L; private Long receivedPackets; private Double transit; private Long rrCount; + private String accountCode; - public RtpReceiverStatEvent(Object source) - { + public RtpReceiverStatEvent(Object source) { super(source); } @@ -44,23 +43,19 @@ public RtpReceiverStatEvent(Object source) * * @return the number of packets received. */ - public Long getReceivedPackets() - { + public Long getReceivedPackets() { return receivedPackets; } - public void setReceivedPackets(Long receivedPackets) - { + public void setReceivedPackets(Long receivedPackets) { this.receivedPackets = receivedPackets; } - public Double getTransit() - { + public Double getTransit() { return transit; } - public void setTransit(Double transit) - { + public void setTransit(Double transit) { this.transit = transit; } @@ -69,13 +64,21 @@ public void setTransit(Double transit) * * @return the number of receiver reports. */ - public Long getRrCount() - { + public Long getRrCount() { return rrCount; } - public void setRrCount(Long rrCount) - { + public void setRrCount(Long rrCount) { this.rrCount = rrCount; } -} \ No newline at end of file + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/RtpSenderStatEvent.java b/src/main/java/org/asteriskjava/manager/event/RtpSenderStatEvent.java index 793beeb69..7beff21a9 100644 --- a/src/main/java/org/asteriskjava/manager/event/RtpSenderStatEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RtpSenderStatEvent.java @@ -26,16 +26,14 @@ * @version $Id$ * @since 1.0.0 */ -public class RtpSenderStatEvent extends AbstractRtpStatEvent -{ +public class RtpSenderStatEvent extends AbstractRtpStatEvent { private static final long serialVersionUID = 1L; private Long sentPackets; private Long srCount; private Double rtt; - public RtpSenderStatEvent(Object source) - { + public RtpSenderStatEvent(Object source) { super(source); } @@ -44,13 +42,11 @@ public RtpSenderStatEvent(Object source) * * @return the number of packets sent. */ - public Long getSentPackets() - { + public Long getSentPackets() { return sentPackets; } - public void setSentPackets(Long sentPackets) - { + public void setSentPackets(Long sentPackets) { this.sentPackets = sentPackets; } @@ -59,23 +55,19 @@ public void setSentPackets(Long sentPackets) * * @return the number of sender reports. */ - public Long getSrCount() - { + public Long getSrCount() { return srCount; } - public void setSrCount(Long srCount) - { + public void setSrCount(Long srCount) { this.srCount = srCount; } - public Double getRtt() - { + public Double getRtt() { return rtt; } - public void setRtt(Double rtt) - { + public void setRtt(Double rtt) { this.rtt = rtt; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/SendFaxEvent.java b/src/main/java/org/asteriskjava/manager/event/SendFaxEvent.java index 020582acd..7209364cc 100644 --- a/src/main/java/org/asteriskjava/manager/event/SendFaxEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SendFaxEvent.java @@ -19,14 +19,12 @@ /** * A SendFaxEvent is an event of Digium's Fax For Asterisk add-on. */ -public class SendFaxEvent extends AbstractFaxEvent -{ +public class SendFaxEvent extends AbstractFaxEvent { /** * Serial version identifier. */ private static final long serialVersionUID = -1L; - private String context; - private String exten; + private String channel; private String callerId; private String localStationId; private String remoteStationId; @@ -35,54 +33,29 @@ public class SendFaxEvent extends AbstractFaxEvent private String transferRate; private String fileName; + private String language; + private String accountCode; + private String linkedId; + private String uniqueId; - public SendFaxEvent(Object source) - { + public SendFaxEvent(Object source) { super(source); } - - /** - * @return the context - */ - public String getContext() - { - return context; - } - - - /** - * @param context the context to set - */ - public void setContext(String context) - { - this.context = context; + @Override + public String getChannel() { + return channel; } - - /** - * @return the exten - */ - public String getExten() - { - return exten; + @Override + public void setChannel(String channel) { + this.channel = channel; } - - /** - * @param exten the exten to set - */ - public void setExten(String exten) - { - this.exten = exten; - } - - /** * @return the callerId */ - public String getCallerId() - { + public String getCallerId() { return callerId; } @@ -90,8 +63,7 @@ public String getCallerId() /** * @param callerId the callerId to set */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } @@ -99,8 +71,7 @@ public void setCallerId(String callerId) /** * @return the localStationId */ - public String getLocalStationId() - { + public String getLocalStationId() { return localStationId; } @@ -108,8 +79,7 @@ public String getLocalStationId() /** * @param localStationId the localStationId to set */ - public void setLocalStationId(String localStationId) - { + public void setLocalStationId(String localStationId) { this.localStationId = localStationId; } @@ -117,8 +87,7 @@ public void setLocalStationId(String localStationId) /** * @return the remoteStationId */ - public String getRemoteStationId() - { + public String getRemoteStationId() { return remoteStationId; } @@ -126,8 +95,7 @@ public String getRemoteStationId() /** * @param remoteStationId the remoteStationId to set */ - public void setRemoteStationId(String remoteStationId) - { + public void setRemoteStationId(String remoteStationId) { this.remoteStationId = remoteStationId; } @@ -135,8 +103,7 @@ public void setRemoteStationId(String remoteStationId) /** * @return the pagesTransferred */ - public String getPagesTransferred() - { + public String getPagesTransferred() { return pagesTransferred; } @@ -144,8 +111,7 @@ public String getPagesTransferred() /** * @param pagesTransferred the pagesTransferred to set */ - public void setPagesTransferred(String pagesTransferred) - { + public void setPagesTransferred(String pagesTransferred) { this.pagesTransferred = pagesTransferred; } @@ -153,8 +119,7 @@ public void setPagesTransferred(String pagesTransferred) /** * @return the resolution */ - public String getResolution() - { + public String getResolution() { return resolution; } @@ -162,8 +127,7 @@ public String getResolution() /** * @param resolution the resolution to set */ - public void setResolution(String resolution) - { + public void setResolution(String resolution) { this.resolution = resolution; } @@ -171,8 +135,7 @@ public void setResolution(String resolution) /** * @return the transferRate */ - public String getTransferRate() - { + public String getTransferRate() { return transferRate; } @@ -180,8 +143,7 @@ public String getTransferRate() /** * @param transferRate the transferRate to set */ - public void setTransferRate(String transferRate) - { + public void setTransferRate(String transferRate) { this.transferRate = transferRate; } @@ -189,8 +151,7 @@ public void setTransferRate(String transferRate) /** * @return the fileName */ - public String getFileName() - { + public String getFileName() { return fileName; } @@ -198,11 +159,40 @@ public String getFileName() /** * @param fileName the fileName to set */ - public void setFileName(String fileName) - { + public void setFileName(String fileName) { this.fileName = fileName; } + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/SendFaxStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/SendFaxStatusEvent.java index bd9b45fce..6a84f1c7b 100644 --- a/src/main/java/org/asteriskjava/manager/event/SendFaxStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SendFaxStatusEvent.java @@ -19,67 +19,26 @@ /** * A SendFaxStatusEvent is an event of Digium's Fax For Asterisk add-on. */ -public class SendFaxStatusEvent extends AbstractFaxEvent -{ +public class SendFaxStatusEvent extends AbstractFaxEvent { /** * Serial version identifier. */ private static final long serialVersionUID = -1L; - private String context; - private String exten; private String status; private String callerId; private String localStationId; private String fileName; - public SendFaxStatusEvent(Object source) - { + public SendFaxStatusEvent(Object source) { super(source); } - /** - * @return the context - */ - public String getContext() - { - return context; - } - - - /** - * @param context the context to set - */ - public void setContext(String context) - { - this.context = context; - } - - - /** - * @return the exten - */ - public String getExten() - { - return exten; - } - - - /** - * @param exten the exten to set - */ - public void setExten(String exten) - { - this.exten = exten; - } - - /** * @return the status */ - public String getStatus() - { + public String getStatus() { return status; } @@ -87,8 +46,7 @@ public String getStatus() /** * @param status the status to set */ - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } @@ -96,8 +54,7 @@ public void setStatus(String status) /** * @return the callerId */ - public String getCallerId() - { + public String getCallerId() { return callerId; } @@ -105,8 +62,7 @@ public String getCallerId() /** * @param callerId the callerId to set */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } @@ -114,8 +70,7 @@ public void setCallerId(String callerId) /** * @return the localStationId */ - public String getLocalStationId() - { + public String getLocalStationId() { return localStationId; } @@ -123,8 +78,7 @@ public String getLocalStationId() /** * @param localStationId the localStationId to set */ - public void setLocalStationId(String localStationId) - { + public void setLocalStationId(String localStationId) { this.localStationId = localStationId; } @@ -132,8 +86,7 @@ public void setLocalStationId(String localStationId) /** * @return the fileName */ - public String getFileName() - { + public String getFileName() { return fileName; } @@ -141,8 +94,7 @@ public String getFileName() /** * @param fileName the fileName to set */ - public void setFileName(String fileName) - { + public void setFileName(String fileName) { this.fileName = fileName; } diff --git a/src/main/java/org/asteriskjava/manager/event/SessionLimitEvent.java b/src/main/java/org/asteriskjava/manager/event/SessionLimitEvent.java new file mode 100644 index 000000000..f6debbfe2 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/SessionLimitEvent.java @@ -0,0 +1,7 @@ +package org.asteriskjava.manager.event; + +public final class SessionLimitEvent extends AbstractSecurityEvent { + public SessionLimitEvent(Object source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/ShowDialplanCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/ShowDialplanCompleteEvent.java index 26f8ae015..8aa8a55c4 100644 --- a/src/main/java/org/asteriskjava/manager/event/ShowDialplanCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ShowDialplanCompleteEvent.java @@ -12,32 +12,37 @@ * @see org.asteriskjava.manager.event.ListDialplanEvent * @since 1.0.0 */ -public class ShowDialplanCompleteEvent extends ResponseEvent -{ +public class ShowDialplanCompleteEvent extends ResponseEvent { private static final long serialVersionUID = 1L; + private String eventList; private Integer listItems; private Integer listExtensions; private Integer listPriorities; private Integer listContexts; - public ShowDialplanCompleteEvent(Object source) - { + public ShowDialplanCompleteEvent(Object source) { super(source); } + public String getEventList() { + return eventList; + } + + public void setEventList(String eventList) { + this.eventList = eventList; + } + /** * Returns the total number of list items reported. * * @return the total number of list items reported. */ - public Integer getListItems() - { + public Integer getListItems() { return listItems; } - public void setListItems(Integer listItems) - { + public void setListItems(Integer listItems) { this.listItems = listItems; } @@ -46,13 +51,11 @@ public void setListItems(Integer listItems) * * @return the number of extensions reported. */ - public Integer getListExtensions() - { + public Integer getListExtensions() { return listExtensions; } - public void setListExtensions(Integer listExtensions) - { + public void setListExtensions(Integer listExtensions) { this.listExtensions = listExtensions; } @@ -61,13 +64,11 @@ public void setListExtensions(Integer listExtensions) * * @return the number of priorites reported. */ - public Integer getListPriorities() - { + public Integer getListPriorities() { return listPriorities; } - public void setListPriorities(Integer listPriorities) - { + public void setListPriorities(Integer listPriorities) { this.listPriorities = listPriorities; } @@ -76,13 +77,11 @@ public void setListPriorities(Integer listPriorities) * * @return the number of contexts reported. */ - public Integer getListContexts() - { + public Integer getListContexts() { return listContexts; } - public void setListContexts(Integer listContexts) - { + public void setListContexts(Integer listContexts) { this.listContexts = listContexts; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/ShutdownEvent.java b/src/main/java/org/asteriskjava/manager/event/ShutdownEvent.java index 99f768952..46eee4d9a 100644 --- a/src/main/java/org/asteriskjava/manager/event/ShutdownEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ShutdownEvent.java @@ -19,12 +19,11 @@ /** * A ShutdownEvent is triggered when the asterisk server is shut down or restarted.

    * It is implemented in asterisk.c - * + * * @author srt * @version $Id$ */ -public class ShutdownEvent extends ManagerEvent -{ +public class ShutdownEvent extends ManagerEvent { /** * Serial version identifier */ @@ -36,8 +35,7 @@ public class ShutdownEvent extends ManagerEvent /** * @param source */ - public ShutdownEvent(Object source) - { + public ShutdownEvent(Object source) { super(source); } @@ -45,13 +43,11 @@ public ShutdownEvent(Object source) * Returns the kind of shutdown or restart. Possible values are "Uncleanly" and "Cleanly". A * shutdown is considered unclean if there are any active channels when the system is shut down. */ - public String getShutdown() - { + public String getShutdown() { return shutdown; } - public void setShutdown(String shutdown) - { + public void setShutdown(String shutdown) { this.shutdown = shutdown; } @@ -59,13 +55,11 @@ public void setShutdown(String shutdown) * Returns true if the server has been restarted; false if it has * been halted. */ - public Boolean getRestart() - { + public Boolean getRestart() { return restart; } - public void setRestart(Boolean restart) - { + public void setRestart(Boolean restart) { this.restart = restart; } } diff --git a/src/main/java/org/asteriskjava/manager/event/SkypeAccountStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/SkypeAccountStatusEvent.java index e81b3c1d5..e433b3d19 100644 --- a/src/main/java/org/asteriskjava/manager/event/SkypeAccountStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SkypeAccountStatusEvent.java @@ -1,6 +1,6 @@ /* * Copyright 2004-2006 Stefan Reuter - * + * * amended 2010 Allan Wylie * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,8 +26,7 @@ * * @since 1.0.0 */ -public class SkypeAccountStatusEvent extends ManagerEvent -{ +public class SkypeAccountStatusEvent extends ManagerEvent { private static final long serialVersionUID = 1L; private String username; private String status; @@ -35,8 +34,7 @@ public class SkypeAccountStatusEvent extends ManagerEvent static final String STATUS_LOGGED_IN = "Logged In"; static final String STATUS_LOGGED_OUT = "Logged Out"; - public SkypeAccountStatusEvent(Object source) - { + public SkypeAccountStatusEvent(Object source) { super(source); } @@ -45,8 +43,7 @@ public SkypeAccountStatusEvent(Object source) * * @return the name of the Skype user. */ - public String getUsername() - { + public String getUsername() { return username; } @@ -55,8 +52,7 @@ public String getUsername() * * @param username the name of the Skype user. */ - public void setUsername(String username) - { + public void setUsername(String username) { this.username = username; } @@ -65,8 +61,7 @@ public void setUsername(String username) * * @return the Skype user status. */ - public String getStatus() - { + public String getStatus() { return status; } @@ -75,8 +70,7 @@ public String getStatus() * * @param status user status. */ - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } } diff --git a/src/main/java/org/asteriskjava/manager/event/SkypeBuddyEntryEvent.java b/src/main/java/org/asteriskjava/manager/event/SkypeBuddyEntryEvent.java index 914b2b3c4..e38826277 100644 --- a/src/main/java/org/asteriskjava/manager/event/SkypeBuddyEntryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SkypeBuddyEntryEvent.java @@ -25,8 +25,7 @@ * @see org.asteriskjava.manager.action.SkypeBuddiesAction * @since 1.0.0 */ -public class SkypeBuddyEntryEvent extends ResponseEvent -{ +public class SkypeBuddyEntryEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -35,8 +34,7 @@ public class SkypeBuddyEntryEvent extends ResponseEvent private String status; private String fullname; - public SkypeBuddyEntryEvent(Object source) - { + public SkypeBuddyEntryEvent(Object source) { super(source); } @@ -45,8 +43,7 @@ public SkypeBuddyEntryEvent(Object source) * * @return the Skype username of the buddy. */ - public String getBuddy() - { + public String getBuddy() { return buddy; } @@ -55,8 +52,7 @@ public String getBuddy() * * @param buddy the Skype username of the buddy. */ - public void setBuddy(String buddy) - { + public void setBuddy(String buddy) { this.buddy = buddy; } @@ -65,8 +61,7 @@ public void setBuddy(String buddy) * * @return the status of the buddy. */ - public String getStatus() - { + public String getStatus() { return status; } @@ -75,8 +70,7 @@ public String getStatus() * * @param status the status of the buddy. */ - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } @@ -85,8 +79,7 @@ public void setStatus(String status) * * @return the full name of the buddy. */ - public String getFullname() - { + public String getFullname() { return fullname; } @@ -95,8 +88,7 @@ public String getFullname() * * @param fullname the full name of the buddy. */ - public void setFullname(String fullname) - { + public void setFullname(String fullname) { this.fullname = fullname; } } diff --git a/src/main/java/org/asteriskjava/manager/event/SkypeBuddyListCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/SkypeBuddyListCompleteEvent.java index d49f363b5..e960a526a 100644 --- a/src/main/java/org/asteriskjava/manager/event/SkypeBuddyListCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SkypeBuddyListCompleteEvent.java @@ -25,16 +25,14 @@ * @see org.asteriskjava.manager.action.SkypeBuddiesAction * @since 1.0.0 */ -public class SkypeBuddyListCompleteEvent extends ResponseEvent -{ +public class SkypeBuddyListCompleteEvent extends ResponseEvent { /** * Serial version identifier. */ private static final long serialVersionUID = 1L; private Integer listItems; - public SkypeBuddyListCompleteEvent(Object source) - { + public SkypeBuddyListCompleteEvent(Object source) { super(source); } @@ -43,8 +41,7 @@ public SkypeBuddyListCompleteEvent(Object source) * * @return the number of buddies that have been reported. */ - public Integer getListItems() - { + public Integer getListItems() { return listItems; } @@ -53,8 +50,7 @@ public Integer getListItems() * * @param listItems the number of buddies that have been reported. */ - public void setListItems(Integer listItems) - { + public void setListItems(Integer listItems) { this.listItems = listItems; } } diff --git a/src/main/java/org/asteriskjava/manager/event/SkypeBuddyStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/SkypeBuddyStatusEvent.java index 8934d18fa..eda2121f8 100644 --- a/src/main/java/org/asteriskjava/manager/event/SkypeBuddyStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SkypeBuddyStatusEvent.java @@ -1,6 +1,6 @@ /* * Copyright 2004-2006 Stefan Reuter - * + * * amended 2010 - Allan Wylie * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,8 +29,7 @@ * * @since 1.0.0 */ -public class SkypeBuddyStatusEvent extends ManagerEvent -{ +public class SkypeBuddyStatusEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -63,8 +62,7 @@ public class SkypeBuddyStatusEvent extends ManagerEvent private String buddyStatus; - public SkypeBuddyStatusEvent(Object source) - { + public SkypeBuddyStatusEvent(Object source) { super(source); } @@ -78,8 +76,7 @@ public SkypeBuddyStatusEvent(Object source) * @see #getUser() * @see #getBuddySkypename() */ - public String getBuddy() - { + public String getBuddy() { return buddy; } @@ -88,8 +85,7 @@ public String getBuddy() * * @return the Skype username of the Skype for Asterisk user. */ - public String getUser() - { + public String getUser() { return buddyGroup(1); } @@ -98,20 +94,16 @@ public String getUser() * * @return the Skype username of the buddy who changed his status. */ - public String getBuddySkypename() - { + public String getBuddySkypename() { return buddyGroup(2); } - private String buddyGroup(int group) - { - if (buddy == null) - { + private String buddyGroup(int group) { + if (buddy == null) { return null; } final Matcher buddyMatcher = BUDDY_PATTERN.matcher(buddy); - if (buddyMatcher.matches()) - { + if (buddyMatcher.matches()) { return buddyMatcher.group(group); } return null; @@ -122,8 +114,7 @@ private String buddyGroup(int group) * * @param buddy the address of the buddy. */ - public void setBuddy(String buddy) - { + public void setBuddy(String buddy) { this.buddy = buddy; } @@ -132,13 +123,11 @@ public void setBuddy(String buddy) * * @return the status of the buddy. */ - public String getBuddyStatus() - { + public String getBuddyStatus() { return buddyStatus; } - public void setBuddyStatus(String buddyStatus) - { + public void setBuddyStatus(String buddyStatus) { this.buddyStatus = buddyStatus; } } diff --git a/src/main/java/org/asteriskjava/manager/event/SkypeChatMessageEvent.java b/src/main/java/org/asteriskjava/manager/event/SkypeChatMessageEvent.java index 68af67403..913241a1c 100644 --- a/src/main/java/org/asteriskjava/manager/event/SkypeChatMessageEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SkypeChatMessageEvent.java @@ -16,19 +16,20 @@ */ package org.asteriskjava.manager.event; -import org.asteriskjava.util.Base64; - -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Base64; /** - * A SkypeChatMessageEvent is triggered when a Skype Chat message is sent or received.

    - * It is implemented in chan_skye.c.

    + * A SkypeChatMessageEvent is triggered when a Skype Chat message is sent or + * received. + *

    + * It is implemented in chan_skye.c. + *

    * Available with Skype for Asterisk. * * @since 1.0.0 */ -public class SkypeChatMessageEvent extends ManagerEvent -{ +public class SkypeChatMessageEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -38,8 +39,7 @@ public class SkypeChatMessageEvent extends ManagerEvent private String from; private String message; - public SkypeChatMessageEvent(Object source) - { + public SkypeChatMessageEvent(Object source) { super(source); } @@ -48,8 +48,7 @@ public SkypeChatMessageEvent(Object source) * * @return the Skype username of the recipient of this chat message. */ - public String getTo() - { + public String getTo() { return to; } @@ -58,8 +57,7 @@ public String getTo() * * @param to the Skype username of the recipient of this chat message. */ - public void setTo(String to) - { + public void setTo(String to) { this.to = to; } @@ -68,8 +66,7 @@ public void setTo(String to) * * @return the Skype username of the sender of this chat message. */ - public String getFrom() - { + public String getFrom() { return from; } @@ -78,8 +75,7 @@ public String getFrom() * * @param from the Skype username of the sender of this chat message. */ - public void setFrom(String from) - { + public void setFrom(String from) { this.from = from; } @@ -88,8 +84,7 @@ public void setFrom(String from) * * @return the Base64 encoded message. */ - public String getMessage() - { + public String getMessage() { return message; } @@ -98,8 +93,7 @@ public String getMessage() * * @param message the Base64 encoded message. */ - public void setMessage(String message) - { + public void setMessage(String message) { this.message = message; } @@ -108,12 +102,10 @@ public void setMessage(String message) * * @return the decoded message. */ - public String getDecodedMessage() - { - if (message == null) - { + public String getDecodedMessage() { + if (message == null) { return null; } - return new String(Base64.base64ToByteArray(message), Charset.forName("UTF-8")); + return new String(Base64.getDecoder().decode(message), StandardCharsets.UTF_8); } } diff --git a/src/main/java/org/asteriskjava/manager/event/SkypeLicenseEvent.java b/src/main/java/org/asteriskjava/manager/event/SkypeLicenseEvent.java index 2f2a73c27..2d0d2c09e 100644 --- a/src/main/java/org/asteriskjava/manager/event/SkypeLicenseEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SkypeLicenseEvent.java @@ -25,51 +25,27 @@ * @see org.asteriskjava.manager.action.SkypeLicenseListAction * @since 1.0.0 */ -public class SkypeLicenseEvent extends ResponseEvent -{ +public class SkypeLicenseEvent extends ResponseEvent { /** * Serial version identifier. */ private static final long serialVersionUID = 1L; - private String file; private String key; private String expires; private String hostId; private Integer channels; private String status; - public SkypeLicenseEvent(Object source) - { + public SkypeLicenseEvent(Object source) { super(source); } - /** - * Returns the name of the file this license is stored in. - * - * @return the name of the file this license is stored in. - */ - public String getFile() - { - return file; - } - - /** - * Sets the name of the file this license is stored in. - * - * @param file the name of the file this license is stored in. - */ - public void setFile(String file) - { - this.file = file; - } - /** * Returns the license key. * * @return the license key. */ - public String getKey() - { + public String getKey() { return key; } @@ -78,8 +54,7 @@ public String getKey() * * @param key the license key. */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } @@ -88,8 +63,7 @@ public void setKey(String key) * * @return the date the license expires in the format "YYYY-MM-DD". */ - public String getExpires() - { + public String getExpires() { return expires; } @@ -98,18 +72,15 @@ public String getExpires() * * @param expires the date the license expires in the format "YYYY-MM-DD". */ - public void setExpires(String expires) - { + public void setExpires(String expires) { this.expires = expires; } - public String getHostId() - { + public String getHostId() { return hostId; } - public void setHostId(String hostId) - { + public void setHostId(String hostId) { this.hostId = hostId; } @@ -118,8 +89,7 @@ public void setHostId(String hostId) * * @return the number of licensed channels. */ - public Integer getChannels() - { + public Integer getChannels() { return channels; } @@ -128,18 +98,15 @@ public Integer getChannels() * * @param channels the number of licensed channels. */ - public void setChannels(Integer channels) - { + public void setChannels(Integer channels) { this.channels = channels; } - public String getStatus() - { + public String getStatus() { return status; } - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } } diff --git a/src/main/java/org/asteriskjava/manager/event/SkypeLicenseListCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/SkypeLicenseListCompleteEvent.java index ed0c586e6..796d6ec4e 100644 --- a/src/main/java/org/asteriskjava/manager/event/SkypeLicenseListCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SkypeLicenseListCompleteEvent.java @@ -25,15 +25,13 @@ * @see org.asteriskjava.manager.action.SkypeLicenseListAction * @since 1.0.0 */ -public class SkypeLicenseListCompleteEvent extends ResponseEvent -{ +public class SkypeLicenseListCompleteEvent extends ResponseEvent { /** * Serial version identifier. */ private static final long serialVersionUID = 1L; - public SkypeLicenseListCompleteEvent(Object source) - { + public SkypeLicenseListCompleteEvent(Object source) { super(source); } } diff --git a/src/main/java/org/asteriskjava/manager/event/SoftHangupRequestEvent.java b/src/main/java/org/asteriskjava/manager/event/SoftHangupRequestEvent.java new file mode 100644 index 000000000..6179a3e10 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/SoftHangupRequestEvent.java @@ -0,0 +1,73 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +/** + * A HangupEvent is triggered when a channel is hung up. + *

    + * It is implemented in channel.c + */ +public class SoftHangupRequestEvent extends AbstractChannelEvent { + /** + * Serializable version identifier. + */ + static final long serialVersionUID = 0L; + + private Integer cause; + private String language; + private String linkedId; + + public SoftHangupRequestEvent(Object source) { + super(source); + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + /** + * Returns the cause of the hangup. + * + * @return the hangup cause. + * @see org.asteriskjava.live.HangupCause + */ + public Integer getCause() { + return cause; + } + + /** + * Sets the cause of the hangup. + * + * @param cause the hangup cause. + */ + public void setCause(Integer cause) { + this.cause = cause; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/StatusCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/StatusCompleteEvent.java index fbe3c5b6e..74e0a124c 100644 --- a/src/main/java/org/asteriskjava/manager/event/StatusCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/StatusCompleteEvent.java @@ -17,49 +17,66 @@ package org.asteriskjava.manager.event; /** - * A StatusCompleteEvent is triggered after the state of all channels has been reported in response - * to a StatusAction. - * - * @see org.asteriskjava.manager.action.StatusAction - * @see org.asteriskjava.manager.event.StatusEvent - * + * A StatusCompleteEvent is triggered after the state of all channels has been + * reported in response to a StatusAction. + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.StatusAction + * @see org.asteriskjava.manager.event.StatusEvent */ -public class StatusCompleteEvent extends ResponseEvent -{ +public class StatusCompleteEvent extends ResponseEvent { /** * Serial version identifier. */ private static final long serialVersionUID = 0L; private Integer items; - public StatusCompleteEvent(Object source) - { + private Integer listItems; + private String eventList; + + public StatusCompleteEvent(Object source) { super(source); } /** - * Returns the number of channels reported.

    + * Returns the number of channels reported. + *

    * Available since Asterisk 1.6. * * @return the number of channels reported. * @since 1.0.0 */ - public Integer getItems() - { + public Integer getItems() { return items; } /** - * Sets the number of channels reported.

    + * Sets the number of channels reported. + *

    * Available since Asterisk 1.6. * * @param items the number of channels reported. * @since 1.0.0 */ - public void setItems(Integer items) - { + public void setItems(Integer items) { this.items = items; } + + public Integer getListItems() { + return listItems; + } + + public String getEventList() { + return eventList; + } + + public void setEventList(String eventList) { + this.eventList = eventList; + } + + public void setListItems(Integer listItems) { + this.listItems = listItems; + } + } diff --git a/src/main/java/org/asteriskjava/manager/event/StatusEvent.java b/src/main/java/org/asteriskjava/manager/event/StatusEvent.java index 9f3f6606f..193a0be3d 100644 --- a/src/main/java/org/asteriskjava/manager/event/StatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/StatusEvent.java @@ -16,40 +16,47 @@ */ package org.asteriskjava.manager.event; -import org.asteriskjava.util.AstState; - import java.util.Map; /** - * A StatusEvent is triggered for each active channel in response to a StatusAction. + * A StatusEvent is triggered for each active channel in response to a + * StatusAction. * * @author srt * @version $Id$ * @see org.asteriskjava.manager.action.StatusAction */ -public class StatusEvent extends ResponseEvent -{ +public class StatusEvent extends ResponseEvent { /** * Serial version identifier. */ private static final long serialVersionUID = -3619197512835308812L; private String channel; - private String callerIdNum; - private String callerIdName; private String accountCode; - private Integer channelState; - private String channelStateDesc; - private String context; - private String extension; - private Integer priority; private Integer seconds; private String bridgedChannel; private String bridgedUniqueId; private String uniqueId; + private String linkedId; + private String data; + private String readFormat; + private String writeFormat; + private String type; + private String effectiveConnectedLineName; + private String effectiveConnectedLineNum; + private String application; + private String callGroup; + private String nativeFormats; + private String pickupGroup; + private String timeToHangup; private Map variables; + private String dnid; + private String writetrans; + private String bridgeId; + private String readtrans; + private String language; - public StatusEvent(Object source) - { + public StatusEvent(Object source) { super(source); } @@ -58,8 +65,7 @@ public StatusEvent(Object source) * * @return the name of this channel. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -68,84 +74,43 @@ public String getChannel() * * @param channel the name of this channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - /** - * Returns the Caller*ID Number of this channel.

    - * This property is deprecated as of Asterisk 1.4, use {@link #getCallerIdNum()} instead. - * - * @return the Caller*ID Number of this channel or null if none is available. - * @deprecated - */ - @Deprecated public String getCallerId() - { - return callerIdNum; - } - - /** - * Sets the Caller*ID Number of this channel.

    - * This property is deprecated as of Asterisk 1.4. - * - * @param callerIdNum the Caller*ID Number to set. - */ - public void setCallerId(String callerIdNum) - { - this.callerIdNum = callerIdNum; - } - /** * Returns the Caller*ID Number of this channel. + *

    + * This property is deprecated as of Asterisk 1.4, use + * {@link #getCallerIdNum()} instead. * - * @return the Caller*ID Number of this channel or null if none is available. - * @since 0.3 + * @return the Caller*ID Number of this channel or null if none + * is available. + * @deprecated */ - public String getCallerIdNum() - { + @Deprecated + public String getCallerId() { return callerIdNum; } /** * Sets the Caller*ID Number of this channel. + *

    + * This property is deprecated as of Asterisk 1.4. * * @param callerIdNum the Caller*ID Number to set. - * @since 0.3 */ - public void setCallerIdNum(String callerIdNum) - { + public void setCallerId(String callerIdNum) { this.callerIdNum = callerIdNum; } - /** - * Returns the Caller*ID Name of this channel. - * - * @return the Caller*ID Name of this channel or null if none is available. - */ - public String getCallerIdName() - { - return callerIdName; - } - - /** - * Sets the Caller*ID Name of this channel. - * - * @param callerIdName the Caller*ID Name of this channel. - */ - public void setCallerIdName(String callerIdName) - { - this.callerIdName = callerIdName; - } - /** * Returns the account code of this channel. * * @return the account code of this channel. * @since 1.0.0 */ - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } @@ -155,8 +120,7 @@ public String getAccountCode() * @param accountCode the account code of this channel. * @since 1.0.0 */ - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } @@ -166,106 +130,44 @@ public void setAccountCode(String accountCode) * @return the account code of this channel. * @deprecated since 1.0.0, use {@link #getAccountCode()} instead. */ - @Deprecated public String getAccount() - { + @Deprecated + public String getAccount() { return accountCode; } /** - * Sets the account code of this channel.

    - * Asterisk versions up to 1.4 use the "Account" property instead of "AccountCode". + * Sets the account code of this channel. + *

    + * Asterisk versions up to 1.4 use the "Account" property instead of + * "AccountCode". * * @param account the account code of this channel. */ - public void setAccount(String account) - { + public void setAccount(String account) { this.accountCode = account; } - /** - * Returns the state of the channel.

    - * For Asterisk versions prior to 1.6 (that do not send the numeric value) it is derived - * from the descriptive text. - * - * @return the state of the channel. - * @since 1.0.0 - */ - public Integer getChannelState() - { - return channelState == null ? AstState.str2state(channelStateDesc) : channelState; - } - - /** - * Sets the state of the channel. - * - * @param channelState the state of the channel. - * @since 1.0.0 - */ - public void setChannelState(Integer channelState) - { - this.channelState = channelState; - } - - /** - * Returns the state of the channel as a descriptive text. - * - * @return the state of the channel as a descriptive text. - * @since 1.0.0 - */ - public String getChannelStateDesc() - { - return channelStateDesc; - } - - public void setChannelStateDesc(String channelStateDesc) - { - this.channelStateDesc = channelStateDesc; - } - /** * Returns the state of the channel as a descriptive text. * * @return the state of the channel as a descriptive text. * @deprecated use {@link #getChannelStateDesc()} instead. */ - @Deprecated public String getState() - { - return channelStateDesc; - } - - public void setState(String state) - { - this.channelStateDesc = state; - } - - public String getContext() - { - return context; - } - - public void setContext(String context) - { - this.context = context; - } - - public String getExtension() - { - return extension; + @Deprecated + public String getState() { + return getChannelStateDesc(); } - public void setExtension(String extension) - { - this.extension = extension; + public void setState(String state) { + setChannelStateDesc(state); } - public Integer getPriority() - { - return priority; + public String getExtension() { + return getExten(); } - public void setPriority(Integer priority) - { - this.priority = priority; + public void setExtension(String extension) { + setExten(extension); } /** @@ -273,8 +175,7 @@ public void setPriority(Integer priority) * * @return the number of elapsed seconds. */ - public Integer getSeconds() - { + public Integer getSeconds() { return seconds; } @@ -283,8 +184,7 @@ public Integer getSeconds() * * @param seconds the number of elapsed seconds. */ - public void setSeconds(Integer seconds) - { + public void setSeconds(Integer seconds) { this.seconds = seconds; } @@ -294,19 +194,18 @@ public void setSeconds(Integer seconds) * @return the name of the linked channel if this channel is bridged. * @since 1.0.0 */ - public String getBridgedChannel() - { + public String getBridgedChannel() { return bridgedChannel; } /** * Sets the name of the linked channel. * - * @param bridgedChannel the name of the linked channel if this channel is bridged. + * @param bridgedChannel the name of the linked channel if this channel is + * bridged. * @since 1.0.0 */ - public void setBridgedChannel(String bridgedChannel) - { + public void setBridgedChannel(String bridgedChannel) { this.bridgedChannel = bridgedChannel; } @@ -316,43 +215,44 @@ public void setBridgedChannel(String bridgedChannel) * @return the name of the linked channel if this channel is bridged. * @deprecated as of 1.0.0, use {@link #getBridgedChannel()} instead. */ - @Deprecated public String getLink() - { + @Deprecated + public String getLink() { return bridgedChannel; } /** - * Sets the name of the linked channel.

    + * Sets the name of the linked channel. + *

    * Asterisk versions up to 1.4 use "Link" instead of "BridgedChannel". * * @param link the name of the linked channel if this channel is bridged. */ - public void setLink(String link) - { + public void setLink(String link) { this.bridgedChannel = link; } /** - * Returns the unique id of the linked channel if this channel is bridged.

    + * Returns the unique id of the linked channel if this channel is bridged. + *

    * Available since Asterisk 1.6. * * @return the unique id of the linked channel if this channel is bridged. * @since 1.0.0 */ - public String getBridgedUniqueId() - { + public String getBridgedUniqueId() { return bridgedUniqueId; } /** - * Sets the unique id of the linked channel if this channel is bridged.

    + * Sets the unique id of the linked channel if this channel is bridged. + *

    * Available since Asterisk 1.6. * - * @param bridgedUniqueId the unique id of the linked channel if this channel is bridged. + * @param bridgedUniqueId the unique id of the linked channel if this + * channel is bridged. * @since 1.0.0 */ - public void setBridgedUniqueId(String bridgedUniqueId) - { + public void setBridgedUniqueId(String bridgedUniqueId) { this.bridgedUniqueId = bridgedUniqueId; } @@ -361,8 +261,7 @@ public void setBridgedUniqueId(String bridgedUniqueId) * * @return the unique id of this channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -371,33 +270,193 @@ public String getUniqueId() * * @param uniqueId the unique id of this channel. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } /** - * Returns the channel variables if the {@link org.asteriskjava.manager.action.StatusAction#setVariables(String)} - * property has been set.

    + * Returns the channel variables if the + * {@link org.asteriskjava.manager.action.StatusAction#setVariables(String)} + * property has been set. + *

    * Available since Asterisk 1.6 * * @return the channel variables. * @since 1.0.0 */ - public Map getVariables() - { + public Map getVariables() { return variables; } /** - * Sets the channel variables.

    + * Sets the channel variables. + *

    * Available since Asterisk 1.6 * * @param variables the channel variables. * @since 1.0.0 */ - public void setVariables(Map variables) - { + public void setVariables(Map variables) { this.variables = variables; } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public String getReadFormat() { + return readFormat; + } + + public void setReadFormat(String readFormat) { + this.readFormat = readFormat; + } + + public String getWriteFormat() { + return writeFormat; + } + + public void setWriteFormat(String writeFormat) { + this.writeFormat = writeFormat; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getEffectiveConnectedLineName() { + return effectiveConnectedLineName; + } + + public void setEffectiveConnectedLineName(String effectiveConnectedLineName) { + this.effectiveConnectedLineName = effectiveConnectedLineName; + } + + public String getEffectiveConnectedLineNum() { + return effectiveConnectedLineNum; + } + + public void setEffectiveConnectedLineNum(String effectiveConnectedLineNum) { + this.effectiveConnectedLineNum = effectiveConnectedLineNum; + } + + public String getApplication() { + return application; + } + + public void setApplication(String application) { + this.application = application; + } + + public String getCallGroup() { + return callGroup; + } + + public void setCallGroup(String callGroup) { + this.callGroup = callGroup; + } + + public String getNativeFormats() { + return nativeFormats; + } + + public void setNativeFormats(String nativeFormats) { + this.nativeFormats = nativeFormats; + } + + public String getPickupGroup() { + return pickupGroup; + } + + public void setPickupGroup(String pickupGroup) { + this.pickupGroup = pickupGroup; + } + + public String getTimeToHangup() { + return timeToHangup; + } + + public void setTimeToHangup(String timeToHangup) { + this.timeToHangup = timeToHangup; + } + + /** + * @return the dnid + */ + public String getDnid() { + return dnid; + } + + /** + * @param dnid the dnid to set + */ + public void setDnid(String dnid) { + this.dnid = dnid; + } + + /** + * @return the writetrans + */ + public String getWritetrans() { + return writetrans; + } + + /** + * @param writetrans the writetrans to set + */ + public void setWritetrans(String writetrans) { + this.writetrans = writetrans; + } + + /** + * @return the bridgeid + */ + public String getBridgeId() { + return bridgeId; + } + + /** + * @param bridgeid the bridgeid to set + */ + public void setBridgeId(String bridgeid) { + this.bridgeId = bridgeid; + } + + /** + * @return the readtrans + */ + public String getReadtrans() { + return readtrans; + } + + /** + * @param readtrans the readtrans to set + */ + public void setReadtrans(String readtrans) { + this.readtrans = readtrans; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/SuccessfulAuthEvent.java b/src/main/java/org/asteriskjava/manager/event/SuccessfulAuthEvent.java new file mode 100644 index 000000000..33a4ed511 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/SuccessfulAuthEvent.java @@ -0,0 +1,114 @@ +package org.asteriskjava.manager.event; + +/** + * Created by plhk on 1/15/15. + */ +public class SuccessfulAuthEvent extends ManagerEvent { + /** + * + */ + private static final long serialVersionUID = -1075176582208556468L; + private String severity; + private Integer eventVersion; + private String accountId; + private Integer usingPassword; + private String sessiontv; + private String service; + private String eventtv; + private String remoteAddress; + private String localAddress; + private String sessionId; + private String module; + + public SuccessfulAuthEvent(Object source) { + super(source); + } + + public String getSeverity() { + return severity; + } + + public void setSeverity(String severity) { + this.severity = severity; + } + + public Integer getEventVersion() { + return eventVersion; + } + + public void setEventVersion(Integer eventVersion) { + this.eventVersion = eventVersion; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public Integer getUsingPassword() { + return usingPassword; + } + + public void setUsingPassword(Integer usingPassword) { + this.usingPassword = usingPassword; + } + + public String getSessiontv() { + return sessiontv; + } + + public void setSessiontv(String sessiontv) { + this.sessiontv = sessiontv; + } + + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } + + public String getEventtv() { + return eventtv; + } + + public void setEventtv(String eventtv) { + this.eventtv = eventtv; + } + + public String getRemoteAddress() { + return remoteAddress; + } + + public void setRemoteAddress(String remoteAddress) { + this.remoteAddress = remoteAddress; + } + + public String getLocalAddress() { + return localAddress; + } + + public void setLocalAddress(String localAddress) { + this.localAddress = localAddress; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getModule() { + return module; + } + + public void setModule(String module) { + this.module = module; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/T38FaxStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/T38FaxStatusEvent.java index 9a2a6248b..26f062513 100644 --- a/src/main/java/org/asteriskjava/manager/event/T38FaxStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/T38FaxStatusEvent.java @@ -19,8 +19,7 @@ /** * A FaxDocumentStatusEvent is an event of Digium's Fax For Asterisk add-on. */ -public class T38FaxStatusEvent extends AbstractFaxEvent -{ +public class T38FaxStatusEvent extends AbstractFaxEvent { /** * Serial version identifier. */ @@ -40,8 +39,12 @@ public class T38FaxStatusEvent extends AbstractFaxEvent private Integer minimumJitterSpace; private Integer unrecoverablePackets; - public T38FaxStatusEvent(Object source) - { + private String language; + private String accountCode; + private String linkedId; + private String uniqueId; + + public T38FaxStatusEvent(Object source) { super(source); } @@ -49,274 +52,269 @@ public T38FaxStatusEvent(Object source) /** * @return the maxLag */ - public String getMaxLag() - { + public String getMaxLag() { return maxLag; } /** * @param maxLag the maxLag to set */ - public void setMaxLag(String maxLag) - { + public void setMaxLag(String maxLag) { this.maxLag = maxLag; } /** * @return the totalLag */ - public String getTotalLag() - { + public String getTotalLag() { return totalLag; } /** * @param totalLag the totalLag to set */ - public void setTotalLag(String totalLag) - { + public void setTotalLag(String totalLag) { this.totalLag = totalLag; } /** * @return the averageLag */ - public String getAverageLag() - { + public String getAverageLag() { return averageLag; } /** * @param averageLag the averageLag to set */ - public void setAverageLag(String averageLag) - { + public void setAverageLag(String averageLag) { this.averageLag = averageLag; } /** * @return the totalEvents */ - public Integer getTotalEvents() - { + public Integer getTotalEvents() { return totalEvents; } /** * @param totalEvents the totalEvents to set */ - public void setTotalEvents(Integer totalEvents) - { + public void setTotalEvents(Integer totalEvents) { this.totalEvents = totalEvents; } /** * @return the t38SessionDuration */ - public String getT38SessionDuration() - { + public String getT38SessionDuration() { return t38SessionDuration; } /** * @param t38SessionDuration the t38SessionDuration to set */ - public void setT38SessionDuration(String t38SessionDuration) - { + public void setT38SessionDuration(String t38SessionDuration) { this.t38SessionDuration = t38SessionDuration; } /** * @return the t38PacketsSent */ - public Integer getT38PacketsSent() - { + public Integer getT38PacketsSent() { return t38PacketsSent; } /** * @param t38PacketsSent the t38PacketsSent to set */ - public void setT38PacketsSent(Integer t38PacketsSent) - { + public void setT38PacketsSent(Integer t38PacketsSent) { this.t38PacketsSent = t38PacketsSent; } /** * @return the t38OctetsSent */ - public Integer getT38OctetsSent() - { + public Integer getT38OctetsSent() { return t38OctetsSent; } /** * @param t38OctetsSent the t38OctetsSent to set */ - public void setT38OctetsSent(Integer t38OctetsSent) - { + public void setT38OctetsSent(Integer t38OctetsSent) { this.t38OctetsSent = t38OctetsSent; } /** * @return the averageTxDataRate */ - public String getAverageTxDataRate() - { + public String getAverageTxDataRate() { return averageTxDataRate; } /** * @param averageTxDataRate the averageTxDataRate to set */ - public void setAverageTxDataRate(String averageTxDataRate) - { + public void setAverageTxDataRate(String averageTxDataRate) { this.averageTxDataRate = averageTxDataRate; } /** * @return the t38PacketsReceived */ - public Integer getT38PacketsReceived() - { + public Integer getT38PacketsReceived() { return t38PacketsReceived; } /** * @param t38PacketsReceived the t38PacketsReceived to set */ - public void setT38PacketsReceived(Integer t38PacketsReceived) - { + public void setT38PacketsReceived(Integer t38PacketsReceived) { this.t38PacketsReceived = t38PacketsReceived; } /** * @return the t38OctetsReceived */ - public Integer getT38OctetsReceived() - { + public Integer getT38OctetsReceived() { return t38OctetsReceived; } /** * @param t38OctetsReceived the t38OctetsReceived to set */ - public void setT38OctetsReceived(Integer t38OctetsReceived) - { + public void setT38OctetsReceived(Integer t38OctetsReceived) { this.t38OctetsReceived = t38OctetsReceived; } /** * @return the averageRxDataRate */ - public String getAverageRxDataRate() - { + public String getAverageRxDataRate() { return averageRxDataRate; } /** * @param averageRxDataRate the averageRxDataRate to set */ - public void setAverageRxDataRate(String averageRxDataRate) - { + public void setAverageRxDataRate(String averageRxDataRate) { this.averageRxDataRate = averageRxDataRate; } /** * @return the jitterBufferOverflows */ - public Integer getJitterBufferOverflows() - { + public Integer getJitterBufferOverflows() { return jitterBufferOverflows; } /** * @param jitterBufferOverflows the jitterBufferOverflows to set */ - public void setJitterBufferOverflows(Integer jitterBufferOverflows) - { + public void setJitterBufferOverflows(Integer jitterBufferOverflows) { this.jitterBufferOverflows = jitterBufferOverflows; } /** * @return the minimumJitterSpace */ - public Integer getMinimumJitterSpace() - { + public Integer getMinimumJitterSpace() { return minimumJitterSpace; } /** * @param minimumJitterSpace the minimumJitterSpace to set */ - public void setMinimumJitterSpace(Integer minimumJitterSpace) - { + public void setMinimumJitterSpace(Integer minimumJitterSpace) { this.minimumJitterSpace = minimumJitterSpace; } /** * @return the unrecoverablePackets */ - public Integer getUnrecoverablePackets() - { + public Integer getUnrecoverablePackets() { return unrecoverablePackets; } /** * @param unrecoverablePackets the unrecoverablePackets to set */ - public void setUnrecoverablePackets(Integer unrecoverablePackets) - { + public void setUnrecoverablePackets(Integer unrecoverablePackets) { this.unrecoverablePackets = unrecoverablePackets; } // convenience methods - public Integer getTotalLagInMilliSeconds() - { + public Integer getTotalLagInMilliSeconds() { final String totalLagStripped = stripUnit(this.totalLag); return totalLagStripped == null ? null : Integer.valueOf(totalLagStripped); } - public Integer getMaxLagInMilliSeconds() - { + public Integer getMaxLagInMilliSeconds() { final String maxLagStripped = stripUnit(this.maxLag); return maxLagStripped == null ? null : Integer.valueOf(maxLagStripped); } - public Double getT38SessionDurationInSeconds() - { + public Double getT38SessionDurationInSeconds() { final String t38SessionDurationStripped = stripUnit(this.t38SessionDuration); return t38SessionDurationStripped == null ? null : Double.valueOf(t38SessionDurationStripped); } - public Double getAverageLagInMilliSeconds() - { + public Double getAverageLagInMilliSeconds() { final String averageLagStripped = stripUnit(this.averageLag); return averageLagStripped == null ? null : Double.valueOf(averageLagStripped); } - public Integer getAverageTxDataRateInBps() - { + public Integer getAverageTxDataRateInBps() { final String averageTxDataRateStripped = stripUnit(this.averageTxDataRate); return averageTxDataRateStripped == null ? null : Integer.valueOf(averageTxDataRateStripped); } - public Integer getAverageRxDataRateInBps() - { + public Integer getAverageRxDataRateInBps() { final String averageRxDataRateStripped = stripUnit(this.averageRxDataRate); return averageRxDataRateStripped == null ? null : Integer.valueOf(averageRxDataRateStripped); } - String stripUnit(String s) - { - if (s == null || s.length() == 0) - { + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + String stripUnit(String s) { + if (s == null || s.length() == 0) { return null; } int index = s.indexOf(' '); - if (index < 0) - { + if (index < 0) { return s; } return s.substring(0, index); diff --git a/src/main/java/org/asteriskjava/manager/event/TransferEvent.java b/src/main/java/org/asteriskjava/manager/event/TransferEvent.java index 9e33d857a..f6532cf65 100644 --- a/src/main/java/org/asteriskjava/manager/event/TransferEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/TransferEvent.java @@ -25,8 +25,7 @@ * @version $Id$ * @since 1.0.0 */ -public class TransferEvent extends ManagerEvent -{ +public class TransferEvent extends ManagerEvent { private static final long serialVersionUID = 1L; public static final String TRANSFER_METHOD_SIP = "SIP"; @@ -45,8 +44,7 @@ public class TransferEvent extends ManagerEvent private String transferContext; private Boolean transfer2Parking; - public TransferEvent(Object source) - { + public TransferEvent(Object source) { super(source); } @@ -55,13 +53,11 @@ public TransferEvent(Object source) * * @return channel the name of the transfering channel. */ - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -70,13 +66,11 @@ public void setChannel(String channel) * * @return the unique id of the transfering channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -85,13 +79,11 @@ public void setUniqueId(String uniqueId) * * @return the transfer method ("SIP"). */ - public String getTransferMethod() - { + public String getTransferMethod() { return transferMethod; } - public void setTransferMethod(String transferMethod) - { + public void setTransferMethod(String transferMethod) { this.transferMethod = transferMethod; } @@ -103,8 +95,7 @@ public void setTransferMethod(String transferMethod) * @see #TRANSFER_TYPE_ATTENDED * @see #TRANSFER_TYPE_BLIND */ - public String getTransferType() - { + public String getTransferType() { return transferType; } @@ -113,8 +104,7 @@ public String getTransferType() * * @return true if this is an attended transfer, false if not. */ - public boolean isAttended() - { + public boolean isAttended() { return TRANSFER_TYPE_ATTENDED.equals(transferType); } @@ -123,13 +113,11 @@ public boolean isAttended() * * @return true if this is an blind transfer, false if not. */ - public boolean isBlind() - { + public boolean isBlind() { return TRANSFER_TYPE_BLIND.equals(transferType); } - public void setTransferType(String transferType) - { + public void setTransferType(String transferType) { this.transferType = transferType; } @@ -138,13 +126,11 @@ public void setTransferType(String transferType) * * @return the SIP call id. */ - public String getSipCallId() - { + public String getSipCallId() { return sipCallId; } - public void setSipCallId(String sipCallId) - { + public void setSipCallId(String sipCallId) { this.sipCallId = sipCallId; } @@ -153,13 +139,11 @@ public void setSipCallId(String sipCallId) * * @return the name of the target channel. */ - public String getTargetChannel() - { + public String getTargetChannel() { return targetChannel; } - public void setTargetChannel(String targetChannel) - { + public void setTargetChannel(String targetChannel) { this.targetChannel = targetChannel; } @@ -168,13 +152,11 @@ public void setTargetChannel(String targetChannel) * * @return the unique id of the target channel. */ - public String getTargetUniqueId() - { + public String getTargetUniqueId() { return targetUniqueId; } - public void setTargetUniqueId(String targetUniqueId) - { + public void setTargetUniqueId(String targetUniqueId) { this.targetUniqueId = targetUniqueId; } @@ -184,15 +166,13 @@ public void setTargetUniqueId(String targetUniqueId) * is returned. * * @return the target extension the call is transfered to or null for attended - * transfers. + * transfers. */ - public String getTransferExten() - { + public String getTransferExten() { return transferExten; } - public void setTransferExten(String transferExten) - { + public void setTransferExten(String transferExten) { this.transferExten = transferExten; } @@ -201,15 +181,13 @@ public void setTransferExten(String transferExten) * blind transfers. If the call is transfered to a parking extension null is returned. * * @return the target context the call is transfered to or null for attended - * transfers and transfers to a parking extension. + * transfers and transfers to a parking extension. */ - public String getTransferContext() - { + public String getTransferContext() { return transferContext; } - public void setTransferContext(String transferContext) - { + public void setTransferContext(String transferContext) { this.transferContext = transferContext; } @@ -218,13 +196,11 @@ public void setTransferContext(String transferContext) * * @return Boolean.TRUE if this is a transfer to a parking extension, null otherwise. */ - public Boolean getTransfer2Parking() - { + public Boolean getTransfer2Parking() { return transfer2Parking; } - public void setTransfer2Parking(Boolean transfer2Parking) - { + public void setTransfer2Parking(Boolean transfer2Parking) { this.transfer2Parking = transfer2Parking; } @@ -233,8 +209,7 @@ public void setTransfer2Parking(Boolean transfer2Parking) * * @return true if this is a transfer to a parking extension, false otherwise. */ - public boolean isParking() - { + public boolean isParking() { return transfer2Parking != null && transfer2Parking; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/TransportDetail.java b/src/main/java/org/asteriskjava/manager/event/TransportDetail.java new file mode 100644 index 000000000..d05aaca2a --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/TransportDetail.java @@ -0,0 +1,257 @@ +package org.asteriskjava.manager.event; + + +/** + * A TransportDetail event is triggered in response to a + * {@link org.asteriskjava.manager.action.PJSipShowEndpoint} + *

    + * + * @author Steve Sether + * @version $Id$ + * @since 12 + */ + +public class TransportDetail extends ResponseEvent { + + /** + * Serial version identifier. + */ + private static final long serialVersionUID = 8558130768089350575L; + private String Event; + private String objectType; + private String pbjectName; + private String protocol; + private String bind; + private int asycOperations; + private String caListFile; + private String caListPath; + private String certFile; + private String privKeyFile; + private String password; + private String externalSignalingAddress; + private int externalSignalingPort; + private String externalMediaAddress; + private String domain; + private String verifyServer; + private String verifyClient; + private Boolean requireClientCert; + private String method; + private String cipher; + private String localNet; + private String tos; + private int cos; + private int websocketWriteTimeout; + private String endpointName; + + + /** + * Serial version identifier. + */ + public TransportDetail(Object source) { + super(source); + } + + public String getEvent() { + return Event; + } + + public void setEvent(String event) { + Event = event; + } + + public String getObjectType() { + return objectType; + } + + public void setObjectType(String objectType) { + this.objectType = objectType; + } + + public String getPbjectName() { + return pbjectName; + } + + public void setPbjectName(String pbjectName) { + this.pbjectName = pbjectName; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getBind() { + return bind; + } + + public void setBind(String bind) { + this.bind = bind; + } + + public int getAsycOperations() { + return asycOperations; + } + + public void setAsycOperations(int asycOperations) { + this.asycOperations = asycOperations; + } + + public String getCaListFile() { + return caListFile; + } + + public void setCaListFile(String caListFile) { + this.caListFile = caListFile; + } + + public String getCaListPath() { + return caListPath; + } + + public void setCaListPath(String caListPath) { + this.caListPath = caListPath; + } + + public String getCertFile() { + return certFile; + } + + public void setCertFile(String certFile) { + this.certFile = certFile; + } + + public String getPrivKeyFile() { + return privKeyFile; + } + + public void setPrivKeyFile(String privKeyFile) { + this.privKeyFile = privKeyFile; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getExternalSignalingAddress() { + return externalSignalingAddress; + } + + public void setExternalSignalingAddress(String externalSignalingAddress) { + this.externalSignalingAddress = externalSignalingAddress; + } + + public int getExternalSignalingPort() { + return externalSignalingPort; + } + + public void setExternalSignalingPort(int externalSignalingPort) { + this.externalSignalingPort = externalSignalingPort; + } + + public String getExternalMediaAddress() { + return externalMediaAddress; + } + + public void setExternalMediaAddress(String externalMediaAddress) { + this.externalMediaAddress = externalMediaAddress; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getVerifyServer() { + return verifyServer; + } + + public void setVerifyServer(String verifyServer) { + this.verifyServer = verifyServer; + } + + public String getVerifyClient() { + return verifyClient; + } + + public void setVerifyClient(String verifyClient) { + this.verifyClient = verifyClient; + } + + public Boolean getRequireClientCert() { + return requireClientCert; + } + + public void setRequireClientCert(Boolean requireClientCert) { + this.requireClientCert = requireClientCert; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public String getCipher() { + return cipher; + } + + public void setCipher(String cipher) { + this.cipher = cipher; + } + + public String getLocalNet() { + return localNet; + } + + public void setLocalNet(String localNet) { + this.localNet = localNet; + } + + public String getTos() { + return tos; + } + + public void setTos(String tos) { + this.tos = tos; + } + + public int getCos() { + return cos; + } + + public void setCos(int cos) { + this.cos = cos; + } + + public int getWebsocketWriteTimeout() { + return websocketWriteTimeout; + } + + public void setWebsocketWriteTimeout(int websocketWriteTimeout) { + this.websocketWriteTimeout = websocketWriteTimeout; + } + + public String getEndpointName() { + return endpointName; + } + + public void setEndpointName(String endpointName) { + this.endpointName = endpointName; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/UnexpectedAddressEvent.java b/src/main/java/org/asteriskjava/manager/event/UnexpectedAddressEvent.java new file mode 100644 index 000000000..7229bb2d6 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/UnexpectedAddressEvent.java @@ -0,0 +1,17 @@ +package org.asteriskjava.manager.event; + +public final class UnexpectedAddressEvent extends AbstractSecurityEvent { + private String expectedAddress; + + public UnexpectedAddressEvent(Object source) { + super(source); + } + + public String getExpectedAddress() { + return expectedAddress; + } + + public void setExpectedAddress(String value) { + this.expectedAddress = value; + } +} diff --git a/src/main/java/org/asteriskjava/manager/event/UnholdEvent.java b/src/main/java/org/asteriskjava/manager/event/UnholdEvent.java index 175bb6455..a17771658 100644 --- a/src/main/java/org/asteriskjava/manager/event/UnholdEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/UnholdEvent.java @@ -18,32 +18,33 @@ /** * An UnholdEvent is triggered by the SIP channel driver when a channel is no - * longer put on hold.

    - * It is implemented in channels/chan_sip.c.

    - * Available since Asterisk 1.2, as of Asterisk 1.6 only {@link org.asteriskjava.manager.event.HoldEvent} is sent - * with the status set to false to indicate unhold. + * longer put on hold. + *

    + * It is implemented in channels/chan_sip.c. + *

    + * Available since Asterisk 1.2, as of Asterisk 1.6 only + * {@link org.asteriskjava.manager.event.HoldEvent} is sent with the status set + * to false to indicate unhold. * * @author srt * @version $Id$ * @see org.asteriskjava.manager.event.HoldEvent - * @since 0.2 - * @deprecated as of 1.0.0, use {@link org.asteriskjava.manager.event.HoldEvent} and its - * {@link #isUnhold()} method instead. + * @since 0.2 Enro 2015-03: No longer deprecated since Asterisk 13 uses this + * again. */ -@Deprecated public class UnholdEvent extends HoldEvent -{ +public class UnholdEvent extends AbstractHoldEvent { /** * Serializable version identifier. */ static final long serialVersionUID = 1L; + /** * Creates a new UnholdEvent. * * @param source */ - public UnholdEvent(Object source) - { + public UnholdEvent(Object source) { super(source); setStatus(false); } diff --git a/src/main/java/org/asteriskjava/manager/event/UnlinkEvent.java b/src/main/java/org/asteriskjava/manager/event/UnlinkEvent.java index 5a53f0e4c..075d7031b 100644 --- a/src/main/java/org/asteriskjava/manager/event/UnlinkEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/UnlinkEvent.java @@ -20,21 +20,20 @@ * An UnlinkEvent is triggered when a link between two voice channels is discontinued, for example, * just before call completion.

    * It is implemented in channel.c - * + * * @author srt * @version $Id$ * @deprecated as of 1.0.0, use {@link org.asteriskjava.manager.event.BridgeEvent} and - * {@link BridgeEvent#isUnlink()} instead + * {@link BridgeEvent#isUnlink()} instead */ -@Deprecated public class UnlinkEvent extends BridgeEvent -{ +@Deprecated +public class UnlinkEvent extends BridgeEvent { /** * Serial version identifier. */ static final long serialVersionUID = -2943257621137870024L; - public UnlinkEvent(Object source) - { + public UnlinkEvent(Object source) { super(source); setBridgeState(BRIDGE_STATE_UNLINK); } diff --git a/src/main/java/org/asteriskjava/manager/event/UnparkedCallEvent.java b/src/main/java/org/asteriskjava/manager/event/UnparkedCallEvent.java index 3b63fb0fd..6795b6521 100644 --- a/src/main/java/org/asteriskjava/manager/event/UnparkedCallEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/UnparkedCallEvent.java @@ -18,44 +18,138 @@ /** * A UnparkedCallEvent is triggered when a channel that has been parked is - * resumed.

    - * It is implemented in res/res_features.c

    + * resumed. + *

    + * It is implemented in res/res_features.c + *

    * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class UnparkedCallEvent extends AbstractParkedCallEvent -{ +public class UnparkedCallEvent extends AbstractUnParkedEvent { /** * Serializable version identifier */ private static final long serialVersionUID = -7437833328723536814L; - private String from; + /** + * Enro 2015-03: Asterisk 13 Support + */ + private String RetrieverChannel; + private Integer RetrieverChannelState; + private String RetrieverChannelStateDesc; + private String RetrieverCallerIDNum; + private String RetrieverCallerIDName; + private String RetrieverConnectedLineNum; + private String RetrieverConnectedLineName; + private String RetrieverAccountCode; + private String RetrieverContext; + private String RetrieverExten; + private String RetrieverPriority; + private String RetrieverUniqueid; /** * @param source */ - public UnparkedCallEvent(Object source) - { + public UnparkedCallEvent(Object source) { super(source); } - /** - * Returns the name of the channel that parked the call. - */ - public String getFrom() - { - return from; + public String getRetrieverChannel() { + return RetrieverChannel; } - /** - * Sets the name of the channel that parked the call. - */ - public void setFrom(String from) - { - this.from = from; + public void setRetrieverChannel(String retrieverChannel) { + RetrieverChannel = retrieverChannel; + } + + public Integer getRetrieverChannelState() { + return RetrieverChannelState; + } + + public void setRetrieverChannelState(Integer retrieverChannelState) { + RetrieverChannelState = retrieverChannelState; + } + + public String getRetrieverChannelStateDesc() { + return RetrieverChannelStateDesc; + } + + public void setRetrieverChannelStateDesc(String retrieverChannelStateDesc) { + RetrieverChannelStateDesc = retrieverChannelStateDesc; + } + + public String getRetrieverCallerIDNum() { + return RetrieverCallerIDNum; + } + + public void setRetrieverCallerIDNum(String retrieverCallerIDNum) { + RetrieverCallerIDNum = retrieverCallerIDNum; + } + + public String getRetrieverCallerIDName() { + return RetrieverCallerIDName; + } + + public void setRetrieverCallerIDName(String retrieverCallerIDName) { + RetrieverCallerIDName = retrieverCallerIDName; + } + + public String getRetrieverConnectedLineNum() { + return RetrieverConnectedLineNum; + } + + public void setRetrieverConnectedLineNum(String retrieverConnectedLineNum) { + RetrieverConnectedLineNum = retrieverConnectedLineNum; + } + + public String getRetrieverConnectedLineName() { + return RetrieverConnectedLineName; + } + + public void setRetrieverConnectedLineName(String retrieverConnectedLineName) { + RetrieverConnectedLineName = retrieverConnectedLineName; + } + + public String getRetrieverAccountCode() { + return RetrieverAccountCode; + } + + public void setRetrieverAccountCode(String retrieverAccountCode) { + RetrieverAccountCode = retrieverAccountCode; + } + + public String getRetrieverContext() { + return RetrieverContext; + } + + public void setRetrieverContext(String retrieverContext) { + RetrieverContext = retrieverContext; + } + + public String getRetrieverExten() { + return RetrieverExten; + } + + public void setRetrieverExten(String retrieverExten) { + RetrieverExten = retrieverExten; + } + + public String getRetrieverPriority() { + return RetrieverPriority; + } + + public void setRetrieverPriority(String retrieverPriority) { + RetrieverPriority = retrieverPriority; + } + + public String getRetrieverUniqueid() { + return RetrieverUniqueid; + } + + public void setRetrieverUniqueid(String retrieverUniqueid) { + RetrieverUniqueid = retrieverUniqueid; } } diff --git a/src/main/java/org/asteriskjava/manager/event/UnpausedEvent.java b/src/main/java/org/asteriskjava/manager/event/UnpausedEvent.java new file mode 100644 index 000000000..cd6196e0e --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/UnpausedEvent.java @@ -0,0 +1,34 @@ +package org.asteriskjava.manager.event; + +public class UnpausedEvent extends UserEvent { + + public UnpausedEvent(Object source) { + super(source); + } + + /** + * + */ + private static final long serialVersionUID = 4175034098824101733L; + + private String header; + + private String extension; + + public String getHeader() { + return header; + } + + public void setHeader(String header) { + this.header = header; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/UserEvent.java b/src/main/java/org/asteriskjava/manager/event/UserEvent.java index 1b9bf834c..6a8f6a377 100644 --- a/src/main/java/org/asteriskjava/manager/event/UserEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/UserEvent.java @@ -17,52 +17,62 @@ package org.asteriskjava.manager.event; /** - * Abstract base class for user events.

    - * You can send arbitrary user events via the UserEvent application provided with asterisk. A user - * event by default has the attributes channel and uniqueId but you can add custom attributes by - * specifying an event body.

    - * To add your own user events you must subclass this class and name it corresponding to your event. - * If you plan to send an event by UserEvent(VIPCall) you will create a new class - * called VIPCallEvent that extends UserEvent. The name of this class is important: Just use the - * name of the event you will send (VIPCall in this example) and append "Event".

    - * To pass additional data create appropriate attributes with getter and setter methods in your - * new class.

    + * Abstract base class for user events. + *

    + * You can send arbitrary user events via the UserEvent application provided + * with asterisk. A user event by default has the attributes channel and + * uniqueId but you can add custom attributes by specifying an event body. + *

    + * To add your own user events you must subclass this class and name it + * corresponding to your event. If you plan to send an event by + * UserEvent(VIPCall) you will create a new class called + * VIPCallEvent that extends UserEvent. The name of this class is important: + * Just use the name of the event you will send (VIPCall in this example) and + * append "Event". + *

    + * To pass additional data create appropriate attributes with getter and setter + * methods in your new class. + *

    * Example: + * *

      * public class VIPCallEvent extends UserEvent
      * {
    - *   private String firstName;
    - * 
    - *   public VIPCallEvent(Object source)
    - *   {
    - *     super(source);
    - *   }
    - *   
    - *   public String getFirstName()
    - *   {
    - *     return firstName;
    - *   }
    - *   
    - *   public void setFirstName(String firstName)
    - *   {
    - *     this.firstName = firstName;
    - *   }
    + *     private String firstName;
    + *
    + *     public VIPCallEvent(Object source)
    + *     {
    + *         super(source);
    + *     }
    + *
    + *     public String getFirstName()
    + *     {
    + *         return firstName;
    + *     }
    + *
    + *     public void setFirstName(String firstName)
    + *     {
    + *         this.firstName = firstName;
    + *     }
      * }
      * 
    - * To send this event use UserEvent(VIPCall|firstName: Jon) in your dialplan. Asterisk - * up to 1.2 (including) does only support one property in the UserEvent so something like - * UserEvent(VIPCall|firstName: Jon|lastName: Doe) will not work as expected.

    - * The UserEvent is implemented in apps/app_userevent.c.

    - * Note that you must register your UserEvent with the ManagerConnection you are using in order - * to be recognized. - * - * @see org.asteriskjava.manager.ManagerConnection#registerUserEventClass(Class) - * + *

    + * To send this event use UserEvent(VIPCall|firstName: Jon) in your + * dialplan. Asterisk up to 1.2 (including) does only support one property in + * the UserEvent so something like + * UserEvent(VIPCall|firstName: Jon|lastName: Doe) will not work as + * expected. + *

    + * The UserEvent is implemented in apps/app_userevent.c. + *

    + * Note that you must register your UserEvent with the ManagerConnection you are + * using in order to be recognized. + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.ManagerConnection#registerUserEventClass(Class) */ -public abstract class UserEvent extends ManagerEvent -{ +public abstract class UserEvent extends ManagerEvent { /** * Serial version identifier */ @@ -78,48 +88,43 @@ public abstract class UserEvent extends ManagerEvent */ private String uniqueId; - public UserEvent(Object source) - { + public UserEvent(Object source) { super(source); } /** * Returns the name of the channel this event occured in. - * + * * @return the name of the channel this event occured in. */ - public String getChannel() - { + public String getChannel() { return channel; } /** * Sets the name of the channel this event occured in. - * + * * @param channel the name of the channel this event occured in. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * Returns the unqiue id of the channel this event occured in. - * + * * @return the unqiue id of the channel this event occured in. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } /** * Sets the unqiue id of the channel this event occured in. - * + * * @param uniqueId the unqiue id of the channel this event occured in. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } } diff --git a/src/main/java/org/asteriskjava/manager/event/VarSetEvent.java b/src/main/java/org/asteriskjava/manager/event/VarSetEvent.java index 25de29fbc..2bf16e395 100644 --- a/src/main/java/org/asteriskjava/manager/event/VarSetEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/VarSetEvent.java @@ -17,55 +17,67 @@ package org.asteriskjava.manager.event; /** - * A VarSetEvent is triggered when a channel or global variable is set in Asterisk.

    - * Available since Asterisk 1.6

    + * A VarSetEvent is triggered when a channel or global variable is set in + * Asterisk. + *

    + * Available since Asterisk 1.6 + *

    * It is implemented in main/pbx.c * * @author srt * @version $Id$ * @since 1.0.0 */ -public class VarSetEvent extends ManagerEvent -{ +public class VarSetEvent extends ManagerEvent { static final long serialVersionUID = 1L; private String channel; private String uniqueId; private String variable; private String value; + private String language; + private String linkedId; + private String accountCode; - public VarSetEvent(Object source) - { + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + public VarSetEvent(Object source) { super(source); } /** - * Returns the name of the channel or null for global variables. + * Returns the name of the channel or null for global + * variables. * - * @return the name of the channel or null for global variables. + * @return the name of the channel or null for global + * variables. */ - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** - * Returns the unique id of the channel or null for global variables. + * Returns the unique id of the channel or null for global + * variables. * - * @return the unique id of the channel or null for global variables. + * @return the unique id of the channel or null for global + * variables. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -74,13 +86,11 @@ public void setUniqueId(String uniqueId) * * @return the name of the variable that has been set. */ - public String getVariable() - { + public String getVariable() { return variable; } - public void setVariable(String variable) - { + public void setVariable(String variable) { this.variable = variable; } @@ -89,13 +99,28 @@ public void setVariable(String variable) * * @return the new value of the variable. */ - public String getValue() - { + public String getValue() { return value; } - public void setValue(String value) - { + public void setValue(String value) { this.value = value; } -} \ No newline at end of file + + public String getLinkedId() { + return linkedId; + } + + public void setLinkedId(String linkedId) { + this.linkedId = linkedId; + } + + public String getAccountCode() { + return accountCode; + } + + public void setAccountCode(String accountCode) { + this.accountCode = accountCode; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryCompleteEvent.java index 46039db1a..6f1aebdad 100644 --- a/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryCompleteEvent.java @@ -23,14 +23,13 @@ *

    * Available since Asterisk 1.6 * - * @see VoicemailUserEntryEvent - * @see org.asteriskjava.manager.action.VoicemailUsersListAction * @author srt * @version $Id$ + * @see VoicemailUserEntryEvent + * @see org.asteriskjava.manager.action.VoicemailUsersListAction * @since 1.0.0 */ -public class VoicemailUserEntryCompleteEvent extends ResponseEvent -{ +public class VoicemailUserEntryCompleteEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -41,8 +40,7 @@ public class VoicemailUserEntryCompleteEvent extends ResponseEvent * * @param source */ - public VoicemailUserEntryCompleteEvent(Object source) - { + public VoicemailUserEntryCompleteEvent(Object source) { super(source); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryEvent.java b/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryEvent.java index b48524a0e..8fbc8fd14 100644 --- a/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryEvent.java @@ -20,7 +20,7 @@ * A VoicemailUserEntryCompleteEvent is triggered in response to a VoicemailUsersListAction * and contains the details about a voicemail user.

    * It is implemented in apps/app_voicemail.c - *

    + *
    * Available since Asterisk 1.6 * * @author srt @@ -29,8 +29,7 @@ * @see org.asteriskjava.manager.action.VoicemailUsersListAction * @since 1.0.0 */ -public class VoicemailUserEntryEvent extends ResponseEvent -{ +public class VoicemailUserEntryEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -70,8 +69,7 @@ public class VoicemailUserEntryEvent extends ResponseEvent * * @param source */ - public VoicemailUserEntryEvent(Object source) - { + public VoicemailUserEntryEvent(Object source) { super(source); } @@ -80,8 +78,7 @@ public VoicemailUserEntryEvent(Object source) * * @return the voicemail context. */ - public String getVmContext() - { + public String getVmContext() { return vmContext; } @@ -90,8 +87,7 @@ public String getVmContext() * * @param vmContext the voicemail context. */ - public void setVmContext(String vmContext) - { + public void setVmContext(String vmContext) { this.vmContext = vmContext; } @@ -100,8 +96,7 @@ public void setVmContext(String vmContext) * * @return the mailbox id. */ - public String getVoicemailbox() - { + public String getVoicemailbox() { return voicemailbox; } @@ -110,8 +105,7 @@ public String getVoicemailbox() * * @param voicemailbox the mailbox id. */ - public void setVoicemailbox(String voicemailbox) - { + public void setVoicemailbox(String voicemailbox) { this.voicemailbox = voicemailbox; } @@ -120,8 +114,7 @@ public void setVoicemailbox(String voicemailbox) * * @return the full name of the voicemail user. */ - public String getFullname() - { + public String getFullname() { return fullname; } @@ -130,8 +123,7 @@ public String getFullname() * * @param fullname the full name of the voicemail user. */ - public void setFullname(String fullname) - { + public void setFullname(String fullname) { this.fullname = fullname; } @@ -140,8 +132,7 @@ public void setFullname(String fullname) * * @return the email address of the voicemail user. */ - public String getEmail() - { + public String getEmail() { return email; } @@ -150,8 +141,7 @@ public String getEmail() * * @param email the email address of the voicemail user. */ - public void setEmail(String email) - { + public void setEmail(String email) { this.email = email; } @@ -161,8 +151,7 @@ public void setEmail(String email) * * @return the email adress of pager of the voicemail user. */ - public String getPager() - { + public String getPager() { return pager; } @@ -171,8 +160,7 @@ public String getPager() * * @param pager the email adress of pager of the voicemail user. */ - public void setPager(String pager) - { + public void setPager(String pager) { this.pager = pager; } @@ -181,8 +169,7 @@ public void setPager(String pager) * * @return the email address used for the "from" header when sending notification emails. */ - public String getServerEmail() - { + public String getServerEmail() { return serverEmail; } @@ -191,8 +178,7 @@ public String getServerEmail() * * @param serverEmail the email address used for the "from" header when sending notification emails. */ - public void setServerEmail(String serverEmail) - { + public void setServerEmail(String serverEmail) { this.serverEmail = serverEmail; } @@ -201,8 +187,7 @@ public void setServerEmail(String serverEmail) * * @return the custom mail command used to send notifications to the voicemail user. */ - public String getMailCommand() - { + public String getMailCommand() { return mailCommand; } @@ -211,28 +196,23 @@ public String getMailCommand() * * @param mailCommand the custom mail command used to send notifications to the voicemail user. */ - public void setMailCommand(String mailCommand) - { + public void setMailCommand(String mailCommand) { this.mailCommand = mailCommand; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getTimezone() - { + public String getTimezone() { return timezone; } - public void setTimezone(String timezone) - { + public void setTimezone(String timezone) { this.timezone = timezone; } @@ -241,10 +221,9 @@ public void setTimezone(String timezone) * voicemail features menu. * * @return the dialplan context used by the "return phone call" feature in the advanced - * voicemail features menu. + * voicemail features menu. */ - public String getCallback() - { + public String getCallback() { return callback; } @@ -255,8 +234,7 @@ public String getCallback() * @param callback the dialplan context used by the "return phone call" feature in the advanced * voicemail features menu. */ - public void setCallback(String callback) - { + public void setCallback(String callback) { this.callback = callback; } @@ -265,10 +243,9 @@ public void setCallback(String callback) * voicemail features menu. * * @return the dialplan context used by the "place an outgoing call" feature in the advanced - * voicemail features menu. + * voicemail features menu. */ - public String getDialout() - { + public String getDialout() { return dialout; } @@ -279,18 +256,15 @@ public String getDialout() * @param dialout the dialplan context used by the "place an outgoing call" feature in the advanced * voicemail features menu. */ - public void setDialout(String dialout) - { + public void setDialout(String dialout) { this.dialout = dialout; } - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -299,8 +273,7 @@ public void setUniqueId(String uniqueId) * * @return the dialplan context the user is dropped into after he has pressed * or 0 to exit voicemail. */ - public String getExitContext() - { + public String getExitContext() { return exitContext; } @@ -309,38 +282,31 @@ public String getExitContext() * * @param exitContext the dialplan context the user is dropped into after he has pressed * or 0 to exit voicemail. */ - public void setExitContext(String exitContext) - { + public void setExitContext(String exitContext) { this.exitContext = exitContext; } - public Integer getSayDurationMinimum() - { + public Integer getSayDurationMinimum() { return sayDurationMinimum; } - public void setSayDurationMinimum(Integer sayDurationMinimum) - { + public void setSayDurationMinimum(Integer sayDurationMinimum) { this.sayDurationMinimum = sayDurationMinimum; } - public Boolean getSayEnvelope() - { + public Boolean getSayEnvelope() { return sayEnvelope; } - public void setSayEnvelope(Boolean sayEnvelope) - { + public void setSayEnvelope(Boolean sayEnvelope) { this.sayEnvelope = sayEnvelope; } - public Boolean getSayCid() - { + public Boolean getSayCid() { return sayCid; } - public void setSayCid(Boolean sayCid) - { + public void setSayCid(Boolean sayCid) { this.sayCid = sayCid; } @@ -350,8 +316,7 @@ public void setSayCid(Boolean sayCid) * * @return Booelan.TRUE if message will be attached, Boolean.FALSE if not, null if unset. */ - public Boolean getAttachMessage() - { + public Boolean getAttachMessage() { return attachMessage; } @@ -361,18 +326,15 @@ public Boolean getAttachMessage() * * @param attachMessage Booelan.TRUE if message will be attached, Boolean.FALSE if not, null if unset. */ - public void setAttachMessage(Boolean attachMessage) - { + public void setAttachMessage(Boolean attachMessage) { this.attachMessage = attachMessage; } - public String getAttachmentFormat() - { + public String getAttachmentFormat() { return attachmentFormat; } - public void setAttachmentFormat(String attachmentFormat) - { + public void setAttachmentFormat(String attachmentFormat) { this.attachmentFormat = attachmentFormat; } @@ -380,10 +342,9 @@ public void setAttachmentFormat(String attachmentFormat) * Returns whether messages will be deleted from the voicemailbox (after having been emailed). * * @return Booelan.TRUE if messages will be deleted from the voicemailbox, Boolean.FALSE if not, - * null if unset. + * null if unset. */ - public Boolean getDeleteMessage() - { + public Boolean getDeleteMessage() { return deleteMessage; } @@ -392,8 +353,7 @@ public Boolean getDeleteMessage() * * @param deleteMessage Booelan.TRUE if messages will be deleted from the voicemailbox, Boolean.FALSE if not. */ - public void setDeleteMessage(Boolean deleteMessage) - { + public void setDeleteMessage(Boolean deleteMessage) { this.deleteMessage = deleteMessage; } @@ -402,8 +362,7 @@ public void setDeleteMessage(Boolean deleteMessage) * * @return the volume gain used for voicemails sent via email. */ - public Double getVolumeGain() - { + public Double getVolumeGain() { return volumeGain; } @@ -412,28 +371,23 @@ public Double getVolumeGain() * * @param volumeGain the volume gain used for voicemails sent via email. */ - public void setVolumeGain(Double volumeGain) - { + public void setVolumeGain(Double volumeGain) { this.volumeGain = volumeGain; } - public Boolean getCanReview() - { + public Boolean getCanReview() { return canReview; } - public void setCanReview(Boolean canReview) - { + public void setCanReview(Boolean canReview) { this.canReview = canReview; } - public Boolean getCallOperator() - { + public Boolean getCallOperator() { return callOperator; } - public void setCallOperator(Boolean callOperator) - { + public void setCallOperator(Boolean callOperator) { this.callOperator = callOperator; } @@ -442,8 +396,7 @@ public void setCallOperator(Boolean callOperator) * * @return the maximum number of messages per folder or 0 for unlimited. */ - public Integer getMaxMessageCount() - { + public Integer getMaxMessageCount() { return maxMessageCount; } @@ -452,8 +405,7 @@ public Integer getMaxMessageCount() * * @param maxMessageCount the maximum number of messages per folder. */ - public void setMaxMessageCount(Integer maxMessageCount) - { + public void setMaxMessageCount(Integer maxMessageCount) { this.maxMessageCount = maxMessageCount; } @@ -462,8 +414,7 @@ public void setMaxMessageCount(Integer maxMessageCount) * * @return the maximum duration in seconds. */ - public Integer getMaxMessageLength() - { + public Integer getMaxMessageLength() { return maxMessageLength; } @@ -472,18 +423,15 @@ public Integer getMaxMessageLength() * * @param maxMessageLength the maximum duration in seconds. */ - public void setMaxMessageLength(Integer maxMessageLength) - { + public void setMaxMessageLength(Integer maxMessageLength) { this.maxMessageLength = maxMessageLength; } - public Integer getNewMessageCount() - { + public Integer getNewMessageCount() { return newMessageCount; } - public void setNewMessageCount(Integer newMessageCount) - { + public void setNewMessageCount(Integer newMessageCount) { this.newMessageCount = newMessageCount; } @@ -493,8 +441,7 @@ public void setNewMessageCount(Integer newMessageCount) * * @return the number of old messages for this voicemail user. */ - public Integer getOldMessageCount() - { + public Integer getOldMessageCount() { return oldMessageCount; } @@ -503,8 +450,7 @@ public Integer getOldMessageCount() * * @param oldMessageCount the number of old messages for this voicemail user. */ - public void setOldMessageCount(Integer oldMessageCount) - { + public void setOldMessageCount(Integer oldMessageCount) { this.oldMessageCount = oldMessageCount; } @@ -514,8 +460,7 @@ public void setOldMessageCount(Integer oldMessageCount) * * @return the username of the IMAP account associated with this mailbox. */ - public String getImapUser() - { + public String getImapUser() { return imapUser; } @@ -524,8 +469,7 @@ public String getImapUser() * * @param imapUser the username of the IMAP account associated with this mailbox. */ - public void setImapUser(String imapUser) - { + public void setImapUser(String imapUser) { this.imapUser = imapUser; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsCompleteEvent.java index fef123bf9..55e10313e 100644 --- a/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsCompleteEvent.java @@ -19,15 +19,13 @@ /** * A ZapShowChannelsCompleteEvent is triggered after the state of all zap channels has been reported * in response to a ZapShowChannelsAction. - * - * @see org.asteriskjava.manager.action.ZapShowChannelsAction - * @see org.asteriskjava.manager.event.ZapShowChannelsEvent - * + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.ZapShowChannelsAction + * @see org.asteriskjava.manager.event.ZapShowChannelsEvent */ -public class ZapShowChannelsCompleteEvent extends ResponseEvent -{ +public class ZapShowChannelsCompleteEvent extends ResponseEvent { /** * Serial version identifier */ @@ -36,8 +34,7 @@ public class ZapShowChannelsCompleteEvent extends ResponseEvent /** * @param source */ - public ZapShowChannelsCompleteEvent(Object source) - { + public ZapShowChannelsCompleteEvent(Object source) { super(source); } } diff --git a/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsEvent.java b/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsEvent.java index c2550cbf9..5460927b2 100644 --- a/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsEvent.java @@ -17,57 +17,53 @@ package org.asteriskjava.manager.event; /** - * A ZapShowChannelsEvent is triggered in response to a ZapShowChannelsAction and shows the state of - * a zap channel. - * - * @see org.asteriskjava.manager.action.ZapShowChannelsAction - * + * A ZapShowChannelsEvent is triggered in response to a ZapShowChannelsAction + * and shows the state of a zap channel. + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.ZapShowChannelsAction */ -public class ZapShowChannelsEvent extends ResponseEvent -{ +public class ZapShowChannelsEvent extends ResponseEvent { /** * Serial version identifier */ private static final long serialVersionUID = -3613642267527361400L; private Integer channel; private String signalling; - private String context; + // private String context; private Boolean dnd; private String alarm; /** * @param source */ - public ZapShowChannelsEvent(Object source) - { + public ZapShowChannelsEvent(Object source) { super(source); } /** * Returns the number of this zap channel. */ - public Integer getChannel() - { + public Integer getChannel() { return channel; } /** * Sets the number of this zap channel. */ - public void setChannel(Integer channel) - { + public void setChannel(Integer channel) { this.channel = channel; } /** - * Returns the signalling of this zap channel.

    + * Returns the signalling of this zap channel. + *

    * Possible values are: *

      - *
    • E & M Immediate
    • - *
    • E & M Wink
    • - *
    • E & M E1
    • + *
    • E & M Immediate
    • + *
    • E & M Wink
    • + *
    • E & M E1
    • *
    • Feature Group D (DTMF)
    • *
    • Feature Group D (MF)
    • *
    • Feature Group B (MF)
    • @@ -90,60 +86,42 @@ public void setChannel(Integer channel) *
    • Pseudo Signalling
    • *
    */ - public String getSignalling() - { + public String getSignalling() { return signalling; } /** * Sets the signalling of this zap channel. */ - public void setSignalling(String signalling) - { + public void setSignalling(String signalling) { this.signalling = signalling; } - /** - * Returns the context of this zap channel as defined in zapata.conf. - */ - public String getContext() - { - return context; - } - - /** - * Sets the context of this zap channel. - */ - public void setContext(String context) - { - this.context = context; - } - /** * Returns whether dnd (do not disturb) is enabled for this zap channel. - * + * * @return Boolean.TRUE if dnd is enabled, Boolean.FALSE if it is disabled, - * null if not set. + * null if not set. * @since 0.3 */ - public Boolean getDnd() - { + public Boolean getDnd() { return dnd; } /** * Sets whether dnd (do not disturb) is enabled for this zap channel. - * - * @param dnd Boolean.TRUE if dnd is enabled, Boolean.FALSE if it is disabled. + * + * @param dnd Boolean.TRUE if dnd is enabled, Boolean.FALSE if it is + * disabled. * @since 0.3 */ - public void setDnd(Boolean dnd) - { + public void setDnd(Boolean dnd) { this.dnd = dnd; } /** - * Returns the alarm state of this zap channel.

    + * Returns the alarm state of this zap channel. + *

    * This may be one of *

      *
    • Red Alarm
    • @@ -155,16 +133,14 @@ public void setDnd(Boolean dnd) *
    • No Alarm
    • *
    */ - public String getAlarm() - { + public String getAlarm() { return alarm; } /** * Sets the alarm state of this zap channel. */ - public void setAlarm(String alarm) - { + public void setAlarm(String alarm) { this.alarm = alarm; } } diff --git a/src/main/java/org/asteriskjava/manager/event/package.html b/src/main/java/org/asteriskjava/manager/event/package.html index d6d1dcb81..92e1e1d1d 100644 --- a/src/main/java/org/asteriskjava/manager/event/package.html +++ b/src/main/java/org/asteriskjava/manager/event/package.html @@ -1,28 +1,28 @@ - +

    Provides classes that represent the standard events that can be received - from an Asterisk server via the Manager API.

    + from an Asterisk server via the Manager API.

    - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/manager/internal/AbstractBuilder.java b/src/main/java/org/asteriskjava/manager/internal/AbstractBuilder.java deleted file mode 100644 index 94295d16e..000000000 --- a/src/main/java/org/asteriskjava/manager/internal/AbstractBuilder.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.asteriskjava.manager.internal; - -import org.asteriskjava.manager.event.UserEvent; -import org.asteriskjava.util.AstUtil; -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; -import org.asteriskjava.util.ReflectionUtil; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Abstract base class for reflection based builders. - */ -abstract class AbstractBuilder -{ - protected final Log logger = LogFactory.getLog(getClass()); - - @SuppressWarnings("unchecked") - protected void setAttributes(Object target, Map attributes, Set ignoredAttributes) - { - Map setters; - - setters = ReflectionUtil.getSetters(target.getClass()); - for (Map.Entry entry : attributes.entrySet()) - { - Object value; - final Class dataType; - Method setter; - String setterName; - - if (ignoredAttributes != null && ignoredAttributes.contains(entry.getKey())) - { - continue; - } - - setterName = ReflectionUtil.stripIllegalCharacters(entry.getKey()); - /* - * The source property needs special handling as it is already - * defined in java.util.EventObject (the base class of - * ManagerEvent), so we have to translate it. - */ - if ("source".equals(setterName)) - { - setterName = "src"; - } - - setter = setters.get(setterName); - if (setter == null && !setterName.endsWith("s")) // no exact match => try plural - { - setter = setters.get(setterName + "s"); - // but only for maps - if (setter != null && ! (setter.getParameterTypes()[0].isAssignableFrom(Map.class))) - { - setter = null; - } - } - - // it seems silly to warn if it's a user event -- maybe it was intentional - if (setter == null && !(target instanceof UserEvent)) - { - logger.warn("Unable to set property '" + entry.getKey() + "' to '" + entry.getValue() + "' on " - + target.getClass().getName() + ": no setter. Please report at http://jira.reucon.org/browse/AJ"); - } - - if (setter == null) - { - continue; - } - - dataType = setter.getParameterTypes()[0]; - - if (dataType == Boolean.class) - { - value = AstUtil.isTrue(entry.getValue()); - } - else if (dataType.isAssignableFrom(String.class)) - { - value = entry.getValue(); - if (AstUtil.isNull(value)) - { - value = null; - } - } - else if (dataType.isAssignableFrom(Map.class)) - { - if (entry.getValue() instanceof List) - { - List list = (List) entry.getValue(); - value = buildMap(list.toArray(new String[list.size()])); - } - else if (entry.getValue() instanceof String) - { - value = buildMap((String) entry.getValue()); - } - else - { - value = null; - } - } - else - { - try - { - Constructor constructor = dataType.getConstructor(new Class[]{String.class}); - value = constructor.newInstance(entry.getValue()); - } - catch (Exception e) - { - logger.error("Unable to convert value '" + entry.getValue() + "' of property '" + entry.getKey() + "' on " - + target.getClass().getName() + " to required type " + dataType, e); - continue; - } - } - - try - { - setter.invoke(target, value); - } - catch (Exception e) - { - logger.error("Unable to set property '" + entry.getKey() + "' to '" + entry.getValue() + "' on " - + target.getClass().getName(), e); - } - } - } - - private Map buildMap(String... lines) - { - if (lines == null) - { - return null; - } - - final Map map = new LinkedHashMap(); - for (String line : lines) - { - final int index = line.indexOf('='); - if (index > 0) - { - final String key = line.substring(0, index); - final String value = line.substring(index + 1, line.length()); - map.put(key, value); - } - else - { - logger.warn("Malformed line '" + line + "' for a map property"); - } - } - return map; - } -} diff --git a/src/main/java/org/asteriskjava/manager/internal/ActionBuilder.java b/src/main/java/org/asteriskjava/manager/internal/ActionBuilder.java index 94f60a2a7..eb7bd69ba 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ActionBuilder.java +++ b/src/main/java/org/asteriskjava/manager/internal/ActionBuilder.java @@ -23,16 +23,15 @@ /** * Transforms ManagerActions to Strings suitable to be sent to Asterisk.

    * The attributes are determined using reflection. - * + * * @author srt * @version $Id$ */ -interface ActionBuilder -{ +interface ActionBuilder { /** * Sets the version of the Asterisk server to built the action for. - * - * @param asteriskVersion the version of the target Asterisk server. + * + * @param targetVersion the version of the target Asterisk server. * @since 0.2 */ void setTargetVersion(AsteriskVersion targetVersion); @@ -42,7 +41,7 @@ interface ActionBuilder * Asterisk actions consist of an unordered set of key value pairs corresponding to the * attributes of the ManagerActions. Key and value are separated by a colon (":"), key value * pairs by a CR/NL ("\r\n"). An action is terminated by an empty line ("\r\n\r\n"). - * + * * @param action the action to transform * @return a String representing the given action in an asterisk compatible format */ @@ -53,8 +52,8 @@ interface ActionBuilder * Asterisk actions consist of an unordered set of key value pairs corresponding to the * attributes of the ManagerActions. Key and value are separated by a colon (":"), key value * pairs by a CR/NL ("\r\n"). An action is terminated by an empty line ("\r\n\r\n"). - * - * @param action the action to transform + * + * @param action the action to transform * @param internalActionId the internal action id to add * @return a String representing the given action in an asterisk compatible format */ diff --git a/src/main/java/org/asteriskjava/manager/internal/ActionBuilderImpl.java b/src/main/java/org/asteriskjava/manager/internal/ActionBuilderImpl.java index 1a6e96fd8..01f440d4c 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ActionBuilderImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ActionBuilderImpl.java @@ -35,8 +35,8 @@ * @author srt * @version $Id$ */ -class ActionBuilderImpl implements ActionBuilder -{ +class ActionBuilderImpl implements ActionBuilder { + private static final String LINE_SEPARATOR = "\r\n"; private static final String ATTRIBUTES_PROPERTY_NAME = "attributes"; @@ -45,189 +45,176 @@ class ActionBuilderImpl implements ActionBuilder */ private final Log logger = LogFactory.getLog(getClass()); private AsteriskVersion targetVersion; + private final Set membersToIgnore = new HashSet<>(); /** * Creates a new ActionBuilder for Asterisk 1.0. */ - ActionBuilderImpl() - { + ActionBuilderImpl() { this.targetVersion = AsteriskVersion.ASTERISK_1_0; + + /* + * When using the Reflection API to get all of the getters for building + * actions to send, we ignore some of the getters + */ + this.membersToIgnore.add("class"); + this.membersToIgnore.add("action"); + this.membersToIgnore.add("actionid"); + this.membersToIgnore.add(ATTRIBUTES_PROPERTY_NAME); } - public void setTargetVersion(AsteriskVersion targetVersion) - { + public void setTargetVersion(AsteriskVersion targetVersion) { this.targetVersion = targetVersion; } - public String buildAction(final ManagerAction action) - { + public String buildAction(final ManagerAction action) { return buildAction(action, null); } @SuppressWarnings("unchecked") - public String buildAction(final ManagerAction action, final String internalActionId) - { - StringBuffer sb = new StringBuffer(); + public String buildAction(final ManagerAction action, final String internalActionId) { + StringBuilder sb = new StringBuilder(); sb.append("action: "); sb.append(action.getAction()); sb.append(LINE_SEPARATOR); - if (internalActionId != null) - { + if (internalActionId != null) { sb.append("actionid: "); sb.append(ManagerUtil.addInternalActionId(action.getActionId(), internalActionId)); sb.append(LINE_SEPARATOR); - } - else if (action.getActionId() != null) - { + } else if (action.getActionId() != null) { sb.append("actionid: "); sb.append(action.getActionId()); sb.append(LINE_SEPARATOR); } - /* - * When using the Reflection API to get all of the getters for building - * actions to send, we ignore some of the getters - */ - Set ignore = new HashSet(); - ignore.add("class"); - ignore.add("action"); - ignore.add("actionid"); - ignore.add(ATTRIBUTES_PROPERTY_NAME); + Map getters; // if this is a user event action, we need to grab the internal event, // otherwise do below as normal - if (action instanceof UserEventAction) - { + if (action instanceof UserEventAction) { UserEvent userEvent = ((UserEventAction) action).getUserEvent(); appendUserEvent(sb, userEvent); + getters = ReflectionUtil.getGetters(userEvent.getClass()); + // eventually we may want to add more Map keys for events to ignore // when appending - appendGetters(sb, userEvent, ignore); - } - else - { - appendGetters(sb, action, ignore); + appendGetters(sb, userEvent, getters); + } else { + getters = ReflectionUtil.getGetters(action.getClass()); + + appendGetters(sb, action, getters); } // actions that have the special getAttributes method will // have their Map appended without a singular key or separator - Map getters = ReflectionUtil.getGetters(action.getClass()); - - if(getters.containsKey(ATTRIBUTES_PROPERTY_NAME)) - { + if (getters.containsKey(ATTRIBUTES_PROPERTY_NAME)) { Method getter = getters.get(ATTRIBUTES_PROPERTY_NAME); Object value = null; - try - { + try { value = getter.invoke(action); - } - catch (Exception ex) - { + } catch (Exception ex) { logger.error("Unable to retrieve property '" + ATTRIBUTES_PROPERTY_NAME + "' of " + action.getClass(), ex); } - - if(value instanceof Map) - { - Map attributes = (Map)value; - for (Map.Entry entry : attributes.entrySet()) - { + + if (value instanceof Map) { + Map attributes = (Map) value; + for (Map.Entry entry : attributes.entrySet()) { appendString(sb, entry.getKey() == null ? "null" : entry.getKey().toString(), entry.getValue() == null ? "null" : entry.getValue().toString()); - } + } } } - + sb.append(LINE_SEPARATOR); return sb.toString(); } - private void appendMap(StringBuffer sb, String key, Map values) - { + private void appendMap(StringBuilder sb, String key, Map values) { String singularKey; // strip plural s (i.e. use "variable: " instead of "variables: " - if (key.endsWith("s")) - { + if (key.endsWith("s")) { singularKey = key.substring(0, key.length() - 1); - } - else - { + } else { singularKey = key; } - if (targetVersion.isAtLeast(AsteriskVersion.ASTERISK_1_2)) - { + if (targetVersion.isAtLeast(AsteriskVersion.ASTERISK_1_2)) { appendMap12(sb, singularKey, values); - } - else - { + } else { appendMap10(sb, singularKey, values); } } - private void appendMap10(StringBuffer sb, String singularKey, Map values) - { + private void appendMap10(StringBuilder sb, String singularKey, Map values) { Iterator> entryIterator; sb.append(singularKey); sb.append(": "); entryIterator = values.entrySet().iterator(); - while (entryIterator.hasNext()) - { + while (entryIterator.hasNext()) { Map.Entry entry; entry = entryIterator.next(); sb.append(entry.getKey()); sb.append("="); - if (entry.getValue() != null) - { + if (entry.getValue() != null) { sb.append(entry.getValue()); } - if (entryIterator.hasNext()) - { + if (entryIterator.hasNext()) { sb.append("|"); } } sb.append(LINE_SEPARATOR); } - private void appendMap12(StringBuffer sb, String singularKey, Map values) - { - for (Map.Entry entry : values.entrySet()) - { + private void appendMap12(StringBuilder sb, String singularKey, Map values) { + for (Map.Entry entry : values.entrySet()) { sb.append(singularKey); sb.append(": "); sb.append(entry.getKey()); sb.append("="); - if (entry.getValue() != null) - { - sb.append(entry.getValue()); + if (entry.getValue() != null) { + if (entry.getKey().equalsIgnoreCase("Content")) { + String sp[] = entry.getValue().split("\n"); + if (sp.length > 0) { + sb.append(sp[0]); + for (int i = 1; i < sp.length; i++) { + sb.append(LINE_SEPARATOR); + sb.append(singularKey); + sb.append(": "); + sb.append(entry.getKey()); + sb.append("="); + sb.append(sp[i]); + } + } + + } else { + sb.append(entry.getValue()); + } } sb.append(LINE_SEPARATOR); } } - private void appendString(StringBuffer sb, String key, String value) - { + private void appendString(StringBuilder sb, String key, String value) { sb.append(key); sb.append(": "); sb.append(value); sb.append(LINE_SEPARATOR); } - private void appendUserEvent(StringBuffer sb, UserEvent event) - { + private void appendUserEvent(StringBuilder sb, UserEvent event) { Class clazz = event.getClass(); String className = clazz.getName(); String eventType = className.substring(className.lastIndexOf('.') + 1).toLowerCase(Locale.ENGLISH); - if (eventType.endsWith("event")) - { + if (eventType.endsWith("event")) { eventType = eventType.substring(0, eventType.length() - "event".length()); } @@ -235,129 +222,98 @@ private void appendUserEvent(StringBuffer sb, UserEvent event) } @SuppressWarnings("unchecked") - private void appendGetters(StringBuffer sb, Object action, Set membersToIgnore) - { - Map getters = ReflectionUtil.getGetters(action.getClass()); - for (Map.Entry entry : getters.entrySet()) - { + private void appendGetters(StringBuilder sb, Object action, Map getters) { + for (Map.Entry entry : getters.entrySet()) { final String name = entry.getKey(); final Method getter = entry.getValue(); final Object value; - if (membersToIgnore.contains(name)) - { + if (membersToIgnore.contains(name)) { continue; } - try - { + try { value = getter.invoke(action); - } - catch (Exception ex) - { + } catch (Exception ex) { logger.error("Unable to retrieve property '" + name + "' of " + action.getClass(), ex); continue; } - if (value == null || value instanceof Class) - { + if (value == null || value instanceof Class) { continue; } final String mappedName = mapToAsterisk(getter); - if (value instanceof Map) - { + if (value instanceof Map) { appendMap(sb, mappedName, (Map) value); - } - else if (value instanceof String) - { + } else if (value instanceof String) { appendString(sb, mappedName, (String) value); - } - else - { + } else { appendString(sb, mappedName, value.toString()); } } } - private String mapToAsterisk(Method getter) - { + private static String mapToAsterisk(Method getter) { AsteriskMapping annotation; // check annotation of getter method - annotation = getter.getAnnotation(AsteriskMapping.class); - if (annotation != null) - { + annotation + = getter.getAnnotation(AsteriskMapping.class + ); + if (annotation != null) { return annotation.value(); } // check annotation of setter method String setterName = determineSetterName(getter.getName()); - try - { + try { Method setter = getter.getDeclaringClass().getDeclaredMethod(setterName, getter.getReturnType()); - annotation = setter.getAnnotation(AsteriskMapping.class); - if (annotation != null) - { + annotation + = setter.getAnnotation(AsteriskMapping.class + ); + if (annotation != null) { return annotation.value(); } - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { // ok, no setter method } // check annotation of field String fieldName = determineFieldName(getter.getName()); - try - { + try { Field field = getter.getDeclaringClass().getDeclaredField(fieldName); - annotation = field.getAnnotation(AsteriskMapping.class); - if (annotation != null) - { + annotation + = field.getAnnotation(AsteriskMapping.class + ); + if (annotation != null) { return annotation.value(); } - } - catch (NoSuchFieldException e) - { + } catch (NoSuchFieldException e) { // ok, no field } - return fieldName.toLowerCase(Locale.US); + return fieldName.toLowerCase(Locale.ENGLISH); } - String determineSetterName(String getterName) - { - if (getterName.startsWith("get")) - { + static String determineSetterName(String getterName) { + if (getterName.startsWith("get")) { return "set" + getterName.substring(3); - } - else if (getterName.startsWith("is")) - { + } else if (getterName.startsWith("is")) { return "set" + getterName.substring(2); - } - else - { + } else { throw new IllegalArgumentException("Getter '" + getterName + "' doesn't start with either 'get' or 'is'"); } } - String determineFieldName(String accessorName) - { - if (accessorName.startsWith("get")) - { + static String determineFieldName(String accessorName) { + if (accessorName.startsWith("get")) { return lcFirst(accessorName.substring(3)); - } - else if (accessorName.startsWith("is")) - { + } else if (accessorName.startsWith("is")) { return lcFirst(accessorName.substring(2)); - } - else if (accessorName.startsWith("set")) - { + } else if (accessorName.startsWith("set")) { return lcFirst(accessorName.substring(3)); - } - else - { + } else { throw new IllegalArgumentException("Accessor '" + accessorName + "' doesn't start with either 'get', 'is' or 'set'"); } } @@ -368,14 +324,12 @@ else if (accessorName.startsWith("set")) * @param s the string to convert. * @return the converted string. */ - String lcFirst(String s) - { - if (s == null || s.length() < 1) - { + private static String lcFirst(String s) { + if (s == null || s.isEmpty()) { return s; } - char first = s.charAt(0); - return Character.toLowerCase(first) + s.substring(1); + return Character.toLowerCase(s.charAt(0)) + + (s.length() == 1 ? "" : s.substring(1)); } } diff --git a/src/main/java/org/asteriskjava/manager/internal/AsyncEventPump.java b/src/main/java/org/asteriskjava/manager/internal/AsyncEventPump.java new file mode 100644 index 000000000..d17b6ae4c --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/internal/AsyncEventPump.java @@ -0,0 +1,193 @@ +package org.asteriskjava.manager.internal; + +import com.google.common.util.concurrent.RateLimiter; +import org.asteriskjava.lock.Locker; +import org.asteriskjava.manager.event.ManagerEvent; +import org.asteriskjava.manager.response.ManagerResponse; +import org.asteriskjava.pbx.util.LogTime; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.lang.ref.WeakReference; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * AsyncEventPump delivers events and responses to a Dispatcher without blocking + * the thread which is producing the events and responses. AsyncEventPump also + * adds logging around timely handling of events + * + * @author rsutton + */ +public class AsyncEventPump implements Dispatcher, Runnable { + private final Log logger = LogFactory.getLog(AsyncEventPump.class); + + private static final long MAX_SAFE_EVENT_AGE = 500; + + private final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(20000); + private final Dispatcher dispatcher; + private volatile boolean stop = false; + private final WeakReference owner; + + private final Thread thread; + private volatile boolean terminated = false; + + private final String name; + + /** + * @param owner: A weak reference to the owner is created, should it be + * garbage collected then AsyncEventPump will shutdown. + * @param dispatcher: The dispatcher that AsyncEventPump should deliver + * events to. + * @param threadName: The AsyncEventPump's thread will be named with a + * variant of threadName + */ + AsyncEventPump(Object owner, Dispatcher dispatcher, String threadName) { + this.dispatcher = dispatcher; + this.owner = new WeakReference<>(owner); + name = threadName + ":AsyncEventPump"; + thread = new Thread(this, name); + thread.start(); + } + + @Override + public void run() { + try { + logger.info("starting"); + RateLimiter rateLimiter = RateLimiter.create(2); + while (!stop || !queue.isEmpty()) { + try { + EventWrapper wrapper = queue.poll(1, TimeUnit.MINUTES); + if (wrapper != null) { + if (wrapper.timer.timeTaken() > MAX_SAFE_EVENT_AGE && rateLimiter.tryAcquire()) { + logger.warn("The following message will only appear once per second!\n" + "Event dispatched " + + wrapper.timer.timeTaken() + + " MS after arriving, your ManagerEvent handlers are too slow!\n" + + "You should also check for Garbage Collection issues.\n" + "There are " + queue.size() + + " events waiting to be processed in the queue.\n" + "Event was " + + wrapper.getPayloadAsString()); + + } + // assume we need to process all queued events in + // MAX_SAFE_EVENT_AGE + int requiredHandlingTime = (int) (MAX_SAFE_EVENT_AGE / Math.max(1, queue.size())); + + if (wrapper.response != null) { + dispatcher.dispatchResponse(wrapper.response, requiredHandlingTime); + } else if (wrapper.event != null) { + dispatcher.dispatchEvent(wrapper.event, requiredHandlingTime); + } else if (wrapper.poison != null) { + wrapper.poison.countDown(); + } + } else if (owner.get() == null) { + stop = true; + logger.error("The owner has been garbage collected!"); + } + + } catch (InterruptedException e) { + logger.error(e); + } catch (Exception e) { + logger.error(e, e); + } + } + } finally { + terminated = true; + logger.warn("AsyncEventPump has exited"); + } + + } + + /** + * call stop() to cause the AsyncEventPump to stop, it will first empty the + * queue. + */ + public void stop() { + logger.info(name + " Requesting AsyncEventPump to stop"); + if (terminated) { + logger.warn(name + " AsyncEventPump is already stopped"); + if (!queue.isEmpty()) { + logger.error(name + " There are unprocessed events in the queue"); + } + + return; + } + EventWrapper poisonWrapper = new EventWrapper(); + queue.add(poisonWrapper); + stop = true; + LogTime timer = new LogTime(); + try { + int queueSize = queue.size(); + while (!poisonWrapper.poison.await(5, TimeUnit.SECONDS)) { + // still waiting for the poison to be consumed. + if (queueSize == queue.size()) { + if (!terminated) { + Locker.dumpThread(thread, name + " AsyncEventPump thread is blocked here..."); + } + throw new RuntimeException(name + " Failed to shutdown AsyncEventPump cleanly!"); + + } + queueSize = queue.size(); + logger.info(name + " Waiting for AsyncEventPump to Stop... "); + + if (timer.timeTaken() > 60_000) { + throw new RuntimeException(name + " Failed to shutdown AsyncEventPump cleanly!"); + } + } + } catch (InterruptedException e1) { + logger.error(name + e1.getMessage()); + } + } + + /** + * add a ManagerResponse to the queue, only if the queue is not full + */ + @Override + public void dispatchResponse(ManagerResponse response, Integer requiredHandlingTime) { + if (!queue.offer(new EventWrapper(response))) { + logger.error(name + " Event queue is full, not processing ManagerResponse " + response); + } + } + + /** + * add a ManagerEvent to the queue, only if the queue is not full + */ + @Override + public void dispatchEvent(ManagerEvent event, Integer requiredHandlingTime) { + if (!queue.offer(new EventWrapper(event))) { + logger.error(name + " Event queue is full, not processing ManagerEvent " + event); + } + } + + private static class EventWrapper { + LogTime timer = new LogTime(); + ManagerResponse response; + ManagerEvent event; + CountDownLatch poison; + + EventWrapper() { + // poison + poison = new CountDownLatch(1); + } + + public String getPayloadAsString() { + if (response != null) { + return response.toString(); + } else if (event != null) { + return event.toString(); + } + return "Poison"; + + } + + EventWrapper(ManagerResponse response) { + this.response = response; + } + + EventWrapper(ManagerEvent event) { + this.event = event; + } + + } + +} diff --git a/src/main/java/org/asteriskjava/manager/internal/Dispatcher.java b/src/main/java/org/asteriskjava/manager/internal/Dispatcher.java index 89891efc5..95f36efe0 100644 --- a/src/main/java/org/asteriskjava/manager/internal/Dispatcher.java +++ b/src/main/java/org/asteriskjava/manager/internal/Dispatcher.java @@ -19,34 +19,39 @@ import org.asteriskjava.manager.event.ManagerEvent; import org.asteriskjava.manager.response.ManagerResponse; - /** * The Dispatcher defines the interface used for communication between - * ManagerConnection and ManagerReader.

    + * ManagerConnection and ManagerReader. + *

    * Do not use this interface in your code, it is intended to be used only by the * DefaultManagerConnection and its ManagerReader. - * + * * @author srt * @version $Id$ */ -interface Dispatcher -{ +interface Dispatcher { /** * This method is called by the reader whenever a {@link ManagerResponse} is * received. The response is dispatched to the associated * {@link org.asteriskjava.manager.SendActionCallback}. - * - * @param response the resonse received by the reader + * + * @param response the response received by the reader + * @param requiredHandlingTime the time that this event must be handled + * within to not cause a back log of events * @see ManagerReader */ - void dispatchResponse(ManagerResponse response); + void dispatchResponse(ManagerResponse response, Integer requiredHandlingTime); /** * This method is called by the reader whenever a ManagerEvent is received. * The event is dispatched to all registered ManagerEventHandlers. - * - * @param event the event received by the reader + * + * @param event the event received by the reader + * @param requiredHandlingTime the time that this event must be handled + * within to not cause a back log of events * @see ManagerReader */ - void dispatchEvent(ManagerEvent event); + void dispatchEvent(ManagerEvent event, Integer requiredHandlingTime); + + void stop(); } diff --git a/src/main/java/org/asteriskjava/manager/internal/EventBuilder.java b/src/main/java/org/asteriskjava/manager/internal/EventBuilder.java index 5db83f9c9..2224dfd2f 100644 --- a/src/main/java/org/asteriskjava/manager/internal/EventBuilder.java +++ b/src/main/java/org/asteriskjava/manager/internal/EventBuilder.java @@ -16,20 +16,18 @@ */ package org.asteriskjava.manager.internal; -import java.util.Map; - import org.asteriskjava.manager.event.ManagerEvent; +import java.util.Map; /** * Transforms maps of attributes to instances of ManagerEvent. - * - * @see org.asteriskjava.manager.event.ManagerEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.ManagerEvent */ -interface EventBuilder -{ +interface EventBuilder { /** * Registers a new event class. The event this class is registered for is * simply derived from the name of the class by stripping any package name @@ -37,10 +35,11 @@ interface EventBuilder * org.asteriskjava.manager.event.JoinEvent is registered for * the event "Join". *

    - * The event class must be a concrete class with a default constructor - * (one that takes no arguments). - * - * @param clazz the event class to register, must extend {@link ManagerEvent}. + * The event class must be a concrete class with a default constructor (one + * that takes no arguments). + * + * @param clazz the event class to register, must extend + * {@link ManagerEvent}. * @throws IllegalArgumentException if clazz is not a valid event class */ void registerEventClass(Class clazz) throws IllegalArgumentException; @@ -48,11 +47,13 @@ interface EventBuilder /** * Builds the event based on the given map of attributes and the registered * event classes. - * - * @param source source attribute for the event + * + * @param source source attribute for the event * @param attributes map containing event attributes * @return a concrete instance of ManagerEvent or null if no - * event class was registered for the event type. + * event class was registered for the event type. */ ManagerEvent buildEvent(Object source, Map attributes); + + void deregisterEventClass(Class eventClass); } diff --git a/src/main/java/org/asteriskjava/manager/internal/EventBuilderImpl.java b/src/main/java/org/asteriskjava/manager/internal/EventBuilderImpl.java index 1320effc7..d007e63e8 100644 --- a/src/main/java/org/asteriskjava/manager/internal/EventBuilderImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/EventBuilderImpl.java @@ -1,26 +1,31 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.manager.internal; +import org.asteriskjava.manager.AsteriskMapping; import org.asteriskjava.manager.event.*; +import org.asteriskjava.manager.util.EventAttributesHelper; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; +import org.reflections.Reflections; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.*; +import java.util.Map.Entry; /** * Default implementation of the EventBuilder interface. @@ -29,162 +34,48 @@ * @version $Id$ * @see org.asteriskjava.manager.event.ManagerEvent */ -class EventBuilderImpl extends AbstractBuilder implements EventBuilder -{ - private static final Set ignoredAttributes = new HashSet(Arrays.asList("event")); +class EventBuilderImpl implements EventBuilder { + private static final Set ignoredAttributes = new HashSet<>(Arrays.asList("event")); private Map> registeredEventClasses; + private final Set eventClassNegativeCache = new HashSet<>(); + + private static final Log logger = LogFactory.getLog(EventBuilderImpl.class); + + private final static Set> knownManagerEventClasses = new Reflections( + "org.asteriskjava.manager.event").getSubTypesOf(ManagerEvent.class); - EventBuilderImpl() - { - this.registeredEventClasses = new HashMap>(); + EventBuilderImpl() { + this.registeredEventClasses = new HashMap<>(); registerBuiltinEventClasses(); } - @SuppressWarnings({"deprecation"}) - private void registerBuiltinEventClasses() - { - // please add new event classes alphabetically - registerEventClass(AgentCallbackLoginEvent.class); - registerEventClass(AgentCallbackLogoffEvent.class); - registerEventClass(AgentCalledEvent.class); - registerEventClass(AgentConnectEvent.class); - registerEventClass(AgentCompleteEvent.class); - registerEventClass(AgentDumpEvent.class); - registerEventClass(AgentLoginEvent.class); - registerEventClass(AgentLogoffEvent.class); - registerEventClass(AgentRingNoAnswerEvent.class); - registerEventClass(AgentsEvent.class); - registerEventClass(AgentsCompleteEvent.class); - registerEventClass(AgiExecEvent.class); - registerEventClass(AsyncAgiEvent.class); - registerEventClass(AlarmEvent.class); - registerEventClass(AlarmClearEvent.class); - registerEventClass(BridgeEvent.class); - registerEventClass(BridgeExecEvent.class); - registerEventClass(CdrEvent.class); - registerEventClass(ChannelReloadEvent.class); - registerEventClass(ChannelUpdateEvent.class); - registerEventClass(ConfbridgeEndEvent.class); - registerEventClass(ConfbridgeJoinEvent.class); - registerEventClass(ConfbridgeLeaveEvent.class); - registerEventClass(ConfbridgeListEvent.class); - registerEventClass(ConfbridgeListCompleteEvent.class); - registerEventClass(ConfbridgeListRoomsEvent.class); - registerEventClass(ConfbridgeListRoomsCompleteEvent.class); - registerEventClass(ConfbridgeStartEvent.class); - registerEventClass(ConfbridgeTalkingEvent.class); - registerEventClass(CoreShowChannelEvent.class); - registerEventClass(CoreShowChannelsCompleteEvent.class); - registerEventClass(DbGetResponseEvent.class); - registerEventClass(DialEvent.class); - registerEventClass(DndStateEvent.class); - registerEventClass(DtmfEvent.class); - registerEventClass(ExtensionStatusEvent.class); - registerEventClass(FaxDocumentStatusEvent.class); - registerEventClass(FaxReceivedEvent.class); - registerEventClass(FaxStatusEvent.class); - registerEventClass(FullyBootedEvent.class); - registerEventClass(HangupEvent.class); - registerEventClass(HoldedCallEvent.class); - registerEventClass(HoldEvent.class); - registerEventClass(JabberEventEvent.class); - registerEventClass(JitterBufStatsEvent.class); - registerEventClass(JoinEvent.class); - registerEventClass(LeaveEvent.class); - registerEventClass(LinkEvent.class); - registerEventClass(ListDialplanEvent.class); - registerEventClass(LogChannelEvent.class); - registerEventClass(MasqueradeEvent.class); - registerEventClass(MeetMeEndEvent.class); - registerEventClass(MeetMeJoinEvent.class); - registerEventClass(MeetMeLeaveEvent.class); - registerEventClass(MeetMeMuteEvent.class); - registerEventClass(MeetMeTalkingEvent.class); - registerEventClass(MeetMeTalkingRequestEvent.class); - registerEventClass(MeetMeStopTalkingEvent.class); - registerEventClass(MessageWaitingEvent.class); - registerEventClass(ModuleLoadReportEvent.class); - registerEventClass(MonitorStartEvent.class); - registerEventClass(MonitorStopEvent.class); - registerEventClass(MusicOnHoldEvent.class); - registerEventClass(NewAccountCodeEvent.class); - registerEventClass(NewCallerIdEvent.class); - registerEventClass(NewChannelEvent.class); - registerEventClass(NewExtenEvent.class); - registerEventClass(NewStateEvent.class); - registerEventClass(OriginateFailureEvent.class); - registerEventClass(OriginateSuccessEvent.class); - registerEventClass(OriginateResponseEvent.class); - registerEventClass(ParkedCallGiveUpEvent.class); - registerEventClass(ParkedCallEvent.class); - registerEventClass(ParkedCallTimeOutEvent.class); - registerEventClass(ParkedCallsCompleteEvent.class); - registerEventClass(PeerEntryEvent.class); - registerEventClass(PeerlistCompleteEvent.class); - registerEventClass(PeerStatusEvent.class); - registerEventClass(PriEventEvent.class); - registerEventClass(QueueCallerAbandonEvent.class); - registerEventClass(QueueEntryEvent.class); - registerEventClass(QueueMemberAddedEvent.class); - registerEventClass(QueueMemberEvent.class); - registerEventClass(QueueMemberPausedEvent.class); - registerEventClass(QueueMemberPenaltyEvent.class); - registerEventClass(QueueMemberRemovedEvent.class); - registerEventClass(QueueMemberStatusEvent.class); - registerEventClass(QueueParamsEvent.class); - registerEventClass(QueueStatusCompleteEvent.class); - registerEventClass(QueueSummaryCompleteEvent.class); - registerEventClass(QueueSummaryEvent.class); - registerEventClass(ReceiveFaxEvent.class); - registerEventClass(RegistrationsCompleteEvent.class); - registerEventClass(RegistryEntryEvent.class); - registerEventClass(RegistryEvent.class); - registerEventClass(ReloadEvent.class); - registerEventClass(RenameEvent.class); - registerEventClass(RtcpReceivedEvent.class); - registerEventClass(RtcpSentEvent.class); - registerEventClass(RtpReceiverStatEvent.class); - registerEventClass(RtpSenderStatEvent.class); - registerEventClass(SendFaxStatusEvent.class); - registerEventClass(SendFaxEvent.class); - registerEventClass(SkypeAccountStatusEvent.class); - registerEventClass(SkypeBuddyEntryEvent.class); - registerEventClass(SkypeBuddyListCompleteEvent.class); - registerEventClass(SkypeBuddyStatusEvent.class); - registerEventClass(SkypeChatMessageEvent.class); - registerEventClass(SkypeLicenseEvent.class); - registerEventClass(SkypeLicenseListCompleteEvent.class); - registerEventClass(ShowDialplanCompleteEvent.class); - registerEventClass(ShutdownEvent.class); - registerEventClass(StatusEvent.class); - registerEventClass(StatusCompleteEvent.class); - registerEventClass(T38FaxStatusEvent.class); - registerEventClass(TransferEvent.class); - registerEventClass(UnholdEvent.class); - registerEventClass(UnlinkEvent.class); - registerEventClass(UnparkedCallEvent.class); - registerEventClass(VarSetEvent.class); - registerEventClass(VoicemailUserEntryCompleteEvent.class); - registerEventClass(VoicemailUserEntryEvent.class); - registerEventClass(ZapShowChannelsEvent.class); - registerEventClass(ZapShowChannelsCompleteEvent.class); + /** + * register the known ManagerEventClasses for this builder + */ + private void registerBuiltinEventClasses() { + for (Class managerEventClass : knownManagerEventClasses) { + if (!Modifier.isAbstract(managerEventClass.getModifiers())) { + registerEventClass(managerEventClass); + } + } } - public final void registerEventClass(Class clazz) throws IllegalArgumentException - { - String className; + public final void registerEventClass(Class clazz) throws IllegalArgumentException { String eventType; - className = clazz.getName(); - eventType = className.substring(className.lastIndexOf('.') + 1).toLowerCase(Locale.ENGLISH); + AsteriskMapping annotation = clazz.getAnnotation(AsteriskMapping.class); + if (annotation == null) { + String className = clazz.getName(); + eventType = className.substring(className.lastIndexOf('.') + 1).toLowerCase(Locale.ENGLISH); - if (eventType.endsWith("event")) - { - eventType = eventType.substring(0, eventType.length() - "event".length()); + if (eventType.endsWith("event")) { + eventType = eventType.substring(0, eventType.length() - "event".length()); + } + } else { + eventType = annotation.value().toLowerCase(Locale.ENGLISH); } - if (UserEvent.class.isAssignableFrom(clazz) && !eventType.startsWith("userevent")) - { + if (UserEvent.class.isAssignableFrom(clazz) && !eventType.startsWith("userevent")) { eventType = "userevent" + eventType; } @@ -200,122 +91,157 @@ public final void registerEventClass(Class clazz) throws * {@link ManagerEvent}. * @throws IllegalArgumentException if clazz is not a valid event class. */ - public final void registerEventClass(String eventType, Class clazz) throws IllegalArgumentException - { + public final void registerEventClass(String eventType, Class clazz) + throws IllegalArgumentException { Constructor defaultConstructor; - if (!ManagerEvent.class.isAssignableFrom(clazz)) - { - throw new IllegalArgumentException(clazz + " is not a ManagerEvent"); + if (Modifier.isAbstract(clazz.getModifiers())) { + throw new IllegalArgumentException(clazz + " is abstract"); } - - if ((clazz.getModifiers() & Modifier.ABSTRACT) != 0) - { + if (clazz.isInterface()) { throw new IllegalArgumentException(clazz + " is abstract"); } - try - { - defaultConstructor = clazz.getConstructor(new Class[]{Object.class}); - } - catch (NoSuchMethodException ex) - { - throw new IllegalArgumentException(clazz + " has no usable constructor"); - } + try { + defaultConstructor = clazz.getConstructor(Object.class); - if ((defaultConstructor.getModifiers() & Modifier.PUBLIC) == 0) - { - throw new IllegalArgumentException(clazz + " has no public default constructor"); + if (!Modifier.isPublic(defaultConstructor.getModifiers())) { + throw new IllegalArgumentException(clazz + " has no public default constructor"); + } + } catch (NoSuchMethodException ex) { + throw new IllegalArgumentException(clazz + " has no usable constructor"); } - registeredEventClasses.put(eventType.toLowerCase(Locale.US), clazz); + registeredEventClasses.put(eventType.toLowerCase(Locale.ENGLISH), clazz); logger.debug("Registered event type '" + eventType + "' (" + clazz + ")"); } - public ManagerEvent buildEvent(Object source, Map attributes) - { + @SuppressWarnings("unchecked") + public ManagerEvent buildEvent(Object source, Map attributes) { ManagerEvent event; - String eventType; + String eventType = null; Class eventClass; Constructor constructor; - if (attributes.get("event") == null) - { + if (attributes.get("event") == null) { logger.error("No event type in properties"); return null; } - if (!(attributes.get("event") instanceof String)) - { - logger.error("Event type is not a String"); - return null; - } - - eventType = ((String) attributes.get("event")).toLowerCase(Locale.US); - // Change in Asterisk 1.4 where the name of the UserEvent is sent as property instead - // of the event name (AJ-48) - if ("userevent".equals(eventType)) - { - String userEventType; - - if (attributes.get("userevent") == null) - { - logger.error("No user event type in properties"); - return null; + if (attributes.get("event") instanceof List) { + List eventNames = (List) attributes.get("event"); + if (!eventNames.isEmpty() && "PeerEntry".equals(eventNames.get(0))) { + // List of PeerEntry events was received (AJ-329) + // Convert map of lists to list of maps - one map for each + // PeerEntry event + int peersAmount = attributes.get("listitems") != null + ? Integer.parseInt((String) attributes.get("listitems")) + : eventNames.size() - 1; // Last event is + // PeerlistComplete + List> peersAttributes = new ArrayList<>(); + for (Map.Entry attribute : attributes.entrySet()) { + String key = attribute.getKey(); + Object value = attribute.getValue(); + for (int i = 0; i < peersAmount; i++) { + Map peerAttrs; + if (peersAttributes.size() > i) { + peerAttrs = peersAttributes.get(i); + } else { + peerAttrs = new HashMap<>(); + peersAttributes.add(i, peerAttrs); + } + if (value instanceof List) { + peerAttrs.put(key, ((List) value).get(i)); + } else if (value instanceof String && !"listitems".equals(key)) { + peerAttrs.put(key, value); + } + } + } + attributes.put("peersAttributes", peersAttributes); + eventType = "peers"; } - if (!(attributes.get("userevent") instanceof String)) - { - logger.error("User event type is not a String"); + } else { + if (!(attributes.get("event") instanceof String)) { + logger.error("Event type is not a String or List"); return null; } - userEventType = ((String) attributes.get("userevent")).toLowerCase(Locale.US); - eventType = eventType + userEventType; + eventType = ((String) attributes.get("event")).toLowerCase(Locale.ENGLISH); + + // Change in Asterisk 1.4 where the name of the UserEvent is sent as + // property instead + // of the event name (AJ-48) + if ("userevent".equals(eventType)) { + String userEventType; + + if (attributes.get("userevent") == null) { + logger.error("No user event type in properties"); + return null; + } + if (!(attributes.get("userevent") instanceof String)) { + logger.error("User event type is not a String"); + return null; + } + + userEventType = ((String) attributes.get("userevent")).toLowerCase(Locale.ENGLISH); + eventType = eventType + userEventType; + } } eventClass = registeredEventClasses.get(eventType); - if (eventClass == null) - { - logger.info("No event class registered for event type '" + eventType + "', attributes: " + attributes - + ". Please report at http://jira.reucon.org/browse/AJ"); + if (eventClass == null) { + if (eventClassNegativeCache.add(eventType)) { + logger.info("No event class registered for event type '" + eventType + "', attributes: " + attributes + + ". Please report at https://github.com/asterisk-java/asterisk-java/issues"); + } return null; } - try - { - constructor = eventClass.getConstructor(new Class[]{Object.class}); - } - catch (NoSuchMethodException ex) - { + try { + constructor = eventClass.getConstructor(Object.class); + } catch (NoSuchMethodException ex) { logger.error("Unable to get constructor of " + eventClass.getName(), ex); return null; } - try - { + try { event = (ManagerEvent) constructor.newInstance(source); - } - catch (Exception ex) - { + } catch (Exception ex) { logger.error("Unable to create new instance of " + eventClass.getName(), ex); return null; } - setAttributes(event, attributes, ignoredAttributes); + if (attributes.get("peersAttributes") != null && attributes.get("peersAttributes") instanceof List) { + // Fill Peers event with list of PeerEntry events (AJ-329) + PeersEvent peersEvent = (PeersEvent) event; + // TODO: This cast is very ugly, we should review how attributes are + // being passed around. + for (Map peerAttrs : (List>) attributes.get("peersAttributes")) { + PeerEntryEvent peerEntryEvent = new PeerEntryEvent(source); + EventAttributesHelper.setAttributes(peerEntryEvent, peerAttrs, ignoredAttributes); + List peerEntryEvents = peersEvent.getChildEvents(); + if (peerEntryEvents == null) { + peerEntryEvents = new ArrayList<>(); + peersEvent.setChildEvents(peerEntryEvents); + } + peerEntryEvents.add(peerEntryEvent); + } + peersEvent.setActionId(peersEvent.getChildEvents().get(0).getActionId()); + } else { + EventAttributesHelper.setAttributes(event, attributes, ignoredAttributes); + } // ResponseEvents are sent in response to a ManagerAction if the // response contains lots of data. They include the actionId of // the corresponding ManagerAction. - if (event instanceof ResponseEvent) - { + if (event instanceof ResponseEvent) { ResponseEvent responseEvent; String actionId; responseEvent = (ResponseEvent) event; actionId = responseEvent.getActionId(); - if (actionId != null) - { + if (actionId != null) { responseEvent.setActionId(ManagerUtil.stripInternalActionId(actionId)); responseEvent.setInternalActionId(ManagerUtil.getInternalActionId(actionId)); } @@ -323,4 +249,24 @@ public ManagerEvent buildEvent(Object source, Map attributes) return event; } + + @Override + public void deregisterEventClass(Class eventClass) { + + Set toRemove = new HashSet<>(); + for (Entry> registered : registeredEventClasses.entrySet()) { + if (registered.getValue().equals(eventClass)) { + toRemove.add(registered.getKey()); + } + } + if (toRemove.isEmpty()) { + logger.warn("Couldn't remove event type " + eventClass); + } else { + for (String key : toRemove) { + registeredEventClasses.remove(key); + logger.warn("Removed event type " + key); + } + } + + } } diff --git a/src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java b/src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java index f2dac8155..9feeac04b 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java @@ -1,89 +1,96 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.manager.internal; -import static org.asteriskjava.manager.ManagerConnectionState.CONNECTED; -import static org.asteriskjava.manager.ManagerConnectionState.CONNECTING; -import static org.asteriskjava.manager.ManagerConnectionState.DISCONNECTED; -import static org.asteriskjava.manager.ManagerConnectionState.DISCONNECTING; -import static org.asteriskjava.manager.ManagerConnectionState.INITIAL; -import static org.asteriskjava.manager.ManagerConnectionState.RECONNECTING; +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.lock.Lockable; +import org.asteriskjava.lock.LockableList; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.manager.*; +import org.asteriskjava.manager.action.*; +import org.asteriskjava.manager.event.*; +import org.asteriskjava.manager.response.*; +import org.asteriskjava.pbx.util.LogTime; +import org.asteriskjava.util.DateUtil; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; +import org.asteriskjava.util.SocketConnectionFacade; +import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; import java.io.IOException; import java.io.Serializable; -import java.net.Socket; import java.net.InetAddress; +import java.net.Socket; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.asteriskjava.AsteriskVersion; -import org.asteriskjava.manager.*; -import org.asteriskjava.manager.action.ChallengeAction; -import org.asteriskjava.manager.action.CommandAction; -import org.asteriskjava.manager.action.EventGeneratingAction; -import org.asteriskjava.manager.action.LoginAction; -import org.asteriskjava.manager.action.LogoffAction; -import org.asteriskjava.manager.action.ManagerAction; -import org.asteriskjava.manager.event.ConnectEvent; -import org.asteriskjava.manager.event.DisconnectEvent; -import org.asteriskjava.manager.event.ManagerEvent; -import org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent; -import org.asteriskjava.manager.event.ResponseEvent; -import org.asteriskjava.manager.response.ChallengeResponse; -import org.asteriskjava.manager.response.CommandResponse; -import org.asteriskjava.manager.response.ManagerError; -import org.asteriskjava.manager.response.ManagerResponse; -import org.asteriskjava.util.DateUtil; -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; -import org.asteriskjava.util.SocketConnectionFacade; -import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; -import org.asteriskjava.manager.action.UserEventAction; +import static org.asteriskjava.manager.ManagerConnectionState.*; /** - * Internal implemention of the ManagerConnection interface. + * Internal implementation of the ManagerConnection interface. * * @author srt * @version $Id$ * @see org.asteriskjava.manager.ManagerConnectionFactory */ -public class ManagerConnectionImpl implements ManagerConnection, Dispatcher -{ +public class ManagerConnectionImpl extends Lockable implements ManagerConnection, Dispatcher { private static final int RECONNECTION_INTERVAL_1 = 50; private static final int RECONNECTION_INTERVAL_2 = 5000; private static final String DEFAULT_HOSTNAME = "localhost"; private static final int DEFAULT_PORT = 5038; private static final int RECONNECTION_VERSION_INTERVAL = 500; private static final int MAX_VERSION_ATTEMPTS = 4; - private static final Pattern SHOW_VERSION_PATTERN = Pattern.compile("^(core )?show version.*"); + private static final String CMD_SHOW_VERSION = "core show version"; + + // NOTE: identifier is AMI_VERSION, defined in include/asterisk/manager.h + // AMI version consists of MAJOR.BREAKING.NON-BREAKING. + private static final String[] SUPPORTED_AMI_VERSIONS = { + "2.6", // Asterisk 13 + "2.7", // Asterisk 13.2 + "2.8", // Asterisk >13.5 + "2.9", // Asterisk >13.3 + "3.1", // Asterisk =14.3 + "3.2", // Asterisk 14.4.0 + "4.0", // Asterisk 15 + "5.0", // Asterisk 16 + "6.0", // Asterisk 17 + "7.0", // Asterisk 18 + "8.0", // Asterisk 19 + "9.0", // Asterisk 20 + "10.0", // Asterisk 21 + "11.0", // Asterisk 22 + "12.0", // Asterisk 23 + "13.0", // Asterisk Dev + }; private static final AtomicLong idCounter = new AtomicLong(0); /** * Instance logger. */ - private final Log logger = LogFactory.getLog(getClass()); + private final static Log logger = LogFactory.getLog(ManagerConnectionImpl.class); private final long id; @@ -104,8 +111,8 @@ public class ManagerConnectionImpl implements ManagerConnection, Dispatcher private int port = DEFAULT_PORT; /** - * true to use SSL for the connection, false - * for a plain text connection. + * true to use SSL for the connection, false for a + * plain text connection. */ private boolean ssl = false; @@ -121,6 +128,11 @@ public class ManagerConnectionImpl implements ManagerConnection, Dispatcher */ protected String password; + /** + * Encoding used for transmission of strings. + */ + private Charset encoding = StandardCharsets.UTF_8; + /** * The default timeout to wait for a ManagerResponse after sending a * ManagerAction. @@ -139,15 +151,17 @@ public class ManagerConnectionImpl implements ManagerConnection, Dispatcher private int socketTimeout = 0; /** - * Closes the connection (and reconnects) if no input has been read for the given amount - * of milliseconds. A timeout of zero is interpreted as an infinite timeout. + * Closes the connection (and reconnects) if no input has been read for the + * given amount of milliseconds. A timeout of zero is interpreted as an + * infinite timeout. * * @see Socket#setSoTimeout(int) */ private int socketReadTimeout = 0; /** - * true to continue to reconnect after an authentication failure. + * true to continue to reconnect after an authentication + * failure. */ private boolean keepAliveAfterAuthenticationFailure = true; @@ -191,7 +205,7 @@ public class ManagerConnectionImpl implements ManagerConnection, Dispatcher * Key is the internalActionId of the Action sent and value the * corresponding ResponseListener. */ - private final Map responseListeners; + private final LockableMap responseListeners; /** * Contains the event handlers that handle ResponseEvents for the @@ -200,12 +214,12 @@ public class ManagerConnectionImpl implements ManagerConnection, Dispatcher * Key is the internalActionId of the Action sent and value the * corresponding EventHandler. */ - private final Map responseEventListeners; + private final LockableMap responseEventListeners; /** * Contains the event handlers that users registered. */ - private final List eventListeners; + private final LockableList eventListeners; protected ManagerConnectionState state = INITIAL; @@ -214,24 +228,21 @@ public class ManagerConnectionImpl implements ManagerConnection, Dispatcher /** * Creates a new instance. */ - public ManagerConnectionImpl() - { + public ManagerConnectionImpl() { this.id = idCounter.getAndIncrement(); - this.responseListeners = new HashMap(); - this.responseEventListeners = new HashMap(); - this.eventListeners = new ArrayList(); + this.responseListeners = new LockableMap<>(new HashMap<>()); + this.responseEventListeners = new LockableMap<>(new HashMap<>()); + this.eventListeners = new LockableList<>(new ArrayList<>()); this.protocolIdentifier = new ProtocolIdentifierWrapper(); } // the following two methods can be overriden when running test cases to // return a mock object - protected ManagerReader createReader(Dispatcher dispatcher, Object source) - { + protected ManagerReader createReader(Dispatcher dispatcher, Object source) { return new ManagerReaderImpl(dispatcher, source); } - protected ManagerWriter createWriter() - { + protected ManagerWriter createWriter() { return new ManagerWriterImpl(); } @@ -242,8 +253,7 @@ protected ManagerWriter createWriter() * * @param hostname the hostname to connect to */ - public void setHostname(String hostname) - { + public void setHostname(String hostname) { this.hostname = hostname; } @@ -255,29 +265,23 @@ public void setHostname(String hostname) * * @param port the port to connect to */ - public void setPort(int port) - { - if (port <= 0) - { + public void setPort(int port) { + if (port <= 0) { this.port = DEFAULT_PORT; - } - else - { + } else { this.port = port; } } /** - * Sets whether to use SSL. - *

    + * Sets whether to use SSL.
    * Default is false. * * @param ssl true to use SSL for the connection, * false for a plain text connection. * @since 0.3 */ - public void setSsl(boolean ssl) - { + public void setSsl(boolean ssl) { this.ssl = ssl; } @@ -287,8 +291,7 @@ public void setSsl(boolean ssl) * * @param username the username to use for login */ - public void setUsername(String username) - { + public void setUsername(String username) { this.username = username; } @@ -298,23 +301,25 @@ public void setUsername(String username) * * @param password the password to use for login */ - public void setPassword(String password) - { + public void setPassword(String password) { this.password = password; } + @Override + public void setEncoding(Charset encoding) { + this.encoding = encoding; + } + /** * Sets the time in milliseconds the synchronous method * {@link #sendAction(ManagerAction)} will wait for a response before - * throwing a TimeoutException. - *

    + * throwing a TimeoutException.
    * Default is 2000. * * @param defaultResponseTimeout default response timeout in milliseconds * @since 0.2 */ - public void setDefaultResponseTimeout(long defaultResponseTimeout) - { + public void setDefaultResponseTimeout(long defaultResponseTimeout) { this.defaultResponseTimeout = defaultResponseTimeout; } @@ -322,136 +327,118 @@ public void setDefaultResponseTimeout(long defaultResponseTimeout) * Sets the time in milliseconds the synchronous method * {@link #sendEventGeneratingAction(EventGeneratingAction)} will wait for a * response and the last response event before throwing a TimeoutException. - *

    + *
    * Default is 5000. * * @param defaultEventTimeout default event timeout in milliseconds * @since 0.2 */ - public void setDefaultEventTimeout(long defaultEventTimeout) - { + public void setDefaultEventTimeout(long defaultEventTimeout) { this.defaultEventTimeout = defaultEventTimeout; } /** - * Set to true to try reconnecting to ther asterisk serve - * even if the reconnection attempt threw an AuthenticationFailedException. - *

    + * Set to true to try reconnecting to ther asterisk serve even + * if the reconnection attempt threw an AuthenticationFailedException.
    * Default is true. * - * @param keepAliveAfterAuthenticationFailure - * true to try reconnecting to ther asterisk serve - * even if the reconnection attempt threw an AuthenticationFailedException, - * false otherwise. + * @param keepAliveAfterAuthenticationFailure true to try + * reconnecting to ther asterisk serve even if the reconnection + * attempt threw an AuthenticationFailedException, + * false otherwise. */ - public void setKeepAliveAfterAuthenticationFailure(boolean keepAliveAfterAuthenticationFailure) - { + public void setKeepAliveAfterAuthenticationFailure(boolean keepAliveAfterAuthenticationFailure) { this.keepAliveAfterAuthenticationFailure = keepAliveAfterAuthenticationFailure; } /* Implementation of ManagerConnection interface */ - public String getUsername() - { + public String getUsername() { return username; } - public String getPassword() - { + public String getPassword() { return password; } - public AsteriskVersion getVersion() - { + @Override + public Charset getEncoding() { + return encoding; + } + + public AsteriskVersion getVersion() { return version; } - public String getHostname() - { + public String getHostname() { return hostname; } - public int getPort() - { + public int getPort() { return port; } - public boolean isSsl() - { + public boolean isSsl() { return ssl; } - public InetAddress getLocalAddress() - { + public InetAddress getLocalAddress() { return socket.getLocalAddress(); } - public int getLocalPort() - { + public int getLocalPort() { return socket.getLocalPort(); } - public InetAddress getRemoteAddress() - { + public InetAddress getRemoteAddress() { return socket.getRemoteAddress(); } - public int getRemotePort() - { + public int getRemotePort() { return socket.getRemotePort(); } - public void registerUserEventClass(Class userEventClass) - { - if (reader == null) - { + public void registerUserEventClass(Class userEventClass) { + if (reader == null) { reader = createReader(this, this); } reader.registerEventClass(userEventClass); } - public void setSocketTimeout(int socketTimeout) - { + public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } - public void setSocketReadTimeout(int socketReadTimeout) - { + public void setSocketReadTimeout(int socketReadTimeout) { this.socketReadTimeout = socketReadTimeout; } - public synchronized void login() throws IOException, AuthenticationFailedException, TimeoutException - { + public void login() throws IOException, AuthenticationFailedException, TimeoutException { login(null); } - public synchronized void login(String eventMask) throws IOException, AuthenticationFailedException, TimeoutException - { - if (state != INITIAL && state != DISCONNECTED) - { - throw new IllegalStateException("Login may only be perfomed when in state " - + "INITIAL or DISCONNECTED, but connection is in state " + state); - } + public void login(String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { + try (LockCloser closer = this.withLock()) { + if (state != INITIAL && state != DISCONNECTED) { + throw new IllegalStateException("Login may only be perfomed when in state " + + "INITIAL or DISCONNECTED, but connection is in state " + state); + } - state = CONNECTING; - this.eventMask = eventMask; - try - { - doLogin(defaultResponseTimeout, eventMask); - } - finally - { - if (state != CONNECTED) - { - state = DISCONNECTED; + state = CONNECTING; + this.eventMask = eventMask; + try { + doLogin(defaultResponseTimeout, eventMask); + } finally { + if (state != CONNECTED) { + state = DISCONNECTED; + } } } } /** - * Does the real login, following the steps outlined below. - *

    + * Does the real login, following the steps outlined below.
    *

      *
    1. Connects to the asterisk server by calling {@link #connect()} if not * already connected @@ -478,408 +465,322 @@ public synchronized void login(String eventMask) throws IOException, Authenticat * @throws TimeoutException if a timeout occurs while waiting for the * protocol identifier. The connection is closed in this case. */ - protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, - TimeoutException - { - ChallengeAction challengeAction; - ManagerResponse challengeResponse; - String challenge; - String key; - LoginAction loginAction; - ManagerResponse loginResponse; - - if (socket == null) - { - connect(); - } + protected void doLogin(long timeout, String eventMask) + throws IOException, AuthenticationFailedException, TimeoutException { + try (LockCloser closer = this.withLock()) { + ChallengeAction challengeAction; + ManagerResponse challengeResponse; + String challenge; + String key; + LoginAction loginAction; + ManagerResponse loginResponse; + + if (socket == null) { + connect(); + } - synchronized (protocolIdentifier) - { - if (protocolIdentifier.value == null) - { - try - { - protocolIdentifier.wait(timeout); - } - catch (InterruptedException e) // NOPMD + if (protocolIdentifier.getValue() == null) { + try { + protocolIdentifier.await(timeout); + } catch (InterruptedException e) // NOPMD { Thread.currentThread().interrupt(); } } - if (protocolIdentifier.value == null) - { + if (protocolIdentifier.getValue() == null) { disconnect(); - if (reader != null && reader.getTerminationException() != null) - { + if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } - else - { - throw new TimeoutException("Timeout waiting for protocol identifier"); - } + throw new TimeoutException("Timeout waiting for protocol identifier"); } - } - challengeAction = new ChallengeAction("MD5"); - try - { - challengeResponse = sendAction(challengeAction); - } - catch (Exception e) - { - disconnect(); - throw new AuthenticationFailedException("Unable to send challenge action", e); - } + challengeAction = new ChallengeAction("MD5"); + try { + challengeResponse = sendAction(challengeAction); + } catch (Exception e) { + disconnect(); + throw new AuthenticationFailedException("Unable to send challenge action", e); + } - if (challengeResponse instanceof ChallengeResponse) - { - challenge = ((ChallengeResponse) challengeResponse).getChallenge(); - } - else - { - disconnect(); - throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " - + challengeResponse.getMessage()); - } + if (challengeResponse instanceof ChallengeResponse) { + challenge = ((ChallengeResponse) challengeResponse).getChallenge(); + } else { + disconnect(); + throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + + challengeResponse.getMessage()); + } - try - { - MessageDigest md; + try { + MessageDigest md; - md = MessageDigest.getInstance("MD5"); - if (challenge != null) - { - md.update(challenge.getBytes()); - } - if (password != null) - { - md.update(password.getBytes()); + md = MessageDigest.getInstance("MD5"); + if (challenge != null) { + md.update(challenge.getBytes(StandardCharsets.UTF_8)); + } + if (password != null) { + md.update(password.getBytes(StandardCharsets.UTF_8)); + } + key = ManagerUtil.toHexString(md.digest()); + } catch (NoSuchAlgorithmException ex) { + disconnect(); + throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } - key = ManagerUtil.toHexString(md.digest()); - } - catch (NoSuchAlgorithmException ex) - { - disconnect(); - throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); - } - loginAction = new LoginAction(username, "MD5", key, eventMask); - try - { - loginResponse = sendAction(loginAction); - } - catch (Exception e) - { - disconnect(); - throw new AuthenticationFailedException("Unable to send login action", e); - } + loginAction = new LoginAction(username, "MD5", key, eventMask); + try { + loginResponse = sendAction(loginAction); + } catch (Exception e) { + disconnect(); + throw new AuthenticationFailedException("Unable to send login action", e); + } - if (loginResponse instanceof ManagerError) - { - disconnect(); - throw new AuthenticationFailedException(loginResponse.getMessage()); - } + if (loginResponse instanceof ManagerError) { + disconnect(); + throw new AuthenticationFailedException(loginResponse.getMessage()); + } - logger.info("Successfully logged in"); + logger.info("Successfully logged in"); - version = determineVersion(); + version = determineVersion(); - state = CONNECTED; + state = CONNECTED; - writer.setTargetVersion(version); + writer.setTargetVersion(version); - logger.info("Determined Asterisk version: " + version); + logger.info("Determined Asterisk version: " + version); - // generate pseudo event indicating a successful login - ConnectEvent connectEvent = new ConnectEvent(this); - connectEvent.setProtocolIdentifier(getProtocolIdentifier()); - connectEvent.setDateReceived(DateUtil.getDate()); - // TODO could this cause a deadlock? - fireEvent(connectEvent); + // generate pseudo event indicating a successful login + ConnectEvent connectEvent = new ConnectEvent(this); + connectEvent.setProtocolIdentifier(getProtocolIdentifier()); + connectEvent.setDateReceived(DateUtil.getDate()); + // TODO could this cause a deadlock? + fireEvent(connectEvent, null); + } } - protected AsteriskVersion determineVersion() throws IOException, TimeoutException - { + protected AsteriskVersion determineVersion() throws IOException, TimeoutException { int attempts = 0; -// if ("Asterisk Call Manager/1.1".equals(protocolIdentifier.value)) -// { -// return AsteriskVersion.ASTERISK_1_6; -// } - - while (attempts++ < MAX_VERSION_ATTEMPTS) - { - final ManagerResponse showVersionFilesResponse; - final List showVersionFilesResult; - - // increase timeout as output is quite large - showVersionFilesResponse = sendAction(new CommandAction("show version files pbx.c"), defaultResponseTimeout * 2); - if (!(showVersionFilesResponse instanceof CommandResponse)) - { - // return early in case of permission problems - // org.asteriskjava.manager.response.ManagerError: - // actionId='null'; message='Permission denied'; response='Error'; - // uniqueId='null'; systemHashcode=15231583 - break; - } - - showVersionFilesResult = ((CommandResponse) showVersionFilesResponse).getResult(); - if (showVersionFilesResult != null && showVersionFilesResult.size() > 0) - { - final String line1; + logger.info("Got asterisk protocol identifier version " + protocolIdentifier.getValue()); - line1 = showVersionFilesResult.get(0); - if (line1 != null && line1.startsWith("File")) - { - final String rawVersion; + while (attempts++ < MAX_VERSION_ATTEMPTS) { + try { + AsteriskVersion version = determineVersionByCoreSettings(); + if (version != null) + return version; + } catch (Exception e) { + } - rawVersion = getRawVersion(); - if (rawVersion != null && rawVersion.startsWith("Asterisk 1.4")) - { - return AsteriskVersion.ASTERISK_1_4; - } - return AsteriskVersion.ASTERISK_1_2; - } - else if (line1 != null && line1.contains("No such command")) - { - final ManagerResponse coreShowVersionResponse = sendAction(new CommandAction("core show version"), defaultResponseTimeout * 2); - - if(coreShowVersionResponse != null && coreShowVersionResponse instanceof CommandResponse){ - final List coreShowVersionResult = ((CommandResponse) coreShowVersionResponse).getResult(); - - if(coreShowVersionResult != null && coreShowVersionResult.size() > 0){ - final String coreLine = coreShowVersionResult.get(0); - - if (coreLine != null && coreLine.startsWith("Asterisk 1.6")) - { - return AsteriskVersion.ASTERISK_1_6; - } - else if (coreLine != null && coreLine.startsWith("Asterisk 1.8")) - { - return AsteriskVersion.ASTERISK_1_8; - } - } - } - - try - { - Thread.sleep(RECONNECTION_VERSION_INTERVAL); - } - catch (Exception ex) - { - // ingnore - } // NOPMD - } - else - { - // if it isn't the "no such command", break and return the lowest version immediately - break; - } + try { + AsteriskVersion version = determineVersionByCoreShowVersion(); + if (version != null) + return version; + } catch (Exception e) { } + + try { + Thread.sleep(RECONNECTION_VERSION_INTERVAL); + } catch (Exception ex) { + // ignore + } // NOPMD } - // as a fallback assume 1.6 - return AsteriskVersion.ASTERISK_1_6; + logger.error("Unable to determine asterisk version, assuming " + AsteriskVersion.DEFAULT_VERSION + + "... you should expect problems to follow."); + return AsteriskVersion.DEFAULT_VERSION; } - protected String getRawVersion() - { - final ManagerResponse showVersionResponse; + /** + * Get asterisk version by 'core settings' actions. This is supported from + * Asterisk 1.6 onwards. + * + * @return + * @throws Exception + */ + protected AsteriskVersion determineVersionByCoreSettings() throws Exception { - try - { - showVersionResponse = sendAction(new CommandAction("show version"), defaultResponseTimeout * 2); - } - catch (Exception e) - { + ManagerResponse response = sendAction(new CoreSettingsAction()); + if (!(response instanceof CoreSettingsResponse)) { + // NOTE: you need system or reporting permissions + logger.info("Could not get core settings, do we have the necessary permissions?"); return null; } - if (showVersionResponse instanceof CommandResponse) - { - final List showVersionResult; + String ver = ((CoreSettingsResponse) response).getAsteriskVersion(); + return AsteriskVersion.getDetermineVersionFromString("Asterisk " + ver); + } - showVersionResult = ((CommandResponse) showVersionResponse).getResult(); - if (showVersionResult != null && showVersionResult.size() > 0) - { - return showVersionResult.get(0); - } + /** + * Determine version by the 'core show version' command. This needs + * 'command' permissions. + * + * @return + * @throws Exception + */ + protected AsteriskVersion determineVersionByCoreShowVersion() throws Exception { + final ManagerResponse coreShowVersionResponse = sendAction(new CommandAction(CMD_SHOW_VERSION)); + + if (coreShowVersionResponse == null || !(coreShowVersionResponse instanceof CommandResponse)) { + // this needs 'command' permissions + logger.info("Could not get response for 'core show version'"); + return null; } - return null; + final List coreShowVersionResult = ((CommandResponse) coreShowVersionResponse).getResult(); + if (coreShowVersionResult == null || coreShowVersionResult.isEmpty()) { + logger.warn("Got empty response for 'core show version'"); + return null; + } + + final String coreLine = coreShowVersionResult.get(0); + return AsteriskVersion.getDetermineVersionFromString(coreLine); } - protected synchronized void connect() throws IOException - { - logger.info("Connecting to " + hostname + ":" + port); + protected void connect() throws IOException { + try (LockCloser closer = this.withLock()) { + logger.info("Connecting to " + hostname + ":" + port); - if (reader == null) - { - logger.debug("Creating reader for " + hostname + ":" + port); - reader = createReader(this, this); - } + if (reader == null) { + logger.debug("Creating reader for " + hostname + ":" + port); + reader = createReader(this, this); + } - if (writer == null) - { - logger.debug("Creating writer"); - writer = createWriter(); - } + if (writer == null) { + logger.debug("Creating writer"); + writer = createWriter(); + } - logger.debug("Creating socket"); - socket = createSocket(); + logger.debug("Creating socket"); + socket = createSocket(); - logger.debug("Passing socket to reader"); - reader.setSocket(socket); + logger.debug("Passing socket to reader"); + reader.setSocket(socket); - if (readerThread == null || !readerThread.isAlive() || reader.isDead()) - { - logger.debug("Creating and starting reader thread"); - readerThread = new Thread(reader); - readerThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reader-" - + readerThreadCounter.getAndIncrement()); - readerThread.setDaemon(true); - readerThread.start(); - } + if (readerThread == null || !readerThread.isAlive() || reader.isDead()) { + logger.debug("Creating and starting reader thread"); + readerThread = new Thread(reader); + readerThread.setName( + "Asterisk-Java ManagerConnection-" + id + "-Reader-" + readerThreadCounter.getAndIncrement()); + readerThread.setDaemon(true); + readerThread.start(); + } - logger.debug("Passing socket to writer"); - writer.setSocket(socket); + logger.debug("Passing socket to writer"); + writer.setSocket(socket); + } } - protected SocketConnectionFacade createSocket() throws IOException - { - return new SocketConnectionFacadeImpl(hostname, port, ssl, socketTimeout, socketReadTimeout); + protected SocketConnectionFacade createSocket() throws IOException { + return new SocketConnectionFacadeImpl(hostname, port, ssl, socketTimeout, socketReadTimeout, encoding); } - public synchronized void logoff() throws IllegalStateException - { - if (state != CONNECTED && state != RECONNECTING) - { - throw new IllegalStateException("Logoff may only be perfomed when in state " - + "CONNECTED or RECONNECTING, but connection is in state " + state); - } + public void logoff() throws IllegalStateException { + try (LockCloser closer = this.withLock()) { + if (state != CONNECTED && state != RECONNECTING) { + throw new IllegalStateException("Logoff may only be perfomed when in state " + + "CONNECTED or RECONNECTING, but connection is in state " + state); + } - state = DISCONNECTING; + state = DISCONNECTING; - if (socket != null) - { - try - { - sendAction(new LogoffAction()); - } - catch (Exception e) - { - logger.warn("Unable to send LogOff action", e); + if (socket != null) { + try { + sendAction(new LogoffAction()); + } catch (Exception e) { + logger.warn("Unable to send LogOff action", e); + } } + cleanup(); + state = DISCONNECTED; } - cleanup(); - state = DISCONNECTED; } /** * Closes the socket connection. */ - protected synchronized void disconnect() - { - if (socket != null) - { - logger.info("Closing socket."); - try - { - socket.close(); - } - catch (IOException ex) - { - logger.warn("Unable to close socket: " + ex.getMessage()); + protected void disconnect() { + try (LockCloser closer = this.withLock()) { + if (socket != null) { + logger.info("Closing socket."); + try { + socket.close(); + } catch (IOException ex) { + logger.warn("Unable to close socket: " + ex.getMessage()); + } + socket = null; } - socket = null; + protocolIdentifier.reset(); } - protocolIdentifier.value = null; } - public ManagerResponse sendAction(ManagerAction action) throws IOException, TimeoutException, IllegalArgumentException, - IllegalStateException - { + public ManagerResponse sendAction(ManagerAction action) + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { return sendAction(action, defaultResponseTimeout); } - /* + /** * Implements synchronous sending of "simple" actions. + * + * @param timeout - in milliseconds */ - public ManagerResponse sendAction(ManagerAction action, long timeout) throws IOException, TimeoutException, - IllegalArgumentException, IllegalStateException - { - ResponseHandlerResult result; - SendActionCallback callbackHandler; - - result = new ResponseHandlerResult(); - callbackHandler = new DefaultSendActionCallback(result); + public ManagerResponse sendAction(ManagerAction action, long timeout) + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { - synchronized (result) - { + DefaultSendActionCallback callbackHandler = new DefaultSendActionCallback(); + ManagerResponse response = null; + try { sendAction(action, callbackHandler); // definitely return null for the response of user events - if (action instanceof UserEventAction) - { + if (action instanceof UserEventAction) { return null; } - - // only wait if we did not yet receive the response. - // Responses may be returned really fast. - if (result.getResponse() == null) - { - try - { - result.wait(timeout); - } - catch (InterruptedException ex) - { - logger.warn("Interrupted while waiting for result"); - Thread.currentThread().interrupt(); + try { + response = callbackHandler.waitForResponse(timeout); + + // no response? + if (response == null) { + throw new TimeoutException("Timeout waiting for response to " + action.getAction() + + (action.getActionId() == null + ? "" + : " (actionId: " + action.getActionId() + "), Timeout=" + timeout + " Action=" + + action.getAction())); } + } catch (InterruptedException ex) { + logger.warn("Interrupted while waiting for result"); + Thread.currentThread().interrupt(); } + } finally { + callbackHandler.dispose(); } - - // still no response? - if (result.getResponse() == null) - { - throw new TimeoutException("Timeout waiting for response to " + action.getAction() - + (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")")); - } - - return result.getResponse(); + return response; } - public void sendAction(ManagerAction action, SendActionCallback callback) throws IOException, IllegalArgumentException, - IllegalStateException - { + public void sendAction(ManagerAction action, SendActionCallback callback) + throws IOException, IllegalArgumentException, IllegalStateException { final String internalActionId; - if (action == null) - { + if (action == null) { throw new IllegalArgumentException("Unable to send action: action is null."); } // In general sending actions is only allowed while connected, though // there are a few exceptions, these are handled here: - if ((state == CONNECTING || state == RECONNECTING) - && (action instanceof ChallengeAction || action instanceof LoginAction || isShowVersionCommandAction(action))) - { + if ((state == CONNECTING || state == RECONNECTING) && (action instanceof ChallengeAction + || action instanceof LoginAction || isShowVersionCommandAction(action))) { // when (re-)connecting challenge and login actions are ok. } // NOPMD - else if (state == DISCONNECTING && action instanceof LogoffAction) - { + else if (state == DISCONNECTING && action instanceof LogoffAction) { // when disconnecting logoff action is ok. } // NOPMD - else if (state != CONNECTED) - { - throw new IllegalStateException("Actions may only be sent when in state " - + "CONNECTED, but connection is in state " + state); + else if (state != CONNECTED) { + throw new IllegalStateException( + "Actions may only be sent when in state " + "CONNECTED, but connection is in state " + state); } - if (socket == null) - { + if (socket == null) { throw new IllegalStateException("Unable to send " + action.getAction() + " action: socket not connected."); } @@ -887,79 +788,69 @@ else if (state != CONNECTED) // if the callbackHandler is null the user is obviously not interested // in the response, thats fine. - if (callback != null) - { - synchronized (this.responseListeners) - { + if (callback != null) { + try (LockCloser closer = this.responseListeners.withLock()) { this.responseListeners.put(internalActionId, callback); } } Class responseClass = getExpectedResponseClass(action.getClass()); - if (responseClass != null) - { + if (responseClass != null) { reader.expectResponseClass(internalActionId, responseClass); } writer.sendAction(action, internalActionId); } - boolean isShowVersionCommandAction(ManagerAction action) - { - if (! (action instanceof CommandAction)) { - return false; + boolean isShowVersionCommandAction(ManagerAction action) { + if (action instanceof CoreSettingsAction) + return true; + + if (action instanceof CommandAction) { + String cmd = ((CommandAction) action).getCommand(); + return CMD_SHOW_VERSION.equals(cmd); } - final Matcher showVersionMatcher = SHOW_VERSION_PATTERN.matcher(((CommandAction)action).getCommand()); - return showVersionMatcher.matches(); + + return false; } - private Class getExpectedResponseClass(Class actionClass) - { + private Class getExpectedResponseClass(Class actionClass) { final ExpectedResponse annotation = actionClass.getAnnotation(ExpectedResponse.class); - if (annotation == null) - { + if (annotation == null) { return null; } return annotation.value(); } - public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) throws IOException, EventTimeoutException, - IllegalArgumentException, IllegalStateException - { + public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) + throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException { return sendEventGeneratingAction(action, defaultEventTimeout); } /* * Implements synchronous sending of event generating actions. */ - public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) throws IOException, - EventTimeoutException, IllegalArgumentException, IllegalStateException - { + public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) + throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException { final ResponseEventsImpl responseEvents; final ResponseEventHandler responseEventHandler; final String internalActionId; - if (action == null) - { + if (action == null) { throw new IllegalArgumentException("Unable to send action: action is null."); - } - else if (action.getActionCompleteEventClass() == null) - { - throw new IllegalArgumentException("Unable to send action: actionCompleteEventClass for " - + action.getClass().getName() + " is null."); - } - else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClass())) - { - throw new IllegalArgumentException("Unable to send action: actionCompleteEventClass (" - + action.getActionCompleteEventClass().getName() + ") for " + action.getClass().getName() - + " is not a ResponseEvent."); + } else if (action.getActionCompleteEventClass() == null) { + throw new IllegalArgumentException( + "Unable to send action: actionCompleteEventClass for " + action.getClass().getName() + " is null."); + } else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClass())) { + throw new IllegalArgumentException( + "Unable to send action: actionCompleteEventClass (" + action.getActionCompleteEventClass().getName() + + ") for " + action.getClass().getName() + " is not a ResponseEvent."); } - if (state != CONNECTED) - { - throw new IllegalStateException("Actions may only be sent when in state " - + "CONNECTED but connection is in state " + state); + if (state != CONNECTED) { + throw new IllegalStateException( + "Actions may only be sent when in state " + "CONNECTED but connection is in state " + state); } responseEvents = new ResponseEventsImpl(); @@ -967,74 +858,105 @@ else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClas internalActionId = createInternalActionId(); - // register response handler... - synchronized (this.responseListeners) - { - this.responseListeners.put(internalActionId, responseEventHandler); - } + try { + // register response handler... + try (LockCloser closer = this.responseListeners.withLock()) { + this.responseListeners.put(internalActionId, responseEventHandler); + } - // ...and event handler. - synchronized (this.responseEventListeners) - { - this.responseEventListeners.put(internalActionId, responseEventHandler); - } + // ...and event handler. + try (LockCloser closer = this.responseEventListeners.withLock()) { + this.responseEventListeners.put(internalActionId, responseEventHandler); + } - synchronized (responseEvents) - { writer.sendAction(action, internalActionId); // only wait if response has not yet arrived. - if ((responseEvents.getResponse() == null || !responseEvents.isComplete())) - { - try - { - responseEvents.wait(timeout); - } - catch (InterruptedException e) - { + if (responseEvents.getResponse() == null || !responseEvents.isComplete()) { + try { + responseEvents.await(timeout); + } catch (InterruptedException e) { logger.warn("Interrupted while waiting for response events."); Thread.currentThread().interrupt(); } } - } - // still no response or not all events received and timed out? - if ((responseEvents.getResponse() == null || !responseEvents.isComplete())) - { - // clean up - synchronized (this.responseEventListeners) - { + // still no response or not all events received and timed out? + if (responseEvents.getResponse() == null || !responseEvents.isComplete()) { + throw new EventTimeoutException( + "Timeout waiting for response or response events to " + action.getAction() + + (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"), + responseEvents); + } + + } finally { + // remove the event handler + try (LockCloser closer = this.responseEventListeners.withLock()) { this.responseEventListeners.remove(internalActionId); } - throw new EventTimeoutException("Timeout waiting for response or response events to " + action.getAction() - + (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"), responseEvents); - } + // Note: The response handler should have already been removed + // when the response was received, however we remove it here + // just in case it was never received. + try (LockCloser closer = this.responseListeners.withLock()) { + this.responseListeners.remove(internalActionId); + } - // remove the event handler - // Note: The response handler has already been removed - // when the response was received - synchronized (this.responseEventListeners) - { - this.responseEventListeners.remove(internalActionId); } return responseEvents; } + public void sendEventGeneratingAction(EventGeneratingAction action, SendEventGeneratingActionCallback callback) + throws IOException, IllegalArgumentException, IllegalStateException { + if (action == null) { + throw new IllegalArgumentException("Unable to send action: action is null."); + } else if (action.getActionCompleteEventClass() == null) { + throw new IllegalArgumentException( + "Unable to send action: actionCompleteEventClass for " + action.getClass().getName() + " is null."); + } else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClass())) { + throw new IllegalArgumentException( + "Unable to send action: actionCompleteEventClass (" + action.getActionCompleteEventClass().getName() + + ") for " + action.getClass().getName() + " is not a ResponseEvent."); + } + + if (state != CONNECTED) { + throw new IllegalStateException( + "Actions may only be sent when in state " + "CONNECTED but connection is in state " + state); + } + + final String internalActionId = createInternalActionId(); + + if (callback != null) { + AsyncEventGeneratingResponseHandler responseEventHandler = new AsyncEventGeneratingResponseHandler( + action.getActionCompleteEventClass(), callback); + + // register response handler... + try (LockCloser closer = this.responseListeners.withLock()) { + this.responseListeners.put(internalActionId, responseEventHandler); + } + + // ...and event handler. + try (LockCloser closer = this.responseEventListeners.withLock()) { + this.responseEventListeners.put(internalActionId, responseEventHandler); + } + } + + writer.sendAction(action, internalActionId); + } + /** * Creates a new unique internal action id based on the hash code of this * connection and a sequence. * * @return a new internal action id - * @see ManagerUtil#addInternalActionId(String,String) + * @see ManagerUtil#addInternalActionId(String, String) * @see ManagerUtil#getInternalActionId(String) * @see ManagerUtil#stripInternalActionId(String) */ - private String createInternalActionId() - { - final StringBuffer sb; + private String createInternalActionId() { + final StringBuilder sb; - sb = new StringBuffer(); + sb = new StringBuilder(); sb.append(this.hashCode()); sb.append("_"); sb.append(actionIdCounter.getAndIncrement()); @@ -1042,36 +964,28 @@ private String createInternalActionId() return sb.toString(); } - public void addEventListener(final ManagerEventListener listener) - { - synchronized (this.eventListeners) - { + public void addEventListener(final ManagerEventListener listener) { + try (LockCloser closer = this.eventListeners.withLock()) { // only add it if its not already there - if (!this.eventListeners.contains(listener)) - { + if (!this.eventListeners.contains(listener)) { this.eventListeners.add(listener); } } } - public void removeEventListener(final ManagerEventListener listener) - { - synchronized (this.eventListeners) - { - if (this.eventListeners.contains(listener)) - { + public void removeEventListener(final ManagerEventListener listener) { + try (LockCloser closer = this.eventListeners.withLock()) { + if (this.eventListeners.contains(listener)) { this.eventListeners.remove(listener); } } } - public String getProtocolIdentifier() - { - return protocolIdentifier.value; + public String getProtocolIdentifier() { + return protocolIdentifier.getValue(); } - public ManagerConnectionState getState() - { + public ManagerConnectionState getState() { return state; } @@ -1085,15 +999,13 @@ public ManagerConnectionState getState() * @param response the response received by the reader * @see ManagerReader */ - public void dispatchResponse(ManagerResponse response) - { + public void dispatchResponse(ManagerResponse response, Integer requiredHandlingTime) { final String actionId; String internalActionId; SendActionCallback listener; // shouldn't happen - if (response == null) - { + if (response == null) { logger.error("Unable to dispatch null response. This should never happen. Please file a bug."); return; } @@ -1102,45 +1014,42 @@ public void dispatchResponse(ManagerResponse response) internalActionId = null; listener = null; - if (actionId != null) - { + if (actionId != null) { internalActionId = ManagerUtil.getInternalActionId(actionId); response.setActionId(ManagerUtil.stripInternalActionId(actionId)); } - logger.debug("Dispatching response with internalActionId '" + internalActionId + "':\n" + response); + if (logger.isDebugEnabled()) { + logger.debug("Dispatching response with internalActionId '" + internalActionId + "':\n" + response); + } - if (internalActionId != null) - { - synchronized (this.responseListeners) - { + if (internalActionId != null) { + try (LockCloser closer = this.responseListeners.withLock()) { listener = responseListeners.get(internalActionId); - if (listener != null) - { + if (listener != null) { this.responseListeners.remove(internalActionId); - } - else - { + } else { // when using the async sendAction it's ok not to register a // callback so if we don't find a response handler thats ok logger.debug("No response listener registered for " + "internalActionId '" + internalActionId + "'"); } } - } - else - { - logger.error("Unable to retrieve internalActionId from response: " + "actionId '" + actionId + "':\n" + response); + } else { + logger.error( + "Unable to retrieve internalActionId from response: " + "actionId '" + actionId + "':\n" + response); } - if (listener != null) - { - try - { + if (listener != null) { + LogTime timer = new LogTime(); + try { listener.onResponse(response); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Unexpected exception in response listener " + listener.getClass().getName(), e); + } finally { + if (requiredHandlingTime != null && timer.timeTaken() > requiredHandlingTime) { + logger.warn("Slow processing of event " + listener.getClass().getCanonicalName() + " " + + timer.timeTaken() + "MS \n" + response); + } } } } @@ -1154,52 +1063,49 @@ public void dispatchResponse(ManagerResponse response) * @see #removeEventListener(ManagerEventListener) * @see ManagerReader */ - public void dispatchEvent(ManagerEvent event) - { + public void dispatchEvent(ManagerEvent event, Integer requiredHandlingTime) { // shouldn't happen - if (event == null) - { + if (event == null) { logger.error("Unable to dispatch null event. This should never happen. Please file a bug."); return; } - - logger.debug("Dispatching event:\n" + event.toString()); + dispatchLegacyEventIfNeeded(event, requiredHandlingTime); + if (logger.isDebugEnabled()) { + logger.debug("Dispatching event:\n" + event.toString()); + } // Some events need special treatment besides forwarding them to the // registered eventListeners (clients) // These events are handled here at first: // Dispatch ResponseEvents to the appropriate responseEventListener - if (event instanceof ResponseEvent) - { + if (event instanceof ResponseEvent) { ResponseEvent responseEvent; String internalActionId; responseEvent = (ResponseEvent) event; internalActionId = responseEvent.getInternalActionId(); - if (internalActionId != null) - { - synchronized (responseEventListeners) - { + if (internalActionId != null) { + try (LockCloser closer = responseEventListeners.withLock()) { ManagerEventListener listener; listener = responseEventListeners.get(internalActionId); - if (listener != null) - { - try - { + if (listener != null) { + LogTime timer = new LogTime(); + try { listener.onManagerEvent(event); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(), e); + } finally { + if (requiredHandlingTime != null && timer.timeTaken() > requiredHandlingTime) { + logger.warn("Slow processing of event " + listener.getClass().getCanonicalName() + " " + + timer.timeTaken() + "MS \n" + event); + } } } } - } - else - { + } else { // ResponseEvent without internalActionId: // this happens if the same event class is used as response // event @@ -1209,44 +1115,41 @@ public void dispatchEvent(ManagerEvent event) // + "internalActionId:\n" + responseEvent); } // NOPMD } - if (event instanceof DisconnectEvent) - { + if (event instanceof DisconnectEvent) { + cleanupActionListeners((DisconnectEvent) event); // When we receive get disconnected while we are connected start // a new reconnect thread and set the state to RECONNECTING. - if (state == CONNECTED) - { - state = RECONNECTING; - // close socket if still open and remove reference to - // readerThread - // After sending the DisconnectThread that thread will die - // anyway. - cleanup(); - Thread reconnectThread = new Thread(new Runnable() - { - public void run() - { - reconnect(); - } - }); - reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-" - + reconnectThreadCounter.getAndIncrement()); - reconnectThread.setDaemon(true); - reconnectThread.start(); - // now the DisconnectEvent is dispatched to registered - // eventListeners - // (clients) and after that the ManagerReaderThread is gone. - // So effectively we replaced the reader thread by a - // ReconnectThread. - } - else - { - // when we receive a DisconnectEvent while not connected we - // ignore it and do not send it to clients - return; + try (LockCloser closer = this.withLock()) { + if (state == CONNECTED) { + state = RECONNECTING; + // close socket if still open and remove reference to + // readerThread + // After sending the DisconnectThread that thread will die + // anyway. + cleanup(); + Thread reconnectThread = new Thread(new Runnable() { + + public void run() { + reconnect(); + } + }); + reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-" + + reconnectThreadCounter.getAndIncrement()); + reconnectThread.setDaemon(true); + reconnectThread.start(); + // now the DisconnectEvent is dispatched to registered + // eventListeners + // (clients) and after that the ManagerReaderThread is gone. + // So effectively we replaced the reader thread by a + // ReconnectThread. + } else { + // when we receive a DisconnectEvent while not connected we + // ignore it and do not send it to clients + return; + } } } - if (event instanceof ProtocolIdentifierReceivedEvent) - { + if (event instanceof ProtocolIdentifierReceivedEvent) { ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent; String protocolIdentifier; @@ -1257,7 +1160,18 @@ public void run() return; } - fireEvent(event); + fireEvent(event, requiredHandlingTime); + } + + /** + * Enro 2015-03 Workaround to continue having Legacy Events from Asterisk + * 13. + */ + private void dispatchLegacyEventIfNeeded(ManagerEvent event, Integer requiredHandlingTime) { + if (event instanceof DialBeginEvent) { + DialEvent legacyEvent = new DialEvent((DialBeginEvent) event); + dispatchEvent(legacyEvent, requiredHandlingTime); + } } /** @@ -1265,146 +1179,205 @@ public void run() * * @param event the event to propagate */ - private void fireEvent(ManagerEvent event) - { - synchronized (eventListeners) - { - for (ManagerEventListener listener : eventListeners) - { - try - { + private void fireEvent(ManagerEvent event, Integer requiredHandlingTime) { + try (LockCloser closer = eventListeners.withLock()) { + for (ManagerEventListener listener : eventListeners) { + LogTime timer = new LogTime(); + try { listener.onManagerEvent(event); - } - catch (RuntimeException e) - { + } catch (RuntimeException e) { logger.warn("Unexpected exception in eventHandler " + listener.getClass().getName(), e); + } finally { + if (requiredHandlingTime != null && timer.timeTaken() > requiredHandlingTime) { + logger.warn("Slow processing of event " + listener.getClass().getCanonicalName() + " " + + timer.timeTaken() + "MS \n" + event); + } } } } } + private boolean isSupportedProtocolIdentifier(final String identifier) { + + // Normal version checks + for (String supportedVersion : SUPPORTED_AMI_VERSIONS) { + String prefix = "Asterisk Call Manager/" + supportedVersion + "."; + if (identifier.startsWith(prefix)) { + return true; + } + } + + // Other cases + if ("OpenPBX Call Manager/1.0".equals(identifier)) + return true; + if ("CallWeaver Call Manager/1.0".equals(identifier)) + return true; + if (identifier.startsWith("Asterisk Call Manager Proxy/")) + return true; + + return false; + } + /** * This method is called when a {@link ProtocolIdentifierReceivedEvent} is * received from the reader. Having received a correct protocol identifier - * is the precodition for logging in. + * is the precondition for logging in. * * @param identifier the protocol version used by the Asterisk server. */ - private void setProtocolIdentifier(final String identifier) - { + private void setProtocolIdentifier(final String identifier) { logger.info("Connected via " + identifier); - if (!"Asterisk Call Manager/1.0".equals(identifier) - && !"Asterisk Call Manager/1.1".equals(identifier) // Asterisk 1.6 - && !"Asterisk Call Manager/1.2".equals(identifier) // bri stuffed - && !"OpenPBX Call Manager/1.0".equals(identifier) - && !"CallWeaver Call Manager/1.0".equals(identifier) - && !(identifier != null && identifier.startsWith("Asterisk Call Manager Proxy/"))) - { + if (identifier == null || !isSupportedProtocolIdentifier(identifier)) { logger.warn("Unsupported protocol version '" + identifier + "'. Use at your own risk."); } - - synchronized (protocolIdentifier) - { - protocolIdentifier.value = identifier; - protocolIdentifier.notifyAll(); - } + protocolIdentifier.setValue(identifier); } /** - * Reconnects to the asterisk server when the connection is lost. - *

      + * Reconnects to the asterisk server when the connection is lost.
      * While keepAlive is true we will try to reconnect. * Reconnection attempts will be stopped when the {@link #logoff()} method * is called or when the login after a successful reconnect results in an * {@link AuthenticationFailedException} suggesting that the manager * credentials have changed and keepAliveAfterAuthenticationFailure is not - * set. - *

      + * set.
      * This method is called when a {@link DisconnectEvent} is received from the * reader. */ - private void reconnect() - { + private void reconnect() { int numTries; // try to reconnect numTries = 0; - while (state == RECONNECTING) - { - try - { - if (numTries < 10) - { + while (true) { + try { + if (numTries < 10) { // try to reconnect quite fast for the firt 10 times // this succeeds if the server has just been restarted Thread.sleep(RECONNECTION_INTERVAL_1); - } - else - { + } else { // slow down after 10 unsuccessful attempts asuming a // shutdown of the server Thread.sleep(RECONNECTION_INTERVAL_2); } - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - try - { - connect(); - - try - { - doLogin(defaultResponseTimeout, eventMask); - logger.info("Successfully reconnected."); - // everything is ok again, so we leave - // when successful doLogin set the state to CONNECTED so no - // need to adjust it - break; - } - catch (AuthenticationFailedException e1) - { - if (keepAliveAfterAuthenticationFailure) - { - logger.error("Unable to log in after reconnect: " + e1.getMessage()); + try { + try (LockCloser closer = this.withLock()) { + if (state != RECONNECTING) { + break; } - else - { - logger.error("Unable to log in after reconnect: " + e1.getMessage() + ". Giving up."); - state = DISCONNECTED; + connect(); + + try { + doLogin(defaultResponseTimeout, eventMask); + logger.info("Successfully reconnected."); + // everything is ok again, so we leave + // when successful doLogin set the state to CONNECTED so + // no + // need to adjust it + break; + } catch (AuthenticationFailedException e1) { + if (keepAliveAfterAuthenticationFailure) { + logger.error("Unable to log in after reconnect: " + e1.getMessage()); + } else { + logger.error("Unable to log in after reconnect: " + e1.getMessage() + ". Giving up."); + state = DISCONNECTED; + } + } catch (TimeoutException e1) { + // shouldn't happen - but happens! + logger.error("TimeoutException while trying to log in " + "after reconnect."); } } - catch (TimeoutException e1) - { - // shouldn't happen - but happens! - logger.error("TimeoutException while trying to log in " + "after reconnect."); - } - } - catch (IOException e) - { + } catch (IOException e) { // server seems to be still down, just continue to attempt // reconnection - logger.warn("Exception while trying to reconnect: " + e.getMessage()); + String message = e.getClass().getSimpleName(); + if (e.getMessage() != null) { + message = e.getMessage(); + } + + logger.warn("Exception while trying to reconnect: " + message); + try { + // Where multiple connections are present, spread out + // their reconnect attempts and prevent hard loop. + long randomSleep = (long) (Math.random() * 100); + TimeUnit.MILLISECONDS.sleep(50 + randomSleep); + } catch (InterruptedException e1) { + logger.error(e1); + } } numTries++; } } - private void cleanup() - { + /** + * Notify pending {@link #responseListeners} and + * {@link #responseEventListeners} so the synchronous ones can unblock, + * clears those listener collections. + * + * @param event + */ + private void cleanupActionListeners(DisconnectEvent event) { + HashMap oldResponseListeners = null; + + try (LockCloser closer = responseListeners.withLock()) { + // Store remaining response listeners to be notified outside of + // synchronized + oldResponseListeners = new HashMap(responseListeners); + responseListeners.clear(); + } + + // Clear pending responseListeners that will not receive their responses + for (SendActionCallback responseListener : oldResponseListeners.values()) { + // Allows to unblock waiting sendAction() calls + try { + responseListener.onResponse(null); + } catch (Exception ex) { + logger.warn("Exception notifying responseListener.onResponse(null)", ex); + } + } + + HashMap oldResponseEventListeners = null; + try (LockCloser closer = responseEventListeners.withLock()) { + // Store remaining responseEventListeners to be notified outside of + // synchronized + oldResponseEventListeners = new HashMap(responseEventListeners); + responseEventListeners.clear(); + } + + // Remove those already cleaned up via oldResponseListeners + // TODO or should all be notified? + for (String discardedInternalActionId : oldResponseListeners.keySet()) { + oldResponseEventListeners.remove(discardedInternalActionId); + } + + // Notify remaining responseEventListeners. + // These could be EventGeneratingAction handlers that have received a + // response but have not yet received the end event. + for (ManagerEventListener responseEventListener : oldResponseEventListeners.values()) { + try { + // Allows to unblock waiting sendAction() calls + responseEventListener.onManagerEvent(event); + } catch (Exception ex) { + logger.warn("Exception notifying responseListener.onManagerEvent(DisconnectEvent)", ex); + } + } + } + + private void cleanup() { disconnect(); this.readerThread = null; } @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; - sb = new StringBuffer("ManagerConnection["); + sb = new StringBuilder("ManagerConnection["); sb.append("id='").append(id).append("',"); sb.append("hostname='").append(hostname).append("',"); sb.append("port=").append(port).append(","); @@ -1418,67 +1391,40 @@ public String toString() /** * A simple data object to store a ManagerResult. */ - private static class ResponseHandlerResult implements Serializable - { - /** - * Serializable version identifier. - */ + private static class DefaultSendActionCallback implements SendActionCallback, Serializable { private static final long serialVersionUID = 7831097958568769220L; private ManagerResponse response; + private final CountDownLatch latch = new CountDownLatch(1); + private volatile boolean disposed = false; + private LogTime timer = new LogTime(); - public ResponseHandlerResult() - { - } - - public ManagerResponse getResponse() - { + private ManagerResponse waitForResponse(long timeout) throws InterruptedException { + latch.await(timeout, TimeUnit.MILLISECONDS); return this.response; } - public void setResponse(ManagerResponse response) - { + @Override + public void onResponse(ManagerResponse response) { this.response = response; + if (disposed) { + logger.error("Response arrived after Disposal and assumably Timeout " + response + " elapsed: " + + timer.timeTaken() + "(MS)"); + logger.error("" + response.getDateReceived()); + } + latch.countDown(); } - } - - /** - * A simple response handler that stores the received response in a - * ResponseHandlerResult for further processing. - */ - private static class DefaultSendActionCallback implements SendActionCallback, Serializable - { - /** - * Serializable version identifier. - */ - private static final long serialVersionUID = 2926598671855316803L; - private final ResponseHandlerResult result; - /** - * Creates a new instance. - * - * @param result the result to store the response in - */ - public DefaultSendActionCallback(ResponseHandlerResult result) - { - this.result = result; + private void dispose() { + disposed = true; } - public void onResponse(ManagerResponse response) - { - synchronized (result) - { - result.setResponse(response); - result.notifyAll(); - } - } } /** * A combinded event and response handler that adds received events and the * response to a ResponseEvents object. */ - private static class ResponseEventHandler implements ManagerEventListener, SendActionCallback - { + private static class ResponseEventHandler implements ManagerEventListener, SendActionCallback { private final ResponseEventsImpl events; private final Class actionCompleteEventClass; @@ -1489,62 +1435,139 @@ private static class ResponseEventHandler implements ManagerEventListener, SendA * @param actionCompleteEventClass the type of event that indicates that * all events have been received */ - public ResponseEventHandler(ResponseEventsImpl events, Class actionCompleteEventClass) - { + public ResponseEventHandler(ResponseEventsImpl events, Class actionCompleteEventClass) { this.events = events; this.actionCompleteEventClass = actionCompleteEventClass; } - public void onManagerEvent(ManagerEvent event) - { - synchronized (events) - { - // should always be a ResponseEvent, anyway... - if (event instanceof ResponseEvent) - { - ResponseEvent responseEvent; + public void onManagerEvent(ManagerEvent event) { + if (event instanceof DisconnectEvent) { + // Set flag that must not wait for the response + events.setComplete(true); + // unblock potentially waiting synchronous call to + // sendEventGeneratingAction(EventGeneratingAction action, long + // timeout) + events.countDown(); + return; + } - responseEvent = (ResponseEvent) event; - events.addEvent(responseEvent); - } + // should always be a ResponseEvent, anyway... + if (event instanceof ResponseEvent) { + ResponseEvent responseEvent; - // finished? - if (actionCompleteEventClass.isAssignableFrom(event.getClass())) - { - events.setComplete(true); - // notify if action complete event and response have been - // received - if (events.getResponse() != null) - { - events.notifyAll(); - } + responseEvent = (ResponseEvent) event; + events.addEvent(responseEvent); + } + + // finished? + if (actionCompleteEventClass.isAssignableFrom(event.getClass())) { + events.setComplete(true); + // notify if action complete event and response have been + // received + if (events.getResponse() != null) { + events.countDown(); } } } - public void onResponse(ManagerResponse response) - { - synchronized (events) - { - events.setRepsonse(response); - if (response instanceof ManagerError) - { - events.setComplete(true); - } + public void onResponse(ManagerResponse response) { + // If disconnected + if (response == null) { + // Set flag that must not wait for the response + events.setComplete(true); + // unblock potentially waiting synchronous call to + // sendEventGeneratingAction(EventGeneratingAction action, long + // timeout) + events.countDown(); + return; + } - // finished? - // notify if action complete event and response have been - // received - if (events.isComplete()) - { - events.notifyAll(); + events.setRepsonse(response); + if (response instanceof ManagerError) { + events.setComplete(true); + } + + // finished? + // notify if action complete event and response have been + // received + if (events.isComplete()) { + events.countDown(); + } + } + } + + private class AsyncEventGeneratingResponseHandler implements SendActionCallback, ManagerEventListener { + private final Class actionCompleteEventClass; + private final SendEventGeneratingActionCallback callback; + + private final ResponseEventsImpl events; + + public AsyncEventGeneratingResponseHandler(Class actionCompleteEventClass, + SendEventGeneratingActionCallback callback) { + this.actionCompleteEventClass = actionCompleteEventClass; + this.callback = callback; + + this.events = new ResponseEventsImpl(); + } + + @Override + public void onManagerEvent(ManagerEvent event) { + if (event instanceof DisconnectEvent) { + callback.onResponse(events); + return; + } + + // should always be a ResponseEvent, anyway... + if (false == (event instanceof ResponseEvent)) { + return; + } + + ResponseEvent responseEvent = (ResponseEvent) event; + events.addEvent(responseEvent); + + if (actionCompleteEventClass.isAssignableFrom(event.getClass())) { + events.setComplete(true); + String internalActionId = responseEvent.getInternalActionId(); + try (LockCloser closer = responseEventListeners.withLock()) { + responseEventListeners.remove(internalActionId); } + callback.onResponse(events); + } + } + + @Override + public void onResponse(ManagerResponse response) { + // If disconnected + if (response == null) { + callback.onResponse(events); + return; + } + + events.setRepsonse(response); + if (response instanceof ManagerError) { + events.setComplete(true); + } + + // finished? + if (events.isComplete()) { + // invoke callback + callback.onResponse(events); } } } - private static class ProtocolIdentifierWrapper - { - String value; + @Override + public void deregisterEventClass(Class eventClass) { + if (reader == null) { + reader = createReader(this, this); + } + + reader.deregisterEventClass(eventClass); + + } + + @Override + public void stop() { + // NO_OP } } diff --git a/src/main/java/org/asteriskjava/manager/internal/ManagerReader.java b/src/main/java/org/asteriskjava/manager/internal/ManagerReader.java index fac94df34..2b3e46c19 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerReader.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerReader.java @@ -16,16 +16,17 @@ */ package org.asteriskjava.manager.internal; -import java.io.IOException; - import org.asteriskjava.manager.event.ManagerEvent; import org.asteriskjava.manager.response.ManagerResponse; import org.asteriskjava.util.SocketConnectionFacade; +import java.io.IOException; + /** * The ManagerReader reads events and responses from the asterisk server, parses * them using EventBuilderImpl and ResponseBuilder and dispatches them to the - * associated ManagerConnection.

      + * associated ManagerConnection. + *

      * Do not use this interface in your code, it is intended to be used only by the * DefaultManagerConnection. * @@ -35,8 +36,7 @@ * @see org.asteriskjava.manager.internal.ResponseBuilder * @see org.asteriskjava.manager.DefaultManagerConnection */ -public interface ManagerReader extends Runnable -{ +public interface ManagerReader extends Runnable { String COMMAND_RESULT_RESPONSE_KEY = "__result__"; /** @@ -47,7 +47,8 @@ public interface ManagerReader extends Runnable void setSocket(final SocketConnectionFacade socket); /** - * Registers a new event type with the underlying EventBuilderImpl.

      + * Registers a new event type with the underlying EventBuilderImpl. + *

      * The eventClass must extend ManagerEvent. * * @param event class of the event to register. @@ -67,14 +68,17 @@ public interface ManagerReader extends Runnable * Checks whether this reader is terminating or terminated. * * @return true if this reader is terminating or terminated, - * false otherwise. + * false otherwise. */ boolean isDead(); /** * Returns the Exception that caused this reader to terminate if any. * - * @return the Exception that caused this reader to terminate if any or null if not. + * @return the Exception that caused this reader to terminate if any or + * null if not. */ IOException getTerminationException(); + + void deregisterEventClass(Class eventClass); } diff --git a/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java b/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java index e605dbe4d..c97f268ad 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java @@ -16,10 +16,13 @@ */ package org.asteriskjava.manager.internal; +import com.google.common.util.concurrent.RateLimiter; import org.asteriskjava.manager.event.DisconnectEvent; import org.asteriskjava.manager.event.ManagerEvent; import org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent; +import org.asteriskjava.manager.internal.backwardsCompatibility.BackwardsCompatibilityForManagerEvents; import org.asteriskjava.manager.response.ManagerResponse; +import org.asteriskjava.pbx.util.LogTime; import org.asteriskjava.util.DateUtil; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; @@ -29,37 +32,30 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; - /** * Default implementation of the ManagerReader interface. * * @author srt * @version $Id$ */ -public class ManagerReaderImpl implements ManagerReader -{ +public class ManagerReaderImpl implements ManagerReader { /** * Instance logger. */ private final Log logger = LogFactory.getLog(getClass()); /** - * The event builder utility to convert a map of attributes reveived from asterisk to instances - * of registered event classes. + * The event builder utility to convert a map of attributes reveived from + * asterisk to instances of registered event classes. */ private final EventBuilder eventBuilder; /** - * The response builder utility to convert a map of attributes reveived from asterisk to - * instances of well known response classes. + * The response builder utility to convert a map of attributes reveived from + * asterisk to instances of well known response classes. */ private final ResponseBuilder responseBuilder; - /** - * The dispatcher to use for dispatching events and responses. - */ - private final Dispatcher dispatcher; - private final Map> expectedResponseClasses; /** @@ -87,20 +83,28 @@ public class ManagerReaderImpl implements ManagerReader */ private IOException terminationException; + /** + * set of classes able to take newer versions of ManagerEvents and emit + * older style manager Events + */ + BackwardsCompatibilityForManagerEvents compatibility = new BackwardsCompatibilityForManagerEvents(); + + private final Dispatcher rawDispatcher; + /** * Creates a new ManagerReaderImpl. * - * @param dispatcher the dispatcher to use for dispatching events and responses. + * @param dispatcher the dispatcher to use for dispatching events and + * responses. * @param source the source to use when creating {@link ManagerEvent}s */ - public ManagerReaderImpl(final Dispatcher dispatcher, Object source) - { - this.dispatcher = dispatcher; + public ManagerReaderImpl(final Dispatcher dispatcher, Object source) { + this.rawDispatcher = dispatcher; this.source = source; this.eventBuilder = new EventBuilderImpl(); this.responseBuilder = new ResponseBuilderImpl(); - this.expectedResponseClasses = new ConcurrentHashMap>(); + this.expectedResponseClasses = new ConcurrentHashMap<>(); } /** @@ -108,250 +112,257 @@ public ManagerReaderImpl(final Dispatcher dispatcher, Object source) * * @param socket the socket to use for reading from the asterisk server. */ - public void setSocket(final SocketConnectionFacade socket) - { + public void setSocket(final SocketConnectionFacade socket) { this.socket = socket; } - public void registerEventClass(Class eventClass) - { + public void registerEventClass(Class eventClass) { eventBuilder.registerEventClass(eventClass); } - public void expectResponseClass(String internalActionId, Class responseClass) - { + public void expectResponseClass(String internalActionId, Class responseClass) { expectedResponseClasses.put(internalActionId, responseClass); } /** - * Reads line by line from the asterisk server, sets the protocol identifier (using a - * generated {@link org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent}) as soon as it is - * received and dispatches the received events and responses via the associated dispatcher. + * Reads line by line from the asterisk server, sets the protocol identifier + * (using a generated + * {@link org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent}) + * as soon as it is received and dispatches the received events and + * responses via the associated dispatcher. * - * @see org.asteriskjava.manager.internal.Dispatcher#dispatchEvent(ManagerEvent) - * @see org.asteriskjava.manager.internal.Dispatcher#dispatchResponse(ManagerResponse) + * @see org.asteriskjava.manager.internal.Dispatcher#dispatchEvent(ManagerEvent, Integer) + * @see org.asteriskjava.manager.internal.Dispatcher#dispatchResponse(ManagerResponse, Integer) */ - public void run() - { - final Map buffer = new HashMap(); + public void run() { + long timeOfLastEvent = 0; + long reserve = 0; + final Map buffer = new HashMap<>(); String line; - if (socket == null) - { + if (socket == null) { throw new IllegalStateException("Unable to run: socket is null."); } this.die = false; this.dead = false; - try - { + AsyncEventPump dispatcher = new AsyncEventPump(this, rawDispatcher, Thread.currentThread().getName()); + long slowEventThresholdMs = 10; + RateLimiter slowEventLogLimiter = RateLimiter.create(4); + try { // main loop - while (!this.die && (line = socket.readLine()) != null) - { - // maybe we will find a better way to identify the protocol identifier but for now + while (!this.die && (line = socket.readLine()) != null) { + // maybe we will find a better way to identify the protocol + // identifier but for now // this works quite well. - if (line.startsWith("Asterisk Call Manager/") || - line.startsWith("Asterisk Call Manager Proxy/") || - line.startsWith("Asterisk Manager Proxy/") || - line.startsWith("OpenPBX Call Manager/") || - line.startsWith("CallWeaver Call Manager/")) - { + if (line.startsWith("Asterisk Call Manager/") || line.startsWith("Asterisk Call Manager Proxy/") + || line.startsWith("Asterisk Manager Proxy/") || line.startsWith("OpenPBX Call Manager/") + || line.startsWith("CallWeaver Call Manager/")) { ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent; protocolIdentifierReceivedEvent = new ProtocolIdentifierReceivedEvent(source); protocolIdentifierReceivedEvent.setProtocolIdentifier(line); protocolIdentifierReceivedEvent.setDateReceived(DateUtil.getDate()); - dispatcher.dispatchEvent(protocolIdentifierReceivedEvent); + dispatcher.dispatchEvent(protocolIdentifierReceivedEvent, null); continue; } - /* Special handling for "Response: Follows" (CommandResponse) - * As we are using "\r\n" as the delimiter for line this also handles multiline - * results as long as they only contain "\n". + /* + * Special handling for "Response: Follows" (CommandResponse) As + * we are using "\r\n" as the delimiter for line this also + * handles multiline results as long as they only contain "\n". */ - if ("Follows".equals(buffer.get("response")) && line.endsWith("--END COMMAND--")) - { + if ("Follows".equals(buffer.get("response")) && line.endsWith("--END COMMAND--")) { buffer.put(COMMAND_RESULT_RESPONSE_KEY, line); continue; } - if (line.length() > 0) - { - int delimiterIndex; - int delimiterLength; - - // begin of workaround for Astersik bug 13319 - // see AJ-77 - // Use this workaround only when line starts from "From " and "To " - int isFromAtStart, isToAtStart; - isFromAtStart = line.indexOf("From "); - isToAtStart = line.indexOf("To "); - if (isFromAtStart == 0 || isToAtStart == 0) - { - delimiterIndex = line.indexOf(" "); - delimiterLength = 1; - } - else - { - delimiterIndex = line.indexOf(": "); - delimiterLength = 2; - } - // end of workaround for Astersik bug 13319 - - if (delimiterIndex > 0 && line.length() > delimiterIndex + delimiterLength) - { - String name; - String value; - - name = line.substring(0, delimiterIndex).toLowerCase(Locale.ENGLISH); - value = line.substring(delimiterIndex + delimiterLength); - - addToBuffer(buffer, name, value); - // TODO tracing - //logger.debug("Got name [" + name + "], value: [" + value + "]"); + if (!line.isEmpty()) { + String[] parts = line.split(":", 2); + if (parts.length == 2) { + parts[0] = parts[0].toLowerCase(Locale.ENGLISH).trim(); + parts[1] = parts[1].trim(); + if (!parts[0].isEmpty()) { + addToBuffer(buffer, parts[0], parts[1]); + // TODO tracing + // logger.debug("Got name [" + name + "], value: [" + value + "]"); + } } } - - // an empty line indicates a normal response's or event's end so we build - // the corresponding value object and dispatch it through the ManagerConnection. - if (line.length() == 0) - { - if (buffer.containsKey("event")) - { + // an empty line indicates a normal response's or event's end so + // we build + // the corresponding value object and dispatch it through the + // ManagerConnection. + if (line.length() == 0) { + Object cause = null; + LogTime timer = new LogTime(); + if (buffer.containsKey("event")) { // TODO tracing - //logger.debug("attempting to build event: " + buffer.get("event")); + // logger.debug("attempting to build event: " + + // buffer.get("event")); ManagerEvent event = buildEvent(source, buffer); - if (event != null) - { - dispatcher.dispatchEvent(event); - } - else - { + if (event != null) { + cause = event; + dispatcher.dispatchEvent(event, null); + + // Backwards compatibility for bridge events. + // Asterisk 13 uses BridgeCreate, + // BridgeEnter, BridgeLeave and BridgeDestroy + // events. + // So here we track active bridges and simulate + // BridgeEvent's for them allowing legacy code to + // still work with BridgeEvent's + ManagerEvent secondaryEvent = compatibility.handleEvent(event); + if (secondaryEvent != null) { + dispatcher.dispatchEvent(secondaryEvent, null); + } + } else { logger.debug("buildEvent returned null"); } - } - else if (buffer.containsKey("response")) - { + } else if (buffer.containsKey("response")) { ManagerResponse response = buildResponse(buffer); // TODO tracing - //logger.debug("attempting to build response"); - if (response != null) - { - dispatcher.dispatchResponse(response); + // logger.debug("attempting to build response"); + if (response != null) { + cause = response; + dispatcher.dispatchResponse(response, null); } - } - else - { - if (buffer.size() > 0) - { + } else { + if (!buffer.isEmpty()) { logger.debug("Buffer contains neither response nor event"); } } buffer.clear(); + + // some math to determine if events are being processed + // slowly + long elapsed = timer.timeTaken(); + long now = System.currentTimeMillis(); + long add = now - timeOfLastEvent; + + // double the elapsed time, this allows 50% slack. Also note + // that we + // would never be able to exhaust the reserve if we don't + // artificially increase the elapsed time. I'd have probably + // gone for 1.3 but I am trying to avoid floating point math + reserve = (reserve + add) - (elapsed * 2); + + // don't allow reserve to exceed 500 ms + reserve = Math.min(500, reserve); + + // don't allow reserve to go negative, otherwise we might + // accrue a large debt + reserve = Math.max(0, reserve); + timeOfLastEvent = now; + + // check if the event was slow to build and dispatch + if (elapsed > slowEventThresholdMs) { + // check for to many slow events this second. + if (reserve <= 0) { + // check we haven't already logged this to often + if (slowEventLogLimiter.tryAcquire()) { + logger.warn("(This is normal during JVM warmup) Slow processing of event " + elapsed + "\n" + + cause); + } + } + } } } this.dead = true; logger.debug("Reached end of stream, terminating reader."); - } - catch (IOException e) - { + } catch (IOException e) { this.terminationException = e; this.dead = true; logger.info("Terminating reader thread: " + e.getMessage()); - } - finally - { + } catch (Exception e) { + if (this.terminationException == null) { + // wrap in IOException to avoid changing the external API of + // asteriskjava + this.terminationException = new IOException(e); + } + logger.error("Manager reader exiting due to unexpected Exception..."); + logger.error(e, e); + } finally { this.dead = true; // cleans resources and reconnects if needed DisconnectEvent disconnectEvent = new DisconnectEvent(source); disconnectEvent.setDateReceived(DateUtil.getDate()); - dispatcher.dispatchEvent(disconnectEvent); + dispatcher.dispatchEvent(disconnectEvent, null); + dispatcher.stop(); } } @SuppressWarnings("unchecked") - private void addToBuffer(Map buffer, String name, String value) - { - // if we already have a value for that key, convert the value to a list and add + private void addToBuffer(Map buffer, String name, String value) { + // if we already have a value for that key, convert the value to a list + // and add // the new value to that list. - if (buffer.containsKey(name)) - { + if (buffer.containsKey(name)) { Object currentValue = buffer.get(name); - if (currentValue instanceof List) - { + if (currentValue instanceof List) { ((List) currentValue).add(value); return; } - List list = new ArrayList(); - if (currentValue instanceof String) - { + List list = new ArrayList<>(); + if (currentValue instanceof String) { list.add((String) currentValue); - } - else - { + } else { list.add(currentValue.toString()); } list.add(value); buffer.put(name, list); - } - else - { + } else { buffer.put(name, value); } } - public void die() - { + public void die() { this.die = true; } - public boolean isDead() - { + public boolean isDead() { return dead; } - public IOException getTerminationException() - { + public IOException getTerminationException() { return terminationException; } - private ManagerResponse buildResponse(Map buffer) - { + private ManagerResponse buildResponse(Map buffer) { Class responseClass = null; final String actionId = (String) buffer.get("actionid"); final String internalActionId = ManagerUtil.getInternalActionId(actionId); - if (internalActionId != null) - { - responseClass = expectedResponseClasses.get(internalActionId); - if (responseClass != null) - { - expectedResponseClasses.remove(internalActionId); - } + if (internalActionId != null) { + responseClass = expectedResponseClasses.remove(internalActionId); } final ManagerResponse response = responseBuilder.buildResponse(responseClass, buffer); - if (response != null) - { + if (response != null) { response.setDateReceived(DateUtil.getDate()); } return response; } - private ManagerEvent buildEvent(Object source, Map buffer) - { + private ManagerEvent buildEvent(Object source, Map buffer) { ManagerEvent event; event = eventBuilder.buildEvent(source, buffer); - if (event != null) - { + if (event != null) { event.setDateReceived(DateUtil.getDate()); } return event; } + + @Override + public void deregisterEventClass(Class eventClass) { + + eventBuilder.deregisterEventClass(eventClass); + + } } diff --git a/src/main/java/org/asteriskjava/manager/internal/ManagerUtil.java b/src/main/java/org/asteriskjava/manager/internal/ManagerUtil.java index 36181d7b5..545b9f18a 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerUtil.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerUtil.java @@ -18,40 +18,41 @@ /** * Utilitiy class with some static helper methods that are used in multiple - * contexts within the manager package.

      - * The methods for handling the internal action id are used to make sure we - * send unique ids to Asterisk even when the user of Asterisk-Java does not - * provide a unique action id or no action id at all.

      - * All the methods contained in this class are supposed to be internally - * only. - * + * contexts within the manager package. + *

      + * The methods for handling the internal action id are used to make sure we send + * unique ids to Asterisk even when the user of Asterisk-Java does not provide a + * unique action id or no action id at all. + *

      + * All the methods contained in this class are supposed to be internally only. + * * @author srt * @version $Id$ */ -public class ManagerUtil -{ +public class ManagerUtil { public static final char INTERNAL_ACTION_ID_DELIMITER = '#'; /** * The hex digits used to build a hex string representation of a byte array. */ - private static final char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', - '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + private static final char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + private ManagerUtil() { + + } /** * Converts a byte array to a hex string representing it. The hex digits are * lower case. - * + * * @param b the byte array to convert * @return the hex representation of b */ - public static String toHexString(byte[] b) - { + public static String toHexString(byte[] b) { final StringBuilder sb; - + sb = new StringBuilder(b.length * 2); - for (byte aB : b) - { + for (byte aB : b) { sb.append(hexChar[(aB & 0xf0) >>> 4]); sb.append(hexChar[aB & 0x0f]); } @@ -60,81 +61,60 @@ public static String toHexString(byte[] b) /** * Returns the internal action id contained in the given action id. - * - * @param actionId the action id prefixed by the internal action - * id as received from Asterisk. + * + * @param actionId the action id prefixed by the internal action id as + * received from Asterisk. * @return the internal action id that has been added before. * @see #addInternalActionId(String, String) */ - public static String getInternalActionId(String actionId) - { + public static String getInternalActionId(String actionId) { final int delimiterIndex; - if (actionId == null) - { + if (actionId == null) { return null; } - + delimiterIndex = actionId.indexOf(INTERNAL_ACTION_ID_DELIMITER); - if (delimiterIndex > 0) - { + if (delimiterIndex > 0) { return actionId.substring(0, delimiterIndex); } - else - { - return null; - } + return null; } /** * Strips the internal action id from the given action id. - * - * @param actionId the action id prefixed by the internal action - * id as received from Asterisk. + * + * @param actionId the action id prefixed by the internal action id as + * received from Asterisk. * @return the original action id, that is the action id as it was before - * the internal action id was added. + * the internal action id was added. * @see #addInternalActionId(String, String) */ - public static String stripInternalActionId(String actionId) - { + public static String stripInternalActionId(String actionId) { int delimiterIndex; delimiterIndex = actionId.indexOf(INTERNAL_ACTION_ID_DELIMITER); - if (delimiterIndex > 0) - { - if (actionId.length() > delimiterIndex + 1) - { + if (delimiterIndex > 0) { + if (actionId.length() > delimiterIndex + 1) { return actionId.substring(delimiterIndex + 1); } - else - { - return null; - } - } - else - { return null; } + return null; } /** * Adds the internal action id to the given action id. - * - * @param actionId the action id as set by the user. + * + * @param actionId the action id as set by the user. * @param internalActionId the internal action id to add. * @return the action id prefixed by the internal action id suitable to be - * sent to Asterisk. + * sent to Asterisk. */ - public static String addInternalActionId(String actionId, - String internalActionId) - { - if (actionId == null) - { + public static String addInternalActionId(String actionId, String internalActionId) { + if (actionId == null) { return internalActionId + INTERNAL_ACTION_ID_DELIMITER; } - else - { - return internalActionId + INTERNAL_ACTION_ID_DELIMITER + actionId; - } + return internalActionId + INTERNAL_ACTION_ID_DELIMITER + actionId; } } diff --git a/src/main/java/org/asteriskjava/manager/internal/ManagerWriter.java b/src/main/java/org/asteriskjava/manager/internal/ManagerWriter.java index c8d19e171..94d844870 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerWriter.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerWriter.java @@ -16,44 +16,43 @@ */ package org.asteriskjava.manager.internal; -import java.io.IOException; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.manager.action.ManagerAction; import org.asteriskjava.util.SocketConnectionFacade; +import java.io.IOException; + /** * The ManagerWriter transforms actions using an ActionBuilder and sends them to * the asterisk server.

      * This class is intended to be used only by the DefaultManagerConnection. - * - * @see org.asteriskjava.manager.internal.ActionBuilder - * @see org.asteriskjava.manager.DefaultManagerConnection + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.internal.ActionBuilder + * @see org.asteriskjava.manager.DefaultManagerConnection */ -public interface ManagerWriter -{ +public interface ManagerWriter { /** * Sets the version of the target Asterisk server. - * - * @param asteriskVersion the version of the target Asterisk server. + * + * @param targetVersion the version of the target Asterisk server. * @since 0.2 */ - public void setTargetVersion(AsteriskVersion targetVersion); + void setTargetVersion(AsteriskVersion targetVersion); /** * Sets the socket to use for writing to Asterisk. - * + * * @param socket the socket to use for writing to Asterisk. */ void setSocket(final SocketConnectionFacade socket); /** * Sends the given action to the asterisk server. - * - * @param action the action to send to the asterisk server. + * + * @param action the action to send to the asterisk server. * @param internalActionId the internal action id to add. * @throws IOException if there is a problem sending the action. */ diff --git a/src/main/java/org/asteriskjava/manager/internal/ManagerWriterImpl.java b/src/main/java/org/asteriskjava/manager/internal/ManagerWriterImpl.java index 3e321b430..d1d8f01e1 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerWriterImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerWriterImpl.java @@ -16,29 +16,29 @@ */ package org.asteriskjava.manager.internal; -import java.io.IOException; - import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.lock.Lockable; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.action.ManagerAction; import org.asteriskjava.util.SocketConnectionFacade; +import java.io.IOException; /** * Default implementation of ManagerWriter interface. - * + * * @author srt * @version $Id$ */ -public class ManagerWriterImpl implements ManagerWriter -{ +public class ManagerWriterImpl extends Lockable implements ManagerWriter { /** * Instance logger. */ - //private final Log logger = LogFactory.getLog(getClass()); + // private final Log logger = LogFactory.getLog(getClass()); /** - * The action builder utility to convert ManagerAction to a String suitable to be sent to the - * asterisk server. + * The action builder utility to convert ManagerAction to a String suitable + * to be sent to the asterisk server. */ private final ActionBuilder actionBuilder; @@ -47,36 +47,37 @@ public class ManagerWriterImpl implements ManagerWriter /** * Creates a new ManagerWriter. */ - public ManagerWriterImpl() - { + public ManagerWriterImpl() { this.actionBuilder = new ActionBuilderImpl(); } - public void setTargetVersion(AsteriskVersion version) - { + public void setTargetVersion(AsteriskVersion version) { actionBuilder.setTargetVersion(version); } - public synchronized void setSocket(final SocketConnectionFacade socket) - { - this.socket = socket; + public void setSocket(final SocketConnectionFacade socket) { + try (LockCloser closer = this.withLock()) { + this.socket = socket; + } } - public synchronized void sendAction(final ManagerAction action, final String internalActionId) throws IOException - { - final String actionString; + public void sendAction(final ManagerAction action, final String internalActionId) throws IOException { + try (LockCloser closer = this.withLock()) { + final String actionString; - if (socket == null) - { - throw new IllegalStateException("Unable to send action: socket is null"); - } + if (socket == null) { + throw new IllegalStateException("Unable to send action: socket is null"); + } - actionString = actionBuilder.buildAction(action, internalActionId); + actionString = actionBuilder.buildAction(action, internalActionId); - socket.write(actionString); - socket.flush(); + socket.write(actionString); + socket.flush(); - // TODO tracing - //logger.debug("Sent " + action.getAction() + " action with actionId '" + action.getActionId() + "':\n" + actionString); + // TODO tracing + // logger.debug("Sent " + action.getAction() + " action with + // actionId '" + // + action.getActionId() + "':\n" + actionString); + } } } diff --git a/src/main/java/org/asteriskjava/manager/internal/ProtocolIdentifierWrapper.java b/src/main/java/org/asteriskjava/manager/internal/ProtocolIdentifierWrapper.java new file mode 100644 index 000000000..4f9f5b09a --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/internal/ProtocolIdentifierWrapper.java @@ -0,0 +1,28 @@ +package org.asteriskjava.manager.internal; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +class ProtocolIdentifierWrapper { + private volatile CountDownLatch latch = new CountDownLatch(1); + private String value; + + void reset() { + value = null; + latch = new CountDownLatch(1); + } + + boolean await(long timeout) throws InterruptedException { + return latch.await(timeout, TimeUnit.MILLISECONDS); + } + + String getValue() { + return value; + } + + public void setValue(String identifier) { + value = identifier; + latch.countDown(); + + } +} diff --git a/src/main/java/org/asteriskjava/manager/internal/ResponseBuilder.java b/src/main/java/org/asteriskjava/manager/internal/ResponseBuilder.java index 8ede4237c..b3c940409 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ResponseBuilder.java +++ b/src/main/java/org/asteriskjava/manager/internal/ResponseBuilder.java @@ -16,10 +16,10 @@ */ package org.asteriskjava.manager.internal; -import java.util.Map; - import org.asteriskjava.manager.response.ManagerResponse; +import java.util.Map; + /** * Transforms maps of attributes to instances of ManagerResponse. @@ -28,8 +28,7 @@ * @version $Id$ * @see org.asteriskjava.manager.response.ManagerResponse */ -interface ResponseBuilder -{ +interface ResponseBuilder { /** * Constructs an instance of ManagerResponse based on a map of attributes. * diff --git a/src/main/java/org/asteriskjava/manager/internal/ResponseBuilderImpl.java b/src/main/java/org/asteriskjava/manager/internal/ResponseBuilderImpl.java index a07074515..c0a0b9371 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ResponseBuilderImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ResponseBuilderImpl.java @@ -1,93 +1,100 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.manager.internal; -import java.util.*; - -import org.asteriskjava.manager.response.*; +import org.asteriskjava.manager.response.CommandResponse; +import org.asteriskjava.manager.response.ManagerError; +import org.asteriskjava.manager.response.ManagerResponse; +import org.asteriskjava.manager.util.EventAttributesHelper; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; +import java.util.*; /** * Default implementation of the ResponseBuilder interface. - * - * @see org.asteriskjava.manager.response.ManagerResponse + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.response.ManagerResponse */ -class ResponseBuilderImpl extends AbstractBuilder implements ResponseBuilder -{ - private static final Set ignoredAttributes = new HashSet(Arrays.asList( - "attributes", "proxyresponse", ManagerReader.COMMAND_RESULT_RESPONSE_KEY)); +class ResponseBuilderImpl implements ResponseBuilder { + private static final Log logger = LogFactory.getLog(ResponseBuilderImpl.class); + + private static final Set ignoredAttributes = new HashSet<>(Arrays.asList( + "attributes", "proxyresponse", ManagerReader.COMMAND_RESULT_RESPONSE_KEY)); private static final String RESPONSE_KEY = "response"; private static final String PROXY_RESPONSE_KEY = "proxyresponse"; private static final String RESPONSE_TYPE_ERROR = "error"; + private static final String OUTPUT_RESPONSE_KEY = "output"; //Asterisk 14.3.0 - public ManagerResponse buildResponse(Class responseClass, Map attributes) - { + @SuppressWarnings("unchecked") + public ManagerResponse buildResponse(Class responseClass, Map attributes) { final ManagerResponse response; final String responseType = (String) attributes.get(RESPONSE_KEY); - if (RESPONSE_TYPE_ERROR.equalsIgnoreCase(responseType)) - { + if (RESPONSE_TYPE_ERROR.equalsIgnoreCase(responseType)) { response = new ManagerError(); - } - else if (responseClass == null) - { + } else if (responseClass == null) { response = new ManagerResponse(); - } - else - { - try - { - response = responseClass.newInstance(); - } - catch (Exception ex) - { + } else { + try { + response = responseClass.getDeclaredConstructor().newInstance(); + } catch (Exception ex) { logger.error("Unable to create new instance of " + responseClass.getName(), ex); return null; } } - setAttributes(response, attributes, ignoredAttributes); + EventAttributesHelper.setAttributes(response, attributes, ignoredAttributes); - if (response instanceof CommandResponse) - { + if (response instanceof CommandResponse) { final CommandResponse commandResponse = (CommandResponse) response; - final List result = new ArrayList(); - for (String resultLine : ((String) attributes.get(ManagerReader.COMMAND_RESULT_RESPONSE_KEY)).split("\n")) - { - // on error there is a leading space - if (!resultLine.equals("--END COMMAND--") && !resultLine.equals(" --END COMMAND--")) - { - result.add(resultLine); + final List result = new ArrayList<>(); + //For Asterisk 14 + if (attributes.get(OUTPUT_RESPONSE_KEY) != null) { + if (attributes.get(OUTPUT_RESPONSE_KEY) instanceof List) { + for (String tmp : (List) attributes.get(OUTPUT_RESPONSE_KEY)) { + if (tmp != null && tmp.length() != 0) { + result.add(tmp.trim()); + } + } + } else { + result.add((String) attributes.get(OUTPUT_RESPONSE_KEY)); + } + + } else { + for (String resultLine : ((String) attributes.get(ManagerReader.COMMAND_RESULT_RESPONSE_KEY)).split("\n")) { + // on error there is a leading space + if (!resultLine.equals("--END COMMAND--") && !resultLine.equals(" --END COMMAND--")) { + result.add(resultLine); + } } } commandResponse.setResult(result); } - if (response.getResponse() != null && attributes.get(PROXY_RESPONSE_KEY) != null) - { + if (response.getResponse() != null && attributes.get(PROXY_RESPONSE_KEY) != null) { response.setResponse((String) attributes.get(PROXY_RESPONSE_KEY)); } // make the map of all attributes available to the response // but clone it as it is reused by the ManagerReader - response.setAttributes(new HashMap(attributes)); + response.setAttributes(new HashMap<>(attributes)); return response; } diff --git a/src/main/java/org/asteriskjava/manager/internal/ResponseEventsImpl.java b/src/main/java/org/asteriskjava/manager/internal/ResponseEventsImpl.java index bb5e983b0..7507f7598 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ResponseEventsImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ResponseEventsImpl.java @@ -16,50 +16,49 @@ */ package org.asteriskjava.manager.internal; -import java.util.ArrayList; -import java.util.Collection; - +import org.asteriskjava.lock.LockableList; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.ResponseEvents; import org.asteriskjava.manager.event.ResponseEvent; import org.asteriskjava.manager.response.ManagerResponse; +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; /** * Implementation of the ResponseEvents interface. - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class ResponseEventsImpl implements ResponseEvents -{ +public class ResponseEventsImpl implements ResponseEvents { private ManagerResponse response; - private final Collection events; + private final LockableList events; private boolean complete; + private final CountDownLatch latch = new CountDownLatch(1); /** * Creates a new instance. */ - public ResponseEventsImpl() - { - this.events = new ArrayList(); + public ResponseEventsImpl() { + this.events = new LockableList<>(new ArrayList<>()); this.complete = false; } // implementation of the ResponseEvents interface - public ManagerResponse getResponse() - { + public ManagerResponse getResponse() { return response; } - public Collection getEvents() - { + public Collection getEvents() { return events; } - public boolean isComplete() - { + public boolean isComplete() { return complete; } @@ -67,35 +66,49 @@ public boolean isComplete() /** * Sets the ManagerResponse received. - * + * * @param response the ManagerResponse received. */ - public void setRepsonse(ManagerResponse response) - { + public void setRepsonse(ManagerResponse response) { this.response = response; } /** * Adds a ResponseEvent that has been received. - * + * * @param event the ResponseEvent that has been received. */ - public void addEvent(ResponseEvent event) - { - synchronized (events) - { + public void addEvent(ResponseEvent event) { + try (LockCloser closer = events.withLock()) { events.add(event); } } /** - * Indicats if all events have been received. - * + * Indicates if all events have been received. + * * @param complete true if all events have been received, - * false otherwise. + * false otherwise. */ - public void setComplete(boolean complete) - { + public void setComplete(boolean complete) { this.complete = complete; } + + /** + * @param timeout - milliseconds + * @return + * @throws InterruptedException + */ + public boolean await(long timeout) throws InterruptedException { + return latch.await(timeout, TimeUnit.MILLISECONDS); + } + + public void countDown() { + latch.countDown(); + } + + @Override + public String toString() { + return "ResponseEventsImpl [response=" + response + ",\nevents=" + events + ",\ncomplete=" + complete + "]"; + } } diff --git a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/BackwardsCompatibilityForManagerEvents.java b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/BackwardsCompatibilityForManagerEvents.java new file mode 100644 index 000000000..51d6b3a15 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/BackwardsCompatibilityForManagerEvents.java @@ -0,0 +1,20 @@ +package org.asteriskjava.manager.internal.backwardsCompatibility; + +import org.asteriskjava.manager.event.ManagerEvent; +import org.asteriskjava.manager.internal.backwardsCompatibility.bridge.BridgesActive; +import org.asteriskjava.manager.internal.backwardsCompatibility.meetme.MeetmeCompatibility; + +public class BackwardsCompatibilityForManagerEvents { + // Logger logger = LogManager.getLogger(); + BridgesActive bridges = new BridgesActive(); + MeetmeCompatibility meetme = new MeetmeCompatibility(); + + public ManagerEvent handleEvent(ManagerEvent event) { + ManagerEvent newEvent = bridges.handleEvent(event); + if (newEvent == null) { + newEvent = meetme.handleEvent(event); + } + return newEvent; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparator.java b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparator.java new file mode 100644 index 000000000..cd4ca0c36 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparator.java @@ -0,0 +1,52 @@ +/* + * Copyright 2018 Marcin Turek + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.internal.backwardsCompatibility.bridge; + +import org.asteriskjava.manager.event.BridgeEnterEvent; + +import java.util.Comparator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class BridgeEnterEventComparator implements Comparator { + private static final Pattern UNIQUE_ID_PATTERN = Pattern.compile("([0-9]+)\\.([0-9]+)$"); + + @Override + public int compare(BridgeEnterEvent o1, BridgeEnterEvent o2) { + Matcher uniqueId1Matcher = UNIQUE_ID_PATTERN.matcher(o1.getUniqueId()); + Matcher uniqueId2Matcher = UNIQUE_ID_PATTERN.matcher(o2.getUniqueId()); + + boolean find1 = uniqueId1Matcher.find(); + boolean find2 = uniqueId2Matcher.find(); + + if (find1 && find2) { + // 1501234567.890 -> epochtime: 1501234567 | serial: 890 + long epochtime1 = Long.valueOf(uniqueId1Matcher.group(1)); + long epochtime2 = Long.valueOf(uniqueId2Matcher.group(1)); + int serial1 = Integer.valueOf(uniqueId1Matcher.group(2)); + int serial2 = Integer.valueOf(uniqueId2Matcher.group(2)); + + return epochtime1 == epochtime2 ? Integer.compare(serial1, serial2) : Long.compare(epochtime1, epochtime2); + } else if (!find1 && !find2) { + // Both of inputs are invalid value: id1 == id2 + return 0; + } else { + // id1 is valid ==> 1 + return find1 ? 1 : -1; + } + } +} diff --git a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeState.java b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeState.java new file mode 100644 index 000000000..cc6d071c1 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeState.java @@ -0,0 +1,118 @@ +package org.asteriskjava.manager.internal.backwardsCompatibility.bridge; + +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.manager.event.BridgeEnterEvent; +import org.asteriskjava.manager.event.BridgeEvent; +import org.asteriskjava.manager.event.BridgeLeaveEvent; +import org.asteriskjava.manager.event.ManagerEvent; +import org.asteriskjava.util.DateUtil; + +import java.util.*; + +/** + * Track the current members of a bridge, emmitting BridgeEvents when 2 members + * join or breakup + * + * @author rsutton + */ +class BridgeState { + // private final Log logger = LogFactory.getLog(getClass()); + + private static final BridgeEnterEventComparator BRIDGE_ENTER_EVENT_COMPARATOR = new BridgeEnterEventComparator(); + private static final String HOLDING_BRIDGE_TECH = "holding_bridge"; + + private final LockableMap members = new LockableMap<>(new HashMap<>()); + + ManagerEvent destroy() { + try (LockCloser closer = members.withLock()) { + members.clear(); + } + return null; + } + + /** + * if there are exactly 2 members in the bridge, return a BridgeEvent + * + * @param event + * @return + */ + ManagerEvent addMember(BridgeEnterEvent event) { + List remaining = null; + + if (HOLDING_BRIDGE_TECH.equals(event.getBridgeTechnology())) { + /* channels in a holding bridge aren't bridged to one another */ + return null; + } + + try (LockCloser closer = members.withLock()) { + if (members.put(event.getChannel(), event) == null && members.size() == 2) { + remaining = new ArrayList<>(members.values()); + } + } + + if (remaining == null) { + return null; + } + + // logger.info("Members size " + remaining.size() + " " + event); + + BridgeEvent bridgeEvent = buildBridgeEvent(BridgeEvent.BRIDGE_STATE_LINK, remaining); + + // logger.info("Bridge " + bridgeEvent.getChannel1() + " " + + // bridgeEvent.getChannel2()); + + return bridgeEvent; + } + + /** + * If there are exactly 2 members in the bridge, return a BridgeEvent + * + * @param event + * @return + */ + + ManagerEvent removeMember(BridgeLeaveEvent event) { + List remaining = new LinkedList<>(); + + if (HOLDING_BRIDGE_TECH.equals(event.getBridgeTechnology())) { + /* channels in a holding bridge aren't bridged to one another */ + return null; + } + + try (LockCloser closer = members.withLock()) { + remaining.addAll(members.values()); + + if (members.remove(event.getChannel()) != null) { + if (remaining.size() == 2) { + return buildBridgeEvent(BridgeEvent.BRIDGE_STATE_UNLINK, remaining); + } + } + } + + // If we didn't remove anything, or we aren't at exactly 2 members, + // there's nothing else for us to do + + return null; + + } + + private BridgeEvent buildBridgeEvent(String bridgeState, List members) { + Collections.sort(members, BRIDGE_ENTER_EVENT_COMPARATOR); + + BridgeEvent bridgeEvent = new BridgeEvent(this); + + bridgeEvent.setCallerId1(members.get(0).getCallerIdNum()); + bridgeEvent.setUniqueId1(members.get(0).getUniqueId()); + bridgeEvent.setChannel1(members.get(0).getChannel()); + + bridgeEvent.setCallerId2(members.get(1).getCallerIdNum()); + bridgeEvent.setUniqueId2(members.get(1).getUniqueId()); + bridgeEvent.setChannel2(members.get(1).getChannel()); + + bridgeEvent.setBridgeState(bridgeState); + bridgeEvent.setDateReceived(DateUtil.getDate()); + + return bridgeEvent; + } +} diff --git a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgesActive.java b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgesActive.java new file mode 100644 index 000000000..d91f9cba5 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgesActive.java @@ -0,0 +1,70 @@ +package org.asteriskjava.manager.internal.backwardsCompatibility.bridge; + +import org.asteriskjava.manager.event.*; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * Backwards compatibility for bridge events.
      + *
      + * Asterisk 13 uses BridgeCreate, BridgeEnter, BridgeLeave and BridgeDestroy + * events.
      + *
      + * Here we track active bridges and simulate BridgeEvent's for them allowing + * legacy code to still work with BridgeEvent's + * + * @author rsutton + */ +public class BridgesActive { + private final Log logger = LogFactory.getLog(BridgesActive.class); + + private final ConcurrentMap activeBridges = new ConcurrentHashMap<>(); + + public ManagerEvent handleEvent(ManagerEvent event) { + if (event instanceof BridgeCreateEvent) { + return createBridge((BridgeCreateEvent) event); + } else if (event instanceof BridgeDestroyEvent) { + return destroyBridge((BridgeDestroyEvent) event); + } else if (event instanceof BridgeEnterEvent) { + return enterBridge((BridgeEnterEvent) event); + } else if (event instanceof BridgeLeaveEvent) { + return leaveBridge((BridgeLeaveEvent) event); + } + return null; + } + + ManagerEvent createBridge(BridgeCreateEvent event) { + activeBridges.putIfAbsent(event.getBridgeUniqueId(), new BridgeState()); + return null; + } + + ManagerEvent destroyBridge(BridgeDestroyEvent event) { + BridgeState state = activeBridges.remove(event.getBridgeUniqueId()); + if (state != null) { + return state.destroy(); + } + logger.info("Cant find bridge for id " + event.getBridgeUniqueId()); + return null; + } + + ManagerEvent enterBridge(BridgeEnterEvent event) { + BridgeState state = activeBridges.get(event.getBridgeUniqueId()); + if (state != null) { + return state.addMember(event); + } + logger.error("Cant find bridge for id " + event.getBridgeUniqueId()); + return null; + } + + ManagerEvent leaveBridge(BridgeLeaveEvent event) { + BridgeState state = activeBridges.get(event.getBridgeUniqueId()); + if (state != null) { + return state.removeMember(event); + } + logger.info("Cant find bridge for id " + event.getBridgeUniqueId()); + return null; + } +} diff --git a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/meetme/MeetmeCompatibility.java b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/meetme/MeetmeCompatibility.java new file mode 100644 index 000000000..3aea7b3af --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/meetme/MeetmeCompatibility.java @@ -0,0 +1,50 @@ +package org.asteriskjava.manager.internal.backwardsCompatibility.meetme; + +import org.asteriskjava.manager.event.*; + +/** + * Backwards compatibility for bridge events.
      + *
      + * Asterisk 13 uses BridgeCreate, BridgeEnter, BridgeLeave and BridgeDestroy + * events.
      + *
      + * Here we track active bridges and simulate BridgeEvent's for them allowing + * legacy code to still work with BridgeEvent's + * + * @author rsutton + */ +public class MeetmeCompatibility { + + public ManagerEvent handleEvent(ManagerEvent event) { + if (event instanceof ConfbridgeStartEvent) { + } else if (event instanceof ConfbridgeEndEvent) { + MeetMeEndEvent endEvent = new MeetMeEndEvent(this); + endEvent.setDateReceived(event.getDateReceived()); + endEvent.setMeetMe(((ConfbridgeEndEvent) event).getConference()); + return endEvent; + } else if (event instanceof ConfbridgeJoinEvent) { + MeetMeJoinEvent joinEvent = new MeetMeJoinEvent(this); + joinEvent.setCallerIdNum(event.getCallerIdNum()); + joinEvent.setCallerIdName(event.getCallerIdName()); + joinEvent.setUniqueId(((ConfbridgeJoinEvent) event).getUniqueId()); + joinEvent.setChannel(((ConfbridgeJoinEvent) event).getChannel()); + joinEvent.setMeetMe(((ConfbridgeJoinEvent) event).getBridgeName()); + joinEvent.setDateReceived(event.getDateReceived()); + + return joinEvent; + } else if (event instanceof ConfbridgeLeaveEvent) { + MeetMeLeaveEvent leaveEvent = new MeetMeLeaveEvent(this); + leaveEvent.setCallerIdNum(event.getCallerIdNum()); + leaveEvent.setCallerIdName(event.getCallerIdName()); + leaveEvent.setUniqueId(((ConfbridgeLeaveEvent) event).getUniqueId()); + leaveEvent.setChannel(((ConfbridgeLeaveEvent) event).getChannel()); + leaveEvent.setMeetMe(((ConfbridgeLeaveEvent) event).getConference()); + leaveEvent.setDateReceived(event.getDateReceived()); + + return leaveEvent; + } + return null; + + } + +} diff --git a/src/main/java/org/asteriskjava/manager/internal/package.html b/src/main/java/org/asteriskjava/manager/internal/package.html index 18114dfdd..138b830df 100644 --- a/src/main/java/org/asteriskjava/manager/internal/package.html +++ b/src/main/java/org/asteriskjava/manager/internal/package.html @@ -1,28 +1,28 @@ - +

      Provides private implementations for interfaces defined in the - org.asteriskjava.manager package.

      + org.asteriskjava.manager package.

      - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/manager/package.html b/src/main/java/org/asteriskjava/manager/package.html index 706dd9aa2..5f40b682e 100644 --- a/src/main/java/org/asteriskjava/manager/package.html +++ b/src/main/java/org/asteriskjava/manager/package.html @@ -1,27 +1,27 @@ - +

      Provides an implementaion of Asterisk's Manager API.

      - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/manager/response/ChallengeResponse.java b/src/main/java/org/asteriskjava/manager/response/ChallengeResponse.java index 0727fb552..662668784 100644 --- a/src/main/java/org/asteriskjava/manager/response/ChallengeResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/ChallengeResponse.java @@ -25,8 +25,7 @@ * @see org.asteriskjava.manager.action.ChallengeAction * @see org.asteriskjava.manager.action.LoginAction */ -public class ChallengeResponse extends ManagerResponse -{ +public class ChallengeResponse extends ManagerResponse { private static final long serialVersionUID = -7253724086340850957L; private String challenge; @@ -37,13 +36,11 @@ public class ChallengeResponse extends ManagerResponse * @return the challenge to use when creating the key for log in. * @see org.asteriskjava.manager.action.LoginAction#setKey(String) */ - public String getChallenge() - { + public String getChallenge() { return challenge; } - public void setChallenge(String challenge) - { + public void setChallenge(String challenge) { this.challenge = challenge; } } diff --git a/src/main/java/org/asteriskjava/manager/response/CommandResponse.java b/src/main/java/org/asteriskjava/manager/response/CommandResponse.java index f0a33baa9..f1e640dde 100644 --- a/src/main/java/org/asteriskjava/manager/response/CommandResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/CommandResponse.java @@ -24,14 +24,12 @@ * Follows" line followed by the raw output of the command including empty lines. At the end of the * command output a line containing "--END COMMAND--" is sent. The reader parses this response into * a CommandResponse object to hide these details. - * - * @see org.asteriskjava.manager.action.CommandAction - * + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.CommandAction */ -public class CommandResponse extends ManagerResponse -{ +public class CommandResponse extends ManagerResponse { private static final long serialVersionUID = 1L; private String privilege; @@ -43,13 +41,11 @@ public class CommandResponse extends ManagerResponse * @return always "Command" * @since 1.0.0 */ - public String getPrivilege() - { + public String getPrivilege() { return privilege; } - public void setPrivilege(String privilege) - { + public void setPrivilege(String privilege) { this.privilege = privilege; } @@ -58,16 +54,14 @@ public void setPrivilege(String privilege) * * @return a List of strings representing the lines returned by the CLI command. */ - public List getResult() - { + public List getResult() { return result; } /** * Sets the result. */ - public void setResult(List result) - { + public void setResult(List result) { this.result = result; } } diff --git a/src/main/java/org/asteriskjava/manager/response/CoreSettingsResponse.java b/src/main/java/org/asteriskjava/manager/response/CoreSettingsResponse.java index cd06a0f82..a61b9f2ea 100644 --- a/src/main/java/org/asteriskjava/manager/response/CoreSettingsResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/CoreSettingsResponse.java @@ -25,8 +25,7 @@ * @see org.asteriskjava.manager.action.CoreSettingsAction * @since 1.0.0 */ -public class CoreSettingsResponse extends ManagerResponse -{ +public class CoreSettingsResponse extends ManagerResponse { private static final long serialVersionUID = 1L; private String amiVersion; @@ -40,19 +39,18 @@ public class CoreSettingsResponse extends ManagerResponse private Boolean coreRealtimeEnabled; private Boolean coreCdrEnabled; private Boolean coreHttpEnabled; + private Boolean soundsSearchCustomDir; /** * Returns the version of the Asterisk Manager Interface (AMI). For Asterisk 1.6 this is "1.1". * * @return the version of the Asterisk Manager Interface (AMI). */ - public String getAmiVersion() - { + public String getAmiVersion() { return amiVersion; } - public void setAmiVersion(String amiVersion) - { + public void setAmiVersion(String amiVersion) { this.amiVersion = amiVersion; } @@ -61,73 +59,59 @@ public void setAmiVersion(String amiVersion) * * @return the version of the Asterisk server. */ - public String getAsteriskVersion() - { + public String getAsteriskVersion() { return asteriskVersion; } - public void setAsteriskVersion(String asteriskVersion) - { + public void setAsteriskVersion(String asteriskVersion) { this.asteriskVersion = asteriskVersion; } - public String getSystemName() - { + public String getSystemName() { return systemName; } - public void setSystemName(String systemName) - { + public void setSystemName(String systemName) { this.systemName = systemName; } - public Integer getCoreMaxCalls() - { + public Integer getCoreMaxCalls() { return coreMaxCalls; } - public void setCoreMaxCalls(Integer coreMaxCalls) - { + public void setCoreMaxCalls(Integer coreMaxCalls) { this.coreMaxCalls = coreMaxCalls; } - public Double getCoreMaxLoadAvg() - { + public Double getCoreMaxLoadAvg() { return coreMaxLoadAvg; } - public void setCoreMaxLoadAvg(Double coreMaxLoadAvg) - { + public void setCoreMaxLoadAvg(Double coreMaxLoadAvg) { this.coreMaxLoadAvg = coreMaxLoadAvg; } - public String getCoreRunUser() - { + public String getCoreRunUser() { return coreRunUser; } - public void setCoreRunUser(String coreRunUser) - { + public void setCoreRunUser(String coreRunUser) { this.coreRunUser = coreRunUser; } - public String getCoreRunGroup() - { + public String getCoreRunGroup() { return coreRunGroup; } - public void setCoreRunGroup(String coreRunGroup) - { + public void setCoreRunGroup(String coreRunGroup) { this.coreRunGroup = coreRunGroup; } - public Integer getCoreMaxFilehandles() - { + public Integer getCoreMaxFilehandles() { return coreMaxFilehandles; } - public void setCoreMaxFilehandles(Integer coreMaxFilehandles) - { + public void setCoreMaxFilehandles(Integer coreMaxFilehandles) { this.coreMaxFilehandles = coreMaxFilehandles; } @@ -136,13 +120,11 @@ public void setCoreMaxFilehandles(Integer coreMaxFilehandles) * * @return true if the realtime subsystem is enabled, false otherwise. */ - public boolean isCoreRealtimeEnabled() - { + public boolean isCoreRealtimeEnabled() { return coreRealtimeEnabled != null && coreRealtimeEnabled; } - public void setCoreRealtimeEnabled(Boolean coreRealtimeEnabled) - { + public void setCoreRealtimeEnabled(Boolean coreRealtimeEnabled) { this.coreRealtimeEnabled = coreRealtimeEnabled; } @@ -151,13 +133,11 @@ public void setCoreRealtimeEnabled(Boolean coreRealtimeEnabled) * * @return true if the CDR subsystem is enabled, false otherwise. */ - public boolean isCoreCdrEnabled() - { + public boolean isCoreCdrEnabled() { return coreCdrEnabled != null && coreCdrEnabled; } - public void setCoreCdrEnabled(Boolean coreCdrEnabled) - { + public void setCoreCdrEnabled(Boolean coreCdrEnabled) { this.coreCdrEnabled = coreCdrEnabled; } @@ -166,13 +146,19 @@ public void setCoreCdrEnabled(Boolean coreCdrEnabled) * * @return true if the HTTP subsystem is enabled, false otherwise. */ - public boolean isCoreHttpEnabled() - { + public boolean isCoreHttpEnabled() { return coreHttpEnabled != null && coreHttpEnabled; } - public void setCoreHttpEnabled(Boolean coreHttpEnabled) - { + public void setCoreHttpEnabled(Boolean coreHttpEnabled) { this.coreHttpEnabled = coreHttpEnabled; } -} \ No newline at end of file + + public boolean isSoundsSearchCustomDir() { + return soundsSearchCustomDir != null && soundsSearchCustomDir; + } + + public void setSoundsSearchCustomDir(Boolean soundsSearchCustomDir) { + this.soundsSearchCustomDir = soundsSearchCustomDir; + } +} diff --git a/src/main/java/org/asteriskjava/manager/response/CoreStatusResponse.java b/src/main/java/org/asteriskjava/manager/response/CoreStatusResponse.java index 9e78dde1e..cc2f8237a 100644 --- a/src/main/java/org/asteriskjava/manager/response/CoreStatusResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/CoreStatusResponse.java @@ -16,11 +16,11 @@ */ package org.asteriskjava.manager.response; +import org.asteriskjava.util.DateUtil; + import java.util.Date; import java.util.TimeZone; -import org.asteriskjava.util.DateUtil; - /** * Corresponds to a CoreStatusAction and contains the current status summary of the * Asterisk server. @@ -30,8 +30,7 @@ * @see org.asteriskjava.manager.action.CoreStatusAction * @since 1.0.0 */ -public class CoreStatusResponse extends ManagerResponse -{ +public class CoreStatusResponse extends ManagerResponse { private static final long serialVersionUID = 1L; private String coreStartupTime; @@ -46,13 +45,11 @@ public class CoreStatusResponse extends ManagerResponse * * @return the time the server (core module) was last reloaded. */ - public String getCoreReloadTime() - { + public String getCoreReloadTime() { return coreReloadTime; } - public void setCoreReloadTime(String s) - { + public void setCoreReloadTime(String s) { // format is %H:%M:%S this.coreReloadTime = s; } @@ -63,13 +60,11 @@ public void setCoreReloadTime(String s) * * @return the date the server (core module) was last reloaded. */ - public String getCoreReloadDate() - { + public String getCoreReloadDate() { return coreReloadDate; } - public void setCoreReloadDate(String CoreReloadDate) - { + public void setCoreReloadDate(String CoreReloadDate) { this.coreReloadDate = CoreReloadDate; } @@ -83,8 +78,7 @@ public void setCoreReloadDate(String CoreReloadDate) * @see #getCoreReloadTime() * @see #getCoreReloadDateTimeAsDate(java.util.TimeZone) */ - public Date getCoreReloadDateTimeAsDate() - { + public Date getCoreReloadDateTimeAsDate() { return getCoreReloadDateTimeAsDate(null); } @@ -98,10 +92,8 @@ public Date getCoreReloadDateTimeAsDate() * @see #getCoreReloadDate() * @see #getCoreReloadTime() */ - public Date getCoreReloadDateTimeAsDate(TimeZone tz) - { - if (coreReloadDate == null || coreReloadTime == null) - { + public Date getCoreReloadDateTimeAsDate(TimeZone tz) { + if (coreReloadDate == null || coreReloadTime == null) { return null; } @@ -114,13 +106,11 @@ public Date getCoreReloadDateTimeAsDate(TimeZone tz) * * @return the date the server was started. */ - public String getCoreStartupDate() - { + public String getCoreStartupDate() { return coreStartupDate; } - public void setCoreStartupDate(String CoreStartupDate) - { + public void setCoreStartupDate(String CoreStartupDate) { this.coreStartupDate = CoreStartupDate; } @@ -129,13 +119,11 @@ public void setCoreStartupDate(String CoreStartupDate) * * @return the time the server was started. */ - public String getCoreStartupTime() - { + public String getCoreStartupTime() { return coreStartupTime; } - public void setCoreStartupTime(String s) - { + public void setCoreStartupTime(String s) { // format is %H:%M:%S this.coreStartupTime = s; } @@ -150,8 +138,7 @@ public void setCoreStartupTime(String s) * @see #getCoreStartupTime() * @see #getCoreStartupDateTimeAsDate(java.util.TimeZone) */ - public Date getCoreStartupDateTimeAsDate() - { + public Date getCoreStartupDateTimeAsDate() { return getCoreStartupDateTimeAsDate(null); } @@ -165,10 +152,8 @@ public Date getCoreStartupDateTimeAsDate() * @see #getCoreStartupDate() * @see #getCoreStartupTime() */ - public Date getCoreStartupDateTimeAsDate(TimeZone tz) - { - if (coreStartupDate == null || coreStartupTime == null) - { + public Date getCoreStartupDateTimeAsDate(TimeZone tz) { + if (coreStartupDate == null || coreStartupTime == null) { return null; } @@ -180,13 +165,11 @@ public Date getCoreStartupDateTimeAsDate(TimeZone tz) * * @return the number of currently active channels on the server. */ - public Integer getCoreCurrentCalls() - { + public Integer getCoreCurrentCalls() { return coreCurrentCalls; } - public void setCoreCurrentCalls(Integer coreCurrentCalls) - { + public void setCoreCurrentCalls(Integer coreCurrentCalls) { this.coreCurrentCalls = coreCurrentCalls; } } diff --git a/src/main/java/org/asteriskjava/manager/response/ExtensionStateResponse.java b/src/main/java/org/asteriskjava/manager/response/ExtensionStateResponse.java index 4b37365e4..e9afcb964 100644 --- a/src/main/java/org/asteriskjava/manager/response/ExtensionStateResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/ExtensionStateResponse.java @@ -17,66 +17,66 @@ package org.asteriskjava.manager.response; /** - * Response to an {@link org.asteriskjava.manager.action.ExtensionStateAction}. + * Response to an {@link org.asteriskjava.manager.action.ExtensionStateAction}. * * @author srt * @version $Id$ * @see org.asteriskjava.manager.action.ExtensionStateAction */ -public class ExtensionStateResponse extends ManagerResponse -{ +public class ExtensionStateResponse extends ManagerResponse { private static final long serialVersionUID = -2044248427247227390L; private String exten; private String context; private String hint; private Integer status; + private String statusText; - public String getExten() - { + public String getExten() { return exten; } - public void setExten(String exten) - { + public void setExten(String exten) { this.exten = exten; } - public String getContext() - { + public String getContext() { return context; } - public void setContext(String context) - { + public void setContext(String context) { this.context = context; } - public String getHint() - { + public String getHint() { return hint; } - public void setHint(String hint) - { + public void setHint(String hint) { this.hint = hint; } - public Integer getStatus() - { + public Integer getStatus() { return status; } - public void setStatus(Integer status) - { + public void setStatus(Integer status) { this.status = status; } + public String getStatusText() { + return statusText; + } + + public void setStatusText(String statusText) { + this.statusText = statusText; + } + + @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; - sb = new StringBuffer(getClass().getName() + ": "); + sb = new StringBuilder(getClass().getName() + ": "); sb.append("actionId='").append(getActionId()).append("'; "); sb.append("message='").append(getMessage()).append("'; "); sb.append("response='").append(getResponse()).append("'; "); @@ -85,6 +85,7 @@ public String toString() sb.append("context='").append(getContext()).append("'; "); sb.append("hint='").append(getHint()).append("'; "); sb.append("status='").append(getStatus()).append("'; "); + sb.append("statustext='").append(getStatusText()).append("'; "); sb.append("systemHashcode=").append(System.identityHashCode(this)); return sb.toString(); diff --git a/src/main/java/org/asteriskjava/manager/response/FaxLicenseStatusResponse.java b/src/main/java/org/asteriskjava/manager/response/FaxLicenseStatusResponse.java new file mode 100644 index 000000000..f7e91ef2e --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/response/FaxLicenseStatusResponse.java @@ -0,0 +1,13 @@ +package org.asteriskjava.manager.response; + +public final class FaxLicenseStatusResponse extends ManagerResponse { + private Integer portsLicensed; + + public Integer getPortsLicensed() { + return portsLicensed; + } + + public void setPortsLicensed(Integer portsLicensed) { + this.portsLicensed = portsLicensed; + } +} diff --git a/src/main/java/org/asteriskjava/manager/response/GetConfigResponse.java b/src/main/java/org/asteriskjava/manager/response/GetConfigResponse.java index 349355b73..0c1f20b26 100644 --- a/src/main/java/org/asteriskjava/manager/response/GetConfigResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/GetConfigResponse.java @@ -16,10 +16,10 @@ */ package org.asteriskjava.manager.response; +import java.util.Locale; import java.util.Map; -import java.util.Set; +import java.util.Map.Entry; import java.util.TreeMap; -import java.util.Locale; /** * Response that is received when sending a GetConfigAction. @@ -29,37 +29,32 @@ * the ugly details. If the file requested exists but does not contain at least * a line with a category, the ResponseBuilder won't create an instance of * GetConfigResponse, as it won't know what the empty response is. - * - * @see org.asteriskjava.manager.action.GetConfigAction + * * @author martins + * @see org.asteriskjava.manager.action.GetConfigAction * @since 0.3 */ -public class GetConfigResponse extends ManagerResponse -{ +public class GetConfigResponse extends ManagerResponse { private static final long serialVersionUID = -2044248427247227390L; - + private Map categories; private Map> lines; /** * Returns the map of category numbers to category names. - * + * * @return the map of category numbers to names. * @see org.asteriskjava.manager.response.GetConfigResponse#getLines */ - public Map getCategories() - { - if (categories == null) - { - categories = new TreeMap(); + public Map getCategories() { + if (categories == null) { + categories = new TreeMap<>(); } Map responseMap = super.getAttributes(); - Set responseKeys = responseMap.keySet(); - for (String key : responseKeys) - { - if (key.toLowerCase(Locale.US).contains("category")) - { + for (Entry response : responseMap.entrySet()) { + String key = response.getKey(); + if (key.toLowerCase(Locale.ENGLISH).contains("category")) { String[] keyParts = key.split("-"); // if it doesn't have at least category-XXXXXX, skip @@ -68,16 +63,13 @@ public Map getCategories() // try to get the number of this category, skip if we mess up Integer categoryNumber; - try - { + try { categoryNumber = Integer.parseInt(keyParts[1]); - } - catch (Exception exception) - { + } catch (Exception exception) { continue; } - categories.put(categoryNumber, (String) responseMap.get(key)); + categories.put(categoryNumber, (String) response.getValue()); } } @@ -86,65 +78,52 @@ public Map getCategories() /** * Returns the map of line number to line value for a given category. - * + * * @param categoryNumber a valid category number from getCategories. * @return the map of category numbers to names. * @see org.asteriskjava.manager.response.GetConfigResponse#getCategories */ - public Map getLines(int categoryNumber) - { - if (lines == null) - { - lines = new TreeMap>(); + public Map getLines(int categoryNumber) { + if (lines == null) { + lines = new TreeMap<>(); } Map responseMap = super.getAttributes(); - Set responseKeys = responseMap.keySet(); - for (String key : responseKeys) - { - if (key.toLowerCase(Locale.US).contains("line")) - { + for (Entry response : responseMap.entrySet()) { + String key = response.getKey(); + if (key.toLowerCase(Locale.ENGLISH).contains("line")) { String[] keyParts = key.split("-"); // if it doesn't have at least line-XXXXXX-XXXXXX, skip - if (keyParts.length < 3) - { + if (keyParts.length < 3) { continue; } // try to get the number of this category, skip if we mess up Integer potentialCategoryNumber; - try - { + try { potentialCategoryNumber = Integer.parseInt(keyParts[1]); - } - catch (Exception exception) - { + } catch (Exception exception) { continue; } // try to get the number of this line, skip if we mess up Integer potentialLineNumber; - try - { + try { potentialLineNumber = Integer.parseInt(keyParts[2]); - } - catch (Exception exception) - { + } catch (Exception exception) { continue; } // get the List out for placing stuff in Map linesForCategory = lines.get(potentialCategoryNumber); - if (linesForCategory == null) - { - linesForCategory = new TreeMap(); + if (linesForCategory == null) { + linesForCategory = new TreeMap<>(); } // put the line we just parsed into the line map for this category - linesForCategory.put(potentialLineNumber, (String) responseMap.get(key)); - if (!lines.containsKey(potentialCategoryNumber)) - { + linesForCategory.put(potentialLineNumber, (String) response.getValue()); + if (!lines.containsKey(potentialCategoryNumber)) { lines.put(potentialCategoryNumber, linesForCategory); } } diff --git a/src/main/java/org/asteriskjava/manager/response/GetVarResponse.java b/src/main/java/org/asteriskjava/manager/response/GetVarResponse.java index ba862d475..8758a6da7 100644 --- a/src/main/java/org/asteriskjava/manager/response/GetVarResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/GetVarResponse.java @@ -24,8 +24,7 @@ * @see org.asteriskjava.manager.action.GetVarAction * @since 1.0.0 */ -public class GetVarResponse extends ManagerResponse -{ +public class GetVarResponse extends ManagerResponse { private static final long serialVersionUID = 1L; private String variable; @@ -36,8 +35,7 @@ public class GetVarResponse extends ManagerResponse * * @return the name of the requested variable. */ - public String getVariable() - { + public String getVariable() { return variable; } @@ -46,8 +44,7 @@ public String getVariable() * * @param variable the name of the requested variable. */ - public void setVariable(String variable) - { + public void setVariable(String variable) { this.variable = variable; } @@ -56,8 +53,7 @@ public void setVariable(String variable) * * @return the value of the requested variable. */ - public String getValue() - { + public String getValue() { return value; } @@ -66,8 +62,7 @@ public String getValue() * * @param value the value of the requested variable. */ - public void setValue(String value) - { + public void setValue(String value) { this.value = value; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/response/MailboxCountResponse.java b/src/main/java/org/asteriskjava/manager/response/MailboxCountResponse.java index 24db2e53e..5e1469769 100644 --- a/src/main/java/org/asteriskjava/manager/response/MailboxCountResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/MailboxCountResponse.java @@ -19,67 +19,74 @@ /** * A MailboxCountResponse is sent in response to a MailboxCountAction and contains the number of old * and new messages in a mailbox. - * - * @see org.asteriskjava.manager.action.MailboxCountAction - * + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.MailboxCountAction */ -public class MailboxCountResponse extends ManagerResponse -{ +public class MailboxCountResponse extends ManagerResponse { /** * Serial version identifier */ - private static final long serialVersionUID = 7820598941277275838L; + private static final long serialVersionUID = 1408614199035675323L; private String mailbox; + private Integer urgMessages; private Integer newMessages; private Integer oldMessages; /** * Returns the name of the mailbox. */ - public String getMailbox() - { + public String getMailbox() { return mailbox; } /** * Sets the name of the mailbox. */ - public void setMailbox(String mailbox) - { + public void setMailbox(String mailbox) { this.mailbox = mailbox; } + /** + * Returns the number of urgent messages in the mailbox. + */ + public Integer getUrgMessages() { + return urgMessages; + } + + /** + * Sets the number of urgent messages in the mailbox. + */ + public void setUrgMessages(Integer urgMessages) { + this.urgMessages = urgMessages; + } + /** * Returns the number of new messages in the mailbox. */ - public Integer getNewMessages() - { + public Integer getNewMessages() { return newMessages; } /** * Sets the number of new messages in the mailbox. */ - public void setNewMessages(Integer newMessages) - { + public void setNewMessages(Integer newMessages) { this.newMessages = newMessages; } /** * Returns the number of old messages in the mailbox. */ - public Integer getOldMessages() - { + public Integer getOldMessages() { return oldMessages; } /** * Sets the number of old messages in the mailbox. */ - public void setOldMessages(Integer oldMessages) - { + public void setOldMessages(Integer oldMessages) { this.oldMessages = oldMessages; } } diff --git a/src/main/java/org/asteriskjava/manager/response/MailboxStatusResponse.java b/src/main/java/org/asteriskjava/manager/response/MailboxStatusResponse.java index f76155fd5..c0e245d0d 100644 --- a/src/main/java/org/asteriskjava/manager/response/MailboxStatusResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/MailboxStatusResponse.java @@ -19,24 +19,22 @@ /** * A MailboxStatusResponse is sent in response to a MailboxStatusAction and indicates if a set * of mailboxes contains waiting messages. - * - * @see org.asteriskjava.manager.action.MailboxStatusAction - * + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.MailboxStatusAction */ -public class MailboxStatusResponse extends ManagerResponse -{ +public class MailboxStatusResponse extends ManagerResponse { /** * Serial version identifier */ private static final long serialVersionUID = -7193581424292429279L; - + /** * The name of the mailbox. */ private String mailbox; - + /** * Indicates if there are new messages waiting in the given set of mailboxes. */ @@ -44,19 +42,19 @@ public class MailboxStatusResponse extends ManagerResponse /** * Returns the names of the mailboxes, separated by ",". + * * @return the names of the mailbox. */ - public String getMailbox() - { + public String getMailbox() { return mailbox; } /** * Sets the names of the mailboxes. + * * @param mailbox the names of the mailboxes. */ - public void setMailbox(String mailbox) - { + public void setMailbox(String mailbox) { this.mailbox = mailbox; } @@ -64,8 +62,7 @@ public void setMailbox(String mailbox) * Returns Boolean.TRUE if at least one of the given mailboxes contains new messages; * Boolean.FALSE otherwise. */ - public Boolean getWaiting() - { + public Boolean getWaiting() { return waiting; } @@ -73,8 +70,7 @@ public Boolean getWaiting() * Set to Boolean.TRUE if at least one of the mailboxes contains new messages; * Boolean.FALSE otherwise. */ - public void setWaiting(Boolean waiting) - { + public void setWaiting(Boolean waiting) { this.waiting = waiting; } } diff --git a/src/main/java/org/asteriskjava/manager/response/ManagerError.java b/src/main/java/org/asteriskjava/manager/response/ManagerError.java index 47947439f..2b208f72b 100644 --- a/src/main/java/org/asteriskjava/manager/response/ManagerError.java +++ b/src/main/java/org/asteriskjava/manager/response/ManagerError.java @@ -19,12 +19,11 @@ /** * Represents an "Response: Error" response received from the asterisk server. * The cause for the error is given in the message attribute. - * + * * @author srt * @version $Id$ */ -public class ManagerError extends ManagerResponse -{ +public class ManagerError extends ManagerResponse { /** * Serial version identifier */ @@ -33,8 +32,7 @@ public class ManagerError extends ManagerResponse /** * Creates a new ManagerError. */ - public ManagerError() - { + public ManagerError() { super(); } } diff --git a/src/main/java/org/asteriskjava/manager/response/ManagerResponse.java b/src/main/java/org/asteriskjava/manager/response/ManagerResponse.java index f519c3187..cb8e5c53c 100644 --- a/src/main/java/org/asteriskjava/manager/response/ManagerResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/ManagerResponse.java @@ -23,7 +23,8 @@ /** * Represents a response received from the Asterisk server as the result of a - * previously sent ManagerAction.

      + * previously sent ManagerAction. + *

      * The response can be linked with the action that caused it by looking the * action id attribute that will match the action id of the corresponding * action. @@ -32,58 +33,62 @@ * @version $Id$ * @see org.asteriskjava.manager.action.ManagerAction */ -public class ManagerResponse implements Serializable -{ +public class ManagerResponse implements Serializable { private static final long serialVersionUID = 1L; private Date dateReceived; private String actionId; /** - * The server from which this response has been received (only used with AstManProxy). + * The server from which this response has been received (only used with + * AstManProxy). */ private String server; private String response; private String eventList; private String message; private String uniqueId; + private String events; private Map attributes; + private String output; - public ManagerResponse() - { + public ManagerResponse() { this.attributes = null; } /** - * Returns a Map with all attributes of this response.

      + * Returns a Map with all attributes of this response. + *

      * The keys are all lower case! * * @see #getAttribute(String) */ - public Map getAttributes() - { + public Map getAttributes() { return attributes; } /** * Sets the Map with all attributes. * - * @param attributes Map with containing the attributes with all lower - * case keys. + * @param attributes Map with containing the attributes with all lower case + * keys. */ - public void setAttributes(Map attributes) - { + public void setAttributes(Map attributes) { this.attributes = attributes; } /** - * Returns the value of the attribute with the given key.

      - * This is particulary important when a response contains special - * attributes that are dependent on the action that has been sent.

      - * An example of this is the response to the GetVarAction. - * It contains the value of the channel variable as an attribute - * stored under the key of the variable name.

      + * Returns the value of the attribute with the given key. + *

      + * This is particulary important when a response contains special attributes + * that are dependent on the action that has been sent. + *

      + * An example of this is the response to the GetVarAction. It contains the + * value of the channel variable as an attribute stored under the key of the + * variable name. + *

      * Example: + * *

            * GetVarAction action = new GetVarAction();
            * action.setChannel("SIP/1310-22c3");
      @@ -91,15 +96,15 @@ public void setAttributes(Map attributes)
            * ManagerResponse response = connection.sendAction(action);
            * String alertInfo = response.getAttribute("ALERT_INFO");
            * 
      + *

      * As all attributes are internally stored in lower case the key is * automatically converted to lower case before lookup. * * @param key the key to lookup. * @return the value of the attribute stored under this key or - * null if there is no such attribute. + * null if there is no such attribute. */ - public String getAttribute(String key) - { + public String getAttribute(String key) { return (String) attributes.get(key.toLowerCase(Locale.ENGLISH)); } @@ -107,8 +112,7 @@ public String getAttribute(String key) * Returns the point in time this response was received from the asterisk * server. */ - public Date getDateReceived() - { + public Date getDateReceived() { return dateReceived; } @@ -116,48 +120,46 @@ public Date getDateReceived() * Sets the point in time this response was received from the asterisk * server. */ - public void setDateReceived(Date dateReceived) - { + public void setDateReceived(Date dateReceived) { this.dateReceived = dateReceived; } /** - * Returns the user provided action id of the ManagerAction that caused - * this response. If the application did not set an action id this method - * returns null. + * Returns the user provided action id of the ManagerAction that caused this + * response. If the application did not set an action id this method returns + * null. * * @return the action id of the ManagerAction that caused this response or - * null if none was set. + * null if none was set. * @see org.asteriskjava.manager.action.ManagerAction#setActionId(String) */ - public String getActionId() - { + public String getActionId() { return actionId; } /** - * Returns the name of the Asterisk server from which this response has been received. - *

      + * Returns the name of the Asterisk server from which this response has been + * received.
      * This property is only available when using to AstManProxy. * - * @return the name of the Asterisk server from which this response has been received - * or null when directly connected to an Asterisk server - * instead of AstManProxy. + * @return the name of the Asterisk server from which this response has been + * received or null when directly connected to an + * Asterisk server instead of AstManProxy. * @since 1.0.0 */ - public final String getServer() - { + public final String getServer() { return server; } /** - * Sets the name of the Asterisk server from which this response has been received. + * Sets the name of the Asterisk server from which this response has been + * received. * - * @param server the name of the Asterisk server from which this response has been received. + * @param server the name of the Asterisk server from which this response + * has been received. * @since 1.0.0 */ - public final void setServer(String server) - { + public final void setServer(String server) { this.server = server; } @@ -167,8 +169,7 @@ public final void setServer(String server) * @return "start", "stop" or "complete" * @since 1.0.0 */ - public String getEventList() - { + public String getEventList() { return eventList; } @@ -178,8 +179,7 @@ public String getEventList() * @param eventList the eventList. * @since 1.0.0 */ - public void setEventList(String eventList) - { + public void setEventList(String eventList) { this.eventList = eventList; } @@ -189,8 +189,7 @@ public void setEventList(String eventList) * @param actionId the action id of the ManagerAction that caused this * response. */ - public void setActionId(String actionId) - { + public void setActionId(String actionId) { this.actionId = actionId; } @@ -198,16 +197,14 @@ public void setActionId(String actionId) * Returns the message received with this response. The content depends on * the action that generated this response. */ - public String getMessage() - { + public String getMessage() { return message; } /** * Sets the message. */ - public void setMessage(String message) - { + public void setMessage(String message) { this.message = message; } @@ -216,16 +213,14 @@ public void setMessage(String message) * "Success" or "Error" but depends on the action that generated this * response. */ - public String getResponse() - { + public String getResponse() { return response; } /** * Sets the response. */ - public void setResponse(String response) - { + public void setResponse(String response) { this.response = response; } @@ -234,55 +229,46 @@ public void setResponse(String response) * to keep track of channels created by the action sent, for example an * OriginateAction. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } /** * Sets the unique id received with this response. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } - protected Integer stringToInteger(String s, String suffix) throws NumberFormatException - { - if (s == null || s.length() == 0) - { + protected Integer stringToInteger(String s, String suffix) throws NumberFormatException { + if (s == null || s.length() == 0) { return null; } - if (suffix != null && s.endsWith(suffix)) - { + if (suffix != null && s.endsWith(suffix)) { return Integer.parseInt(s.substring(0, s.length() - suffix.length()).trim()); } return Integer.parseInt(s.trim()); } - protected Long stringToLong(String s, String suffix) throws NumberFormatException - { - if (s == null || s.length() == 0) - { + protected Long stringToLong(String s, String suffix) throws NumberFormatException { + if (s == null || s.length() == 0) { return null; } - if (suffix != null && s.endsWith(suffix)) - { + if (suffix != null && s.endsWith(suffix)) { return Long.parseLong(s.substring(0, s.length() - suffix.length()).trim()); } - + return Long.parseLong(s.trim()); } @Override - public String toString() - { - StringBuffer sb; + public String toString() { + StringBuilder sb; - sb = new StringBuffer(100); + sb = new StringBuilder(100); sb.append(getClass().getName()).append(": "); sb.append("actionId='").append(getActionId()).append("'; "); sb.append("message='").append(getMessage()).append("'; "); @@ -292,4 +278,20 @@ public String toString() return sb.toString(); } + + public String getEvents() { + return events; + } + + public void setEvents(String events) { + this.events = events; + } + + public String getOutput() { + return output; + } + + public void setOutput(String output) { + this.output = output; + } } diff --git a/src/main/java/org/asteriskjava/manager/response/MixMonitorResponse.java b/src/main/java/org/asteriskjava/manager/response/MixMonitorResponse.java new file mode 100644 index 000000000..ab8d3997f --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/response/MixMonitorResponse.java @@ -0,0 +1,48 @@ +/* + * Copyright 2018 CallShaper, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.response; + +/** + * A MixMonitorResponse is sent in response to a MixMonitorAction and provides + * the ID of the MixMonitor that was started on the referenced channel. + *

      + * Available since Asterisk 11 + * + * @see org.asteriskjava.manager.action.MixMonitorAction; + */ +public class MixMonitorResponse extends ManagerResponse { + private static final long serialVersionUID = 1L; + private String mixMonitorId; + + /** + * Returns the ID of the MixMonitor + * + * @return the MixMonitor ID + */ + public String getMixMonitorId() { + return mixMonitorId; + } + + /** + * Sets the ID of the MixMonitor + * + * @param mixMonitorId the MixMonitor ID + */ + public void setMixMonitorId(String mixMonitorId) { + this.mixMonitorId = mixMonitorId; + } +} diff --git a/src/main/java/org/asteriskjava/manager/response/ModuleCheckResponse.java b/src/main/java/org/asteriskjava/manager/response/ModuleCheckResponse.java index 04358fbeb..f131a5865 100644 --- a/src/main/java/org/asteriskjava/manager/response/ModuleCheckResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/ModuleCheckResponse.java @@ -24,24 +24,21 @@ * @see org.asteriskjava.manager.action.ModuleCheckAction * @since 1.0.0 */ -public class ModuleCheckResponse extends ManagerResponse -{ +public class ModuleCheckResponse extends ManagerResponse { private static final long serialVersionUID = -7253724086340850957L; - private Integer version; + private String version; /** * Returns the version (svn revision) of the module. * * @return the version (svn revision) of the module. */ - public Integer getVersion() - { + public String getVersion() { return version; } - public void setVersion(Integer version) - { + public void setVersion(String version) { this.version = version; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/response/PingResponse.java b/src/main/java/org/asteriskjava/manager/response/PingResponse.java index c0b77282c..aee7a35b0 100644 --- a/src/main/java/org/asteriskjava/manager/response/PingResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/PingResponse.java @@ -20,27 +20,38 @@ * Corresponds to a PingAction and contains an additional (yet useless) ping property. * * @author srt - * @version $Id$ * @see org.asteriskjava.manager.action.PingAction */ -public class PingResponse extends ManagerResponse -{ +public class PingResponse extends ManagerResponse { private static final long serialVersionUID = 0L; private String ping; + private String timestamp; /** * Returns always "Pong". * * @return always "Pong". */ - public String getPing() - { + public String getPing() { return ping; } - public void setPing(String ping) - { + public void setPing(String ping) { this.ping = ping; } -} \ No newline at end of file + + /** + * Timestamp for the response. + * + * @return Timestamp as a String, e.g 1353747825.795863 + * @since 1.0.0 + */ + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } +} diff --git a/src/main/java/org/asteriskjava/manager/response/SipShowPeerResponse.java b/src/main/java/org/asteriskjava/manager/response/SipShowPeerResponse.java index a87d07d98..1ea7987b7 100644 --- a/src/main/java/org/asteriskjava/manager/response/SipShowPeerResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/SipShowPeerResponse.java @@ -1,3 +1,18 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.asteriskjava.manager.response; import java.util.Map; @@ -7,11 +22,10 @@ * * @author srt * @version $Id$ - * @since 1.0.0 * @see org.asteriskjava.manager.action.SipShowPeerAction + * @since 1.0.0 */ -public class SipShowPeerResponse extends ManagerResponse -{ +public class SipShowPeerResponse extends ManagerResponse { private static final long serialVersionUID = 1L; private String channelType; @@ -19,7 +33,7 @@ public class SipShowPeerResponse extends ManagerResponse private String chanObjectType; private Boolean secretExist; private Boolean md5SecretExist; - private Boolean remoteSecretExist; + private Boolean remoteSecretExist; private String context; private String language; private String accountCode; @@ -41,10 +55,10 @@ public class SipShowPeerResponse extends ManagerResponse private Boolean sipAuthInsecure; private Boolean sipNatSupport; private Boolean acl; - private Boolean sipT38support; - private String sipT38ec; - private Integer sipT38MaxDtgrm; - private Boolean sipDirectMedia; + private Boolean sipT38support; + private String sipT38ec; + private Long sipT38MaxDtgrm; + private Boolean sipDirectMedia; private Boolean sipCanReinvite; private Boolean sipPromiscRedir; private Boolean sipUserPhone; @@ -68,579 +82,746 @@ public class SipShowPeerResponse extends ManagerResponse private String sipUserAgent; private String regContact; private Integer qualifyFreq; // "%d ms" - private String parkingLot; - - private Map chanVariable; - - public String getChannelType() - { + private String parkingLot; + private Integer maxForwards; + + private String toneZone; + private String sipUseReasonHeader; + private String sipEncryption; + private String sipForcerport; + private String sipRtpEngine; + private String sipComedia; + private String mohsuggest; + private String namedPickupgroup; + private String sipRtcpMux; + private String description; + private String subscribecontext; + private String namedCallgroup; + + private Map chanVariable; + + public String getChannelType() { return channelType; } - public void setChannelType(String channelType) - { + public void setChannelType(String channelType) { this.channelType = channelType; } - public String getObjectName() - { + public String getObjectName() { return objectName; } - public void setObjectName(String objectName) - { + public void setObjectName(String objectName) { this.objectName = objectName; } - public String getChanObjectType() - { + public String getChanObjectType() { return chanObjectType; } - public void setChanObjectType(String chanObjectType) - { + public void setChanObjectType(String chanObjectType) { this.chanObjectType = chanObjectType; } - public Boolean getSecretExist() - { + public Boolean getSecretExist() { return secretExist; } - public void setSecretExist(Boolean secretExist) - { + public void setSecretExist(Boolean secretExist) { this.secretExist = secretExist; } - public Boolean getMd5SecretExist() - { + public Boolean getMd5SecretExist() { return md5SecretExist; } - public void setMd5SecretExist(Boolean md5SecretExist) - { + public void setMd5SecretExist(Boolean md5SecretExist) { this.md5SecretExist = md5SecretExist; } - public Boolean getRemoteSecretExist() - { - return remoteSecretExist; - } + public Boolean getRemoteSecretExist() { + return remoteSecretExist; + } - public void setRemoteSecretExist(Boolean remoteSecretExist) - { - this.remoteSecretExist = remoteSecretExist; - } + public void setRemoteSecretExist(Boolean remoteSecretExist) { + this.remoteSecretExist = remoteSecretExist; + } - public String getContext() - { + public String getContext() { return context; } - public void setContext(String context) - { + public void setContext(String context) { this.context = context; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - public String getAmaFlags() - { + public String getAmaFlags() { return amaFlags; } - public void setAmaFlags(String amaFlags) - { + public void setAmaFlags(String amaFlags) { this.amaFlags = amaFlags; } - public String getCidCallingPres() - { + public String getCidCallingPres() { return cidCallingPres; } - public void setCidCallingPres(String cidCallingPres) - { + public void setCidCallingPres(String cidCallingPres) { this.cidCallingPres = cidCallingPres; } - public String getSipFromUser() - { + public String getSipFromUser() { return sipFromUser; } - public void setSipFromUser(String sipFromUser) - { + public void setSipFromUser(String sipFromUser) { this.sipFromUser = sipFromUser; } - public String getSipFromDomain() - { + public String getSipFromDomain() { return sipFromDomain; } - public void setSipFromDomain(String sipFromDomain) - { + public void setSipFromDomain(String sipFromDomain) { this.sipFromDomain = sipFromDomain; } - public String getCallGroup() - { + public String getCallGroup() { return callGroup; } - public void setCallGroup(String callGroup) - { + public void setCallGroup(String callGroup) { this.callGroup = callGroup; } - public String getPickupGroup() - { + public String getPickupGroup() { return pickupGroup; } - public void setPickupGroup(String pickupGroup) - { + public void setPickupGroup(String pickupGroup) { this.pickupGroup = pickupGroup; } - public String getVoiceMailbox() - { + public String getVoiceMailbox() { return voiceMailbox; } - public void setVoiceMailbox(String voiceMailbox) - { + public void setVoiceMailbox(String voiceMailbox) { this.voiceMailbox = voiceMailbox; } - public String getTransferMode() - { + public String getTransferMode() { return transferMode; } - public void setTransferMode(String transferMode) - { + public void setTransferMode(String transferMode) { this.transferMode = transferMode; } - public Integer getLastMsgsSent() - { + public Integer getLastMsgsSent() { return lastMsgsSent; } - public void setLastMsgsSent(Integer lastMsgsSent) - { + public void setLastMsgsSent(Integer lastMsgsSent) { this.lastMsgsSent = lastMsgsSent; } - public Integer getCallLimit() - { + public Integer getCallLimit() { return callLimit; } - public void setCallLimit(Integer callLimit) - { + public void setCallLimit(Integer callLimit) { this.callLimit = callLimit; } - public Integer getBusyLevel() - { + public Integer getBusyLevel() { return busyLevel; } - public void setBusyLevel(Integer busyLevel) - { + public void setBusyLevel(Integer busyLevel) { this.busyLevel = busyLevel; } - public Integer getMaxCallBr() - { + public Integer getMaxCallBr() { return maxCallBr; } - public void setMaxCallBr(String maxCallBr) - { + public void setMaxCallBr(String maxCallBr) { this.maxCallBr = stringToInteger(maxCallBr, "kbps"); } - public Boolean getDynamic() - { + public Boolean getDynamic() { return dynamic; } - public void setDynamic(Boolean dynamic) - { + public void setDynamic(Boolean dynamic) { this.dynamic = dynamic; } - public String getCallerId() - { + public String getCallerId() { return callerId; } - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } - public Long getRegExpire() - { + public Long getRegExpire() { return regExpire; } - public void setRegExpire(String regExpire) - { + public void setRegExpire(String regExpire) { this.regExpire = stringToLong(regExpire, "seconds"); } - public Boolean getSipAuthInsecure() - { + public Boolean getSipAuthInsecure() { return sipAuthInsecure; } - public void setSipAuthInsecure(Boolean sipAuthInsecure) - { + public void setSipAuthInsecure(Boolean sipAuthInsecure) { this.sipAuthInsecure = sipAuthInsecure; } - public Boolean getSipNatSupport() - { + public Boolean getSipNatSupport() { return sipNatSupport; } - public void setSipNatSupport(Boolean sipNatSupport) - { + public void setSipNatSupport(Boolean sipNatSupport) { this.sipNatSupport = sipNatSupport; } - public Boolean getAcl() - { + public Boolean getAcl() { return acl; } - public void setAcl(Boolean acl) - { + public void setAcl(Boolean acl) { this.acl = acl; } - public Boolean getSipT38support() - { - return sipT38support; - } - - public void setSipT38support(Boolean sipT38support) - { - this.sipT38support = sipT38support; - } - - public String getSipT38ec() - { - return sipT38ec; - } - - public void setSipT38ec(String sipT38ec) - { - this.sipT38ec = sipT38ec; - } - - public Integer getSipT38MaxDtgrm() - { - return sipT38MaxDtgrm; - } - - public void setSipT38MaxDtgrm(Integer sipT38MaxDtgrm) - { - this.sipT38MaxDtgrm = sipT38MaxDtgrm; - } - - public Boolean getSipDirectMedia() - { - return sipDirectMedia; - } - - public void setSipDirectMedia(Boolean sipDirectMedia) - { - this.sipDirectMedia = sipDirectMedia; - } - - public Boolean getSipCanReinvite() - { + public Boolean getSipT38support() { + return sipT38support; + } + + public void setSipT38support(Boolean sipT38support) { + this.sipT38support = sipT38support; + } + + public String getSipT38ec() { + return sipT38ec; + } + + public void setSipT38ec(String sipT38ec) { + this.sipT38ec = sipT38ec; + } + + public Long getSipT38MaxDtgrm() { + return sipT38MaxDtgrm; + } + + public void setSipT38MaxDtgrm(Long sipT38MaxDtgrm) { + + /** + * asterisk returns sipT38MaxDtgrm as 4394967295L when the value is -1 + * so I'm taking a long and then changing it to -1 if required + */ + if (sipT38MaxDtgrm == 4294967295L) { + this.sipT38MaxDtgrm = -1L; + } else { + if (sipT38MaxDtgrm < Integer.MAX_VALUE && sipT38MaxDtgrm > Integer.MIN_VALUE) { + this.sipT38MaxDtgrm = sipT38MaxDtgrm; + } + } + } + + public Boolean getSipDirectMedia() { + return sipDirectMedia; + } + + public void setSipDirectMedia(Boolean sipDirectMedia) { + this.sipDirectMedia = sipDirectMedia; + } + + public Boolean getSipCanReinvite() { return sipCanReinvite; } - public void setSipCanReinvite(Boolean sipCanReinvite) - { + public void setSipCanReinvite(Boolean sipCanReinvite) { this.sipCanReinvite = sipCanReinvite; } - public Boolean getSipPromiscRedir() - { + public Boolean getSipPromiscRedir() { return sipPromiscRedir; } - public void setSipPromiscRedir(Boolean sipPromiscRedir) - { + public void setSipPromiscRedir(Boolean sipPromiscRedir) { this.sipPromiscRedir = sipPromiscRedir; } - public Boolean getSipUserPhone() - { + public Boolean getSipUserPhone() { return sipUserPhone; } - public void setSipUserPhone(Boolean sipUserPhone) - { + public void setSipUserPhone(Boolean sipUserPhone) { this.sipUserPhone = sipUserPhone; } - public Boolean getSipVideoSupport() - { + public Boolean getSipVideoSupport() { return sipVideoSupport; } - public void setSipVideoSupport(Boolean sipVideoSupport) - { + public void setSipVideoSupport(Boolean sipVideoSupport) { this.sipVideoSupport = sipVideoSupport; } - public Boolean getSipTextSupport() - { + public Boolean getSipTextSupport() { return sipTextSupport; } - public void setSipTextSupport(Boolean sipTextSupport) - { + public void setSipTextSupport(Boolean sipTextSupport) { this.sipTextSupport = sipTextSupport; } - public String getSipSessTimers() - { + public String getSipSessTimers() { return sipSessTimers; } - public void setSipSessTimers(String sipSessTimers) - { + public void setSipSessTimers(String sipSessTimers) { this.sipSessTimers = sipSessTimers; } - public String getSipSessRefresh() - { + public String getSipSessRefresh() { return sipSessRefresh; } - public void setSipSessRefresh(String sipSessRefresh) - { + public void setSipSessRefresh(String sipSessRefresh) { this.sipSessRefresh = sipSessRefresh; } - public Integer getSipSessExpires() - { + public Integer getSipSessExpires() { return sipSessExpires; } - public void setSipSessExpires(Integer sipSessExpires) - { + public void setSipSessExpires(Integer sipSessExpires) { this.sipSessExpires = sipSessExpires; } - public Integer getSipSessMin() - { + public Integer getSipSessMin() { return sipSessMin; } - public void setSipSessMin(Integer sipSessMin) - { + public void setSipSessMin(Integer sipSessMin) { this.sipSessMin = sipSessMin; } - public String getSipDtmfMode() - { + public String getSipDtmfMode() { return sipDtmfMode; } - public void setSipDtmfMode(String sipDtmfMode) - { + public void setSipDtmfMode(String sipDtmfMode) { this.sipDtmfMode = sipDtmfMode; } - public String getToHost() - { + public String getToHost() { return toHost; } - public void setToHost(String toHost) - { + public void setToHost(String toHost) { this.toHost = toHost; } - public String getAddressIp() - { + public String getAddressIp() { return addressIp; } - public void setAddressIp(String addressIp) - { + public void setAddressIp(String addressIp) { this.addressIp = addressIp; } - public Integer getAddressPort() - { + public Integer getAddressPort() { return addressPort; } - public void setAddressPort(Integer addressPort) - { + public void setAddressPort(Integer addressPort) { this.addressPort = addressPort; } - public String getDefaultAddrIp() - { + public String getDefaultAddrIp() { return defaultAddrIp; } - public void setDefaultAddrIp(String defaultAddrIp) - { + public void setDefaultAddrIp(String defaultAddrIp) { this.defaultAddrIp = defaultAddrIp; } - public Integer getDefaultAddrPort() - { + public Integer getDefaultAddrPort() { return defaultAddrPort; } - public void setDefaultAddrPort(Integer defaultAddrPort) - { + public void setDefaultAddrPort(Integer defaultAddrPort) { this.defaultAddrPort = defaultAddrPort; } - public String getDefaultUsername() - { + public String getDefaultUsername() { return defaultUsername; } - public void setDefaultUsername(String defaultUsername) - { + public void setDefaultUsername(String defaultUsername) { this.defaultUsername = defaultUsername; } - public String getRegExtension() - { + public String getRegExtension() { return regExtension; } - public void setRegExtension(String regExtension) - { + public void setRegExtension(String regExtension) { this.regExtension = regExtension; } - public String getCodecs() - { + public String getCodecs() { return codecs; } - public void setCodecs(String codecs) - { + public void setCodecs(String codecs) { this.codecs = codecs; } - public String getCodecOrder() - { + public String getCodecOrder() { return codecOrder; } - public void setCodecOrder(String codecOrder) - { + public void setCodecOrder(String codecOrder) { this.codecOrder = codecOrder; } - public String getStatus() - { + public String getStatus() { return status; } - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } - public String getSipUserAgent() - { + public String getSipUserAgent() { return sipUserAgent; } - public void setSipUserAgent(String sipUserAgent) - { + public void setSipUserAgent(String sipUserAgent) { this.sipUserAgent = sipUserAgent; } - public String getParkingLot() - { - return parkingLot; - } + public String getParkingLot() { + return parkingLot; + } - public void setParkingLot(String parkingLot) - { - this.parkingLot = parkingLot; - } + public void setParkingLot(String parkingLot) { + this.parkingLot = parkingLot; + } - public String getRegContact() - { + public String getRegContact() { return regContact; } - public void setRegContact(String regContact) - { + public void setRegContact(String regContact) { // workaround for Asterisk bug: - if (regContact.startsWith(": ")) - { + if (regContact.startsWith(": ")) { regContact = regContact.substring(2); } this.regContact = regContact; } - public Integer getQualifyFreq() - { + public Integer getQualifyFreq() { return qualifyFreq; } - public void setQualifyFreq(String qualifyFreq) - { + public void setQualifyFreq(String qualifyFreq) { // workaround for Asterisk bugs: - if (qualifyFreq.startsWith(": ")) - { + if (qualifyFreq.startsWith(": ")) { qualifyFreq = qualifyFreq.substring(2); } - if (qualifyFreq.indexOf('\n') > -1) - { + if (qualifyFreq.indexOf('\n') > -1) { qualifyFreq = qualifyFreq.substring(0, qualifyFreq.indexOf('\n')); } this.qualifyFreq = stringToInteger(qualifyFreq, "ms"); } - public Map getChanVariable() { - return chanVariable; - } + public Map getChanVariable() { + return chanVariable; + } + + public void setChanVariable(final Map chanVariable) { + this.chanVariable = chanVariable; + } + + public Integer getMaxForwards() { + return maxForwards; + } + + public void setMaxForwards(Integer maxForwards) { + this.maxForwards = maxForwards; + } + + public String getToneZone() { + return toneZone; + } + + public void setToneZone(String toneZone) { + this.toneZone = toneZone; + } + + public String getSipUseReasonHeader() { + return sipUseReasonHeader; + } + + public void setSipUseReasonHeader(String sipUseReasonHeader) { + this.sipUseReasonHeader = sipUseReasonHeader; + } + + public String getSipEncryption() { + return sipEncryption; + } + + public void setSipEncryption(String sipEncryption) { + this.sipEncryption = sipEncryption; + } + + public String getSipForcerport() { + return sipForcerport; + } + + public void setSipForcerport(String sipForcerport) { + this.sipForcerport = sipForcerport; + } + + public String getSipRtpEngine() { + return sipRtpEngine; + } + + public void setSipRtpEngine(String sipRtpEngine) { + this.sipRtpEngine = sipRtpEngine; + } + + public String getSipComedia() { + return sipComedia; + } + + public void setSipComedia(String sipComedia) { + this.sipComedia = sipComedia; + } + + public String getMohsuggest() { + return mohsuggest; + } + + public void setMohsuggest(String mohsuggest) { + this.mohsuggest = mohsuggest; + } + + public String getNamedPickupgroup() { + return namedPickupgroup; + } + + public SipShowPeerResponse setNamedPickupgroup(String namedPickupgroup) { + this.namedPickupgroup = namedPickupgroup; + return this; + } + + public String getSipRtcpMux() { + return sipRtcpMux; + } + + public SipShowPeerResponse setSipRtcpMux(String sipRtcpMux) { + this.sipRtcpMux = sipRtcpMux; + return this; + } + + public String getDescription() { + return description; + } + + public SipShowPeerResponse setDescription(String description) { + this.description = description; + return this; + } + + public String getSubscribecontext() { + return subscribecontext; + } + + public SipShowPeerResponse setSubscribecontext(String subscribecontext) { + this.subscribecontext = subscribecontext; + return this; + } + + public String getNamedCallgroup() { + return namedCallgroup; + } + + public SipShowPeerResponse setNamedCallgroup(String namedCallgroup) { + this.namedCallgroup = namedCallgroup; + return this; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("SipShowPeerResponse [channelType="); + builder.append(channelType); + builder.append(", objectName="); + builder.append(objectName); + builder.append(", chanObjectType="); + builder.append(chanObjectType); + builder.append(", secretExist="); + builder.append(secretExist); + builder.append(", md5SecretExist="); + builder.append(md5SecretExist); + builder.append(", remoteSecretExist="); + builder.append(remoteSecretExist); + builder.append(", context="); + builder.append(context); + builder.append(", language="); + builder.append(language); + builder.append(", accountCode="); + builder.append(accountCode); + builder.append(", amaFlags="); + builder.append(amaFlags); + builder.append(", cidCallingPres="); + builder.append(cidCallingPres); + builder.append(", sipFromUser="); + builder.append(sipFromUser); + builder.append(", sipFromDomain="); + builder.append(sipFromDomain); + builder.append(", callGroup="); + builder.append(callGroup); + builder.append(", pickupGroup="); + builder.append(pickupGroup); + builder.append(", voiceMailbox="); + builder.append(voiceMailbox); + builder.append(", transferMode="); + builder.append(transferMode); + builder.append(", lastMsgsSent="); + builder.append(lastMsgsSent); + builder.append(", callLimit="); + builder.append(callLimit); + builder.append(", busyLevel="); + builder.append(busyLevel); + builder.append(", maxCallBr="); + builder.append(maxCallBr); + builder.append(", dynamic="); + builder.append(dynamic); + builder.append(", callerId="); + builder.append(callerId); + builder.append(", regExpire="); + builder.append(regExpire); + builder.append(", sipAuthInsecure="); + builder.append(sipAuthInsecure); + builder.append(", sipNatSupport="); + builder.append(sipNatSupport); + builder.append(", acl="); + builder.append(acl); + builder.append(", sipT38support="); + builder.append(sipT38support); + builder.append(", sipT38ec="); + builder.append(sipT38ec); + builder.append(", sipT38MaxDtgrm="); + builder.append(sipT38MaxDtgrm); + builder.append(", sipDirectMedia="); + builder.append(sipDirectMedia); + builder.append(", sipCanReinvite="); + builder.append(sipCanReinvite); + builder.append(", sipPromiscRedir="); + builder.append(sipPromiscRedir); + builder.append(", sipUserPhone="); + builder.append(sipUserPhone); + builder.append(", sipVideoSupport="); + builder.append(sipVideoSupport); + builder.append(", sipTextSupport="); + builder.append(sipTextSupport); + builder.append(", sipSessTimers="); + builder.append(sipSessTimers); + builder.append(", sipSessRefresh="); + builder.append(sipSessRefresh); + builder.append(", sipSessExpires="); + builder.append(sipSessExpires); + builder.append(", sipSessMin="); + builder.append(sipSessMin); + builder.append(", sipDtmfMode="); + builder.append(sipDtmfMode); + builder.append(", toHost="); + builder.append(toHost); + builder.append(", addressIp="); + builder.append(addressIp); + builder.append(", addressPort="); + builder.append(addressPort); + builder.append(", defaultAddrIp="); + builder.append(defaultAddrIp); + builder.append(", defaultAddrPort="); + builder.append(defaultAddrPort); + builder.append(", defaultUsername="); + builder.append(defaultUsername); + builder.append(", regExtension="); + builder.append(regExtension); + builder.append(", codecs="); + builder.append(codecs); + builder.append(", codecOrder="); + builder.append(codecOrder); + builder.append(", status="); + builder.append(status); + builder.append(", sipUserAgent="); + builder.append(sipUserAgent); + builder.append(", regContact="); + builder.append(regContact); + builder.append(", qualifyFreq="); + builder.append(qualifyFreq); + builder.append(", parkingLot="); + builder.append(parkingLot); + builder.append(", maxForwards="); + builder.append(maxForwards); + builder.append(", toneZone="); + builder.append(toneZone); + builder.append(", sipUseReasonHeader="); + builder.append(sipUseReasonHeader); + builder.append(", sipEncryption="); + builder.append(sipEncryption); + builder.append(", sipForcerport="); + builder.append(sipForcerport); + builder.append(", sipRtpEngine="); + builder.append(sipRtpEngine); + builder.append(", sipComedia="); + builder.append(sipComedia); + builder.append(", chanVariable="); + builder.append(chanVariable); + builder.append(", mohSuggest="); + builder.append(mohsuggest); + builder.append(", namedPickupgroup="); + builder.append(namedPickupgroup); + builder.append(", sipRtcpMux="); + builder.append(sipRtcpMux); + builder.append(", description="); + builder.append(description); + builder.append(", subscribecontext="); + builder.append(subscribecontext); + builder.append(", namedCallgroup="); + builder.append(namedCallgroup); + builder.append("]"); + return builder.toString(); + } - public void setChanVariable(final Map chanVariable) { - this.chanVariable = chanVariable; - } } diff --git a/src/main/java/org/asteriskjava/manager/response/SkypeBuddyResponse.java b/src/main/java/org/asteriskjava/manager/response/SkypeBuddyResponse.java index 59df06498..87f40ff72 100644 --- a/src/main/java/org/asteriskjava/manager/response/SkypeBuddyResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/SkypeBuddyResponse.java @@ -22,8 +22,7 @@ * @see org.asteriskjava.manager.action.SkypeBuddyAction * @since 1.0.0 */ -public class SkypeBuddyResponse extends ManagerResponse -{ +public class SkypeBuddyResponse extends ManagerResponse { private static final long serialVersionUID = 0L; private String skypename; @@ -37,43 +36,35 @@ public class SkypeBuddyResponse extends ManagerResponse private String phoneMobile; private String about; - public String getSkypename() - { + public String getSkypename() { return skypename; } - public void setSkypename(String skypename) - { + public void setSkypename(String skypename) { this.skypename = skypename; } - public String getTimezone() - { + public String getTimezone() { return timezone; } - public void setTimezone(String timezone) - { + public void setTimezone(String timezone) { this.timezone = timezone; } - public String getAvailability() - { + public String getAvailability() { return availability; } - public void setAvailability(String availability) - { + public void setAvailability(String availability) { this.availability = availability; } - public String getFullname() - { + public String getFullname() { return fullname; } - public void setFullname(String fullname) - { + public void setFullname(String fullname) { this.fullname = fullname; } @@ -82,8 +73,7 @@ public void setFullname(String fullname) * * @return the ISO language code. */ - public String getLanguage() - { + public String getLanguage() { return language; } @@ -92,8 +82,7 @@ public String getLanguage() * * @param language the ISO language code. */ - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } @@ -102,8 +91,7 @@ public void setLanguage(String language) * * @return the ISO country code (in lower case). */ - public String getCountry() - { + public String getCountry() { return country; } @@ -112,48 +100,39 @@ public String getCountry() * * @param country the country code. */ - public void setCountry(String country) - { + public void setCountry(String country) { this.country = country; } - public String getPhoneHome() - { + public String getPhoneHome() { return phoneHome; } - public void setPhoneHome(String phoneHome) - { + public void setPhoneHome(String phoneHome) { this.phoneHome = phoneHome; } - public String getPhoneOffice() - { + public String getPhoneOffice() { return phoneOffice; } - public void setPhoneOffice(String phoneOffice) - { + public void setPhoneOffice(String phoneOffice) { this.phoneOffice = phoneOffice; } - public String getPhoneMobile() - { + public String getPhoneMobile() { return phoneMobile; } - public void setPhoneMobile(String phoneMobile) - { + public void setPhoneMobile(String phoneMobile) { this.phoneMobile = phoneMobile; } - public String getAbout() - { + public String getAbout() { return about; } - public void setAbout(String about) - { + public void setAbout(String about) { this.about = about; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/response/SkypeLicenseStatusResponse.java b/src/main/java/org/asteriskjava/manager/response/SkypeLicenseStatusResponse.java index 504d54fb9..7bdaaab88 100644 --- a/src/main/java/org/asteriskjava/manager/response/SkypeLicenseStatusResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/SkypeLicenseStatusResponse.java @@ -22,8 +22,7 @@ * @see org.asteriskjava.manager.action.SkypeLicenseStatusAction * @since 1.0.0 */ -public class SkypeLicenseStatusResponse extends ManagerResponse -{ +public class SkypeLicenseStatusResponse extends ManagerResponse { private static final long serialVersionUID = 0L; private Integer callsLicensed; @@ -33,8 +32,7 @@ public class SkypeLicenseStatusResponse extends ManagerResponse * * @return the total number of concurrent Skype calls currently licenced for this system. */ - public Integer getCallsLicensed() - { + public Integer getCallsLicensed() { return callsLicensed; } @@ -43,8 +41,7 @@ public Integer getCallsLicensed() * * @param callsLicensed the total number of concurrent Skype calls currently licenced for this system. */ - public void setCallsLicensed(Integer callsLicensed) - { + public void setCallsLicensed(Integer callsLicensed) { this.callsLicensed = callsLicensed; } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/response/package.html b/src/main/java/org/asteriskjava/manager/response/package.html index 3de9c914d..f7cb6c526 100644 --- a/src/main/java/org/asteriskjava/manager/response/package.html +++ b/src/main/java/org/asteriskjava/manager/response/package.html @@ -1,29 +1,29 @@ - +

      Provides classes that represent the responses that are received - from an Asterisk server in response to an action send via the - Manager API.

      + from an Asterisk server in response to an action send via the + Manager API.

      - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/manager/util/EventAttributesHelper.java b/src/main/java/org/asteriskjava/manager/util/EventAttributesHelper.java new file mode 100644 index 000000000..6f8d14907 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/util/EventAttributesHelper.java @@ -0,0 +1,233 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.util; + +import org.asteriskjava.manager.event.CdrEvent; +import org.asteriskjava.manager.event.UserEvent; +import org.asteriskjava.manager.response.ManagerResponse; +import org.asteriskjava.util.AstUtil; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; +import org.asteriskjava.util.ReflectionUtil; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author Piotr Olaszewski + */ +public class EventAttributesHelper { + private static final Log logger = LogFactory.getLog(EventAttributesHelper.class); + + private EventAttributesHelper() { + } + + public static void setAttributes(Object target, Map attributes, Set ignoredAttributes) { + Map setters; + + setters = ReflectionUtil.getSetters(target.getClass()); + for (Map.Entry entry : attributes.entrySet()) { + Object value; + final Class dataType; + Method setter; + String setterName; + + if (ignoredAttributes != null && ignoredAttributes.contains(entry.getKey())) { + continue; + } + + setterName = ReflectionUtil.stripIllegalCharacters(entry.getKey()); + + /* + * The source property needs special handling as it is already + * defined in java.util.EventObject (the base class of + * ManagerEvent), so we have to translate it. + */ + if ("source".equals(setterName)) { + setterName = "src"; + } else if ("class".equals(setterName)) { + setterName = "clazz"; + } + + setter = setters.get(setterName); + + if (setter == null && !setterName.endsWith("s")) // no exact match + // => try plural + { + setter = setters.get(setterName + "s"); + // but only for maps + if (setter != null && !(setter.getParameterTypes()[0].isAssignableFrom(Map.class))) { + setter = null; + } + } + + // it seems silly to warn if it's a user event -- maybe it was + // intentional + if (setter == null && !(target instanceof UserEvent) && !target.getClass().equals(ManagerResponse.class)) { + + //CDR has dynamic properties + if (target instanceof CdrEvent) { + try { + Method addproperty= CdrEvent.class.getMethod("addDynamicProperties", String.class, String.class); + addproperty.invoke(target, entry.getKey(), entry.getValue().toString()); + } catch (Exception e) { + logger.error("Unable to set Dynamic CDR Property '" + entry.getKey() + "' to '" + entry.getValue(), e); + continue; + } + + } else { + logger.warn("Unable to set property '" + entry.getKey() + "' to '" + entry.getValue() + "' on " + + target.getClass().getName() + + ": no setter. Please report at https://github.com/asterisk-java/asterisk-java/issues"); + + for (Map.Entry entry2 : attributes.entrySet()) { + logger.debug("Key: " + entry2.getKey() + " Value: " + entry2.getValue()); + } + } + } + + if (setter == null) { + continue; + } + + try { + dataType = setter.getParameterTypes()[0]; + + if (dataType == Boolean.class) { + value = AstUtil.isTrue(entry.getValue()); + } else if (dataType.isAssignableFrom(String.class)) { + value = parseString(entry); + } else if (dataType.isAssignableFrom(Map.class)) { + value = parseMap(entry); + } else if (dataType.isAssignableFrom(double.class) || dataType.isAssignableFrom(Double.class)) { + value = parseDouble(entry); + } else if (dataType.isAssignableFrom(long.class) || dataType.isAssignableFrom(Long.class)) { + value = parseLong(entry); + } else if (dataType.isAssignableFrom(int.class) || dataType.isAssignableFrom(Integer.class)) { + value = parseInteger(entry); + } else { + try { + Constructor constructor = dataType.getConstructor(String.class); + // Asterisk sometimes uses yes/no instead of True/False for boolean. java.lang.Boolean(String) doesn't handle this. + if (dataType.isAssignableFrom(Boolean.class)) { + value = constructor.newInstance(AstUtil.convertAsteriskBooleanStringToStandardBooleanString((String) entry.getValue())); + } else value = constructor.newInstance(entry.getValue()); + } catch (Exception e) { + logger.error("Unable to convert value: Called the constructor of " + dataType + " with value '" + + entry.getValue() + "' for the attribute '" + entry.getKey() + "'\n of event type " + + target.getClass().getName() + " with resulting error: " + e.getMessage(), e); + continue; + } + } + + setter.invoke(target, value); + } catch (Exception e) { + logger.error("Unable to set property '" + entry.getKey() + "' to '" + entry.getValue() + "' on " + + target.getClass().getName() + " " + e.getMessage(), e); + } + } + } + + private static Integer parseInteger(Map.Entry entry) { + Integer value; + String stringValue = (String) entry.getValue(); + if (stringValue != null && stringValue.length() > 0) { + value = Integer.parseInt(stringValue); + } else { + value = null; + } + return value; + } + + @SuppressWarnings("unchecked") + private static Map parseMap(Map.Entry entry) { + Map value; + if (entry.getValue() instanceof List) { + List list = (List) entry.getValue(); + value = buildMap(list.toArray(new String[list.size()])); + } else if (entry.getValue() instanceof String) { + value = buildMap((String) entry.getValue()); + } else { + value = null; + } + return value; + } + + @SuppressWarnings("unchecked") + private static Object parseString(Map.Entry entry) { + Object value; + value = entry.getValue(); + if (AstUtil.isNull(value)) { + + value = null; + } + if (value instanceof List) { + StringBuilder strBuff = new StringBuilder(); + for (String tmp : (List) value) { + if (tmp != null && tmp.length() != 0) { + strBuff.append(tmp).append('\n'); + } + } + value = strBuff.toString(); + } + return value; + } + + private static Double parseDouble(Map.Entry entry) { + Double value; + String stringValue = (String) entry.getValue(); + if (stringValue != null && stringValue.length() > 0) { + value = Double.parseDouble(stringValue); + } else { + value = null; + } + return value; + } + + private static Long parseLong(Map.Entry entry) { + Long value; + String stringValue = (String) entry.getValue(); + if (stringValue != null && stringValue.length() > 0) { + value = Long.parseLong(stringValue); + } else { + value = null; + } + return value; + } + + private static Map buildMap(String... lines) { + if (lines == null) { + return null; + } + + final Map map = new LinkedHashMap<>(); + for (String line : lines) { + final int index = line.indexOf('='); + if (index > 0) { + final String key = line.substring(0, index); + final String value = line.substring(index + 1, line.length()); + map.put(key, value); + } else { + logger.warn("Malformed line '" + line + "' for a map property"); + } + } + return map; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/Activity.java b/src/main/java/org/asteriskjava/pbx/Activity.java new file mode 100644 index 000000000..eb6c612e0 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/Activity.java @@ -0,0 +1,20 @@ +package org.asteriskjava.pbx; + +public interface Activity { + /** + * If an activity fails the getLastError contains a description of the cause + * of the error. This method should be called from the 'complete' method of + * the iCallBack listener. + * + * @return error message which caused the activity to fail. + */ + Throwable getLastException(); + + /** + * Set to true once the activity has suceeded. + * + * @return + */ + boolean isSuccess(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/ActivityCallback.java b/src/main/java/org/asteriskjava/pbx/ActivityCallback.java new file mode 100644 index 000000000..5d607d79c --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/ActivityCallback.java @@ -0,0 +1,23 @@ +package org.asteriskjava.pbx; + +/** + * Provides a generic callback mechansim which allows tracking of the progress + * of any of the async methods provided by iPBX. + */ + +public interface ActivityCallback { + + /** + * Called periodically to indicate progress with the task being tracked. The + * number of progress messages sent is dependant on the task. Every activity + * will see a ActivityStatusEnum.START and either ActivityStatusEnum.SUCCESS + * or ActivityStatusEnum.FAILURE + * + * @param activity - the activity which is being monitored + * @param status TODO + * @param message + */ + + void progress(T activity, ActivityStatusEnum status, String message); + +} diff --git a/src/main/java/org/asteriskjava/pbx/ActivityStatusEnum.java b/src/main/java/org/asteriskjava/pbx/ActivityStatusEnum.java new file mode 100644 index 000000000..5bee17987 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/ActivityStatusEnum.java @@ -0,0 +1,15 @@ +package org.asteriskjava.pbx; + +public enum ActivityStatusEnum { + START("Starting"), PROGRESS("Progress"), SUCCESS("Success"), FAILURE("Failure"); + + String defaultMessage; + + ActivityStatusEnum(String defaultMessage) { + this.defaultMessage = defaultMessage; + } + + public String getDefaultMessage() { + return defaultMessage; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/AgiChannelActivityAction.java b/src/main/java/org/asteriskjava/pbx/AgiChannelActivityAction.java new file mode 100644 index 000000000..1b56632cb --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/AgiChannelActivityAction.java @@ -0,0 +1,15 @@ +package org.asteriskjava.pbx; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.pbx.agi.ActivityAgi; + +public interface AgiChannelActivityAction { + + void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException; + + boolean isDisconnect(ActivityAgi activityAgi); + + void cancel(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/AsteriskSettings.java b/src/main/java/org/asteriskjava/pbx/AsteriskSettings.java new file mode 100644 index 000000000..6a2f5194a --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/AsteriskSettings.java @@ -0,0 +1,114 @@ +package org.asteriskjava.pbx; + +public interface AsteriskSettings { + + /** + * The port no. that the asterisk manager api listens on. This should be + * 5060 unless you have re-configured the manager api. + * + * @return the port no. + */ + int getManagerPortNo(); + + /** + * This password MUST match the password (secret=) in manager.conf + * + * @return + */ + String getManagerPassword(); + + /** + * This MUST match the section header (e.g. '[myconnection]') in + * manager.conf + * + * @return + */ + String getManagerUsername(); + + /** + * The IP address of FQND of the Asterisk PBX + * + * @return IP address or FQDN. + */ + String getAsteriskIP(); + + /** + * Asterisk-Java uses conference rooms for a variety of purposes. Just make + * certain that the base address doesn't overlap any conference rooms you + * are currently running on your pbx. You should probably allow 200 + * conference rooms here e.g. (3000-3200) Actions like transfers (and + * conference calls) use a conference room. + * + * @return meetme base address + */ + Integer getMeetmeBaseAddress(); + + /** + * Return true if you Asterisk version doesn't support bridging channels. + * All version after 1.8 support bridging so normally you should returm + * false; + * + * @return false if you asterisk version supports bridging channels. + */ + boolean getDisableBridge(); + + /** + * This is an asterisk dialplan context. Simply pick a context which doesn't + * already exist and use AsteriskPBX.createAgiEntryPoint() to inject the + * necessary dialplan used by asterisk-java + * + * @return an unused asterisk dialplan context. e.g. "asteriskjava" + */ + String getManagementContext(); + + /** + * Return an asterisk dialplan extension (within the above Management + * Context) that will be used to park calls. Just ensure that its a unique + * asterisk dialplan extension name. + */ + String getExtensionPark(); + + /** + * The time (in seconds) to wait for a dial attempt to be answered before + * giving up. Recommend a value of 30. + * + * @return + */ + int getDialTimeout(); + + /** + * Return the SIP header to be used to force a handset to auto-answer when + * dialed. e.g. For Yealink/Snom use return "Call-Info:\; answer-after=0"; + * + * @return + */ + String getAutoAnswer(); + + /** + * Return an asterisk dialplan extension (within the Management Context) + * that will be used to inject the agi dialplan entry point used by + * Activites.. Just ensure that its a unique asterisk dialplan extension + * name. + * + * @return "asterisk-java-agi" + */ + String getAgiExtension(); + + /** + * Return true if the telephony tech you are dialing from can reliably + * detect hangups. (for SIP set to true, POTS set false). + * + * @return + */ + boolean getCanDetectHangup(); + + /** + * The IP address of FQDN of the asterisk-java application. + * Currenly only used if you are doing 'activities' but its + * safer to just set this. + * + * @return + */ + String getAgiHost(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/Call.java b/src/main/java/org/asteriskjava/pbx/Call.java new file mode 100644 index 000000000..a7055a92e --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/Call.java @@ -0,0 +1,112 @@ +package org.asteriskjava.pbx; + +import java.util.Date; +import java.util.List; + +public interface Call { + /** + * Used to identify which channel of a call an operation is to be performed + * on. This is designed to stop the mis-use of some methods which operate on + * a specific channel of a call. The Operand allows the caller to specify + * which channel to operate on without having to explicitly pass in the + * channel. Without this enum they could potentially pass in a channel which + * is not owned by the call. + * + * @author bsutton + */ + + enum OperandChannel { + /** + * this party received (did not originate) the call + */ + ACCEPTING_PARTY, + + /** + * this party originated (dialled) the call + */ + ORIGINATING_PARTY, + + TRANSFER_TARGET_PARTY, + + /** + * is an end point that is on an external trunk + */ + REMOTE_PARTY, + /** + * a local call is a handset attached directly (via sip) to the pbx + */ + LOCAL_PARTY + } + + // Returns true of the given channel is part of this call. + boolean contains(Channel channel); + + // The caller id of the party that accepted (answered) the call. + CallerID getAcceptingPartyCallerID(); + + // The caller id of the party that dialed the call. + CallerID getOriginatingPartyCallerID(); + + // The caller id of the remote party. + CallerID getRemotePartyCallerID(); + + // The date/time the call started. + Date getCallStartTime(); + + // The channel associated with the party that originated (dialed) the call. + Channel getOriginatingParty(); + + // The channel associated with the part that accepted (answered) the call. + Channel getAcceptingParty(); + + Channel getTransferTargetParty(); + + /** + * retrieves the channel associated with the give Operand. + * + * @param lhs + * @return + */ + Channel getOperandChannel(OperandChannel lhs); + + /** + * This method use the CallDirection to determine which leg of the call is + * the local call and which is the called/calling party. It then returns the + * called/calling party. + * + * @return + */ + Channel getRemoteParty(); + + /** + * This method use the CallDirection to determine which leg of the call is + * the local call and which is the called/calling party. It then returns the + * local call . + * + * @return + */ + Channel getLocalParty(); + + /** + * Returns true of the Call can be split into two (or more) separate calls. + * + * @return + */ + boolean canSplit(); + + /** + * Returns the direction of the call. + * The call Direction can be a little esoteric as a call can + * come in and then be transferred out again. So is this an inbound or outbound call? + * + * @return + */ + CallDirection getDirection(); + + /** + * Returns a list of the Channels associated with this call. + * + * @return + */ + List getChannels(); +} diff --git a/src/main/java/org/asteriskjava/pbx/CallDirection.java b/src/main/java/org/asteriskjava/pbx/CallDirection.java new file mode 100644 index 000000000..b055de7c4 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CallDirection.java @@ -0,0 +1,51 @@ +package org.asteriskjava.pbx; + +/** + * Describes the direction of the call. + * + * @author bsutton + */ +public enum CallDirection { + /** + * INBOUND - call + */ + INBOUND(0), + /** + * OUTBOUND - call. + */ + OUTBOUND(1); + // /** + // * JOIN - call was created by joining two existing calls + // */ + // JOIN(2), + // + // /** + // * Often temporary channels are brought up for actions such as parking a + // * call. These calls don't really have a direction in their own right. + // * + // * TODO: is this really need, should the originating call be the + // controlling + // * entity. The problem is that currently we really track 'channels' rather + // * than Calls. + // */ + // TRANSIENT(3); + + private final int dbValue; + + CallDirection(final int dbValue) { + this.dbValue = dbValue; + } + + public static CallDirection valueOf(final int dbValue) { + CallDirection result = null; + + for (final CallDirection direction : CallDirection.values()) { + if (direction.dbValue == dbValue) { + result = direction; + break; + } + } + return result; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/CallHangupListener.java b/src/main/java/org/asteriskjava/pbx/CallHangupListener.java new file mode 100644 index 000000000..92d33af3d --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CallHangupListener.java @@ -0,0 +1,7 @@ +package org.asteriskjava.pbx; + +public interface CallHangupListener { + + void callHungup(Call call); + +} diff --git a/src/main/java/org/asteriskjava/pbx/CallImpl.java b/src/main/java/org/asteriskjava/pbx/CallImpl.java new file mode 100644 index 000000000..8073c6576 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CallImpl.java @@ -0,0 +1,767 @@ +package org.asteriskjava.pbx; + +import org.asteriskjava.pbx.activities.BlindTransferActivity; +import org.asteriskjava.util.DateUtil; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Holds a call which may consist of 0, 1, 2 or 3 channels. When dialing out a + * call The 1st channel is always the call 'originator'. Channel 2 is + * 'accepting' party Channel 3 is a 'third party' which has joined the call via + * a conference mode. The concept of a Call is independent of a particular PBX. + * All channels of a Call must belong to the same PBX as we have no way of + * bridging calls across multiple PBX's anyway. Calls can be established by: 1) + * When a call arrives at the NJR Management inbound context 2) Dialing 3) + * Joining two existing calls The 'originating' channel is the first channel + * introduced to the call and is stored in the zeroth element of the channel + * list. + * + * @author bsutton + */ + +public class CallImpl implements ChannelHangupListener, Call { + private static final Log logger = LogFactory.getLog(CallImpl.class); + + /** + * We give every call a unique call id to help track the calls when checking + * logs + */ + private static final AtomicInteger global_call_identifier_index = new AtomicInteger(); + + /** + * A id that uniquely identifies this call. + */ + private final int _uniquecallID; + + /* + * transfer types + */ + public enum TransferType { + NONE, ASSISTED, BLIND + } + + /** + * The 1st channel is always the call 'originator'. + */ + private Channel _originatingParty; + + /** + * Channel 2 is 'accepting' party + */ + + private Channel _acceptingParty; + + /** + * Channel 3 is a 'third party' which has joined the call via a conference + * mode which would normally be created during a transfer attempt. + */ + private Channel _transferTargetParty; + + /** + * The direct of the call. If it is OUTBOUND then the originating party is + * the local call . If it is INBOUND then the originationg party is the + * caller. + */ + final private CallDirection _direction; + + private CallerID _originatingPartyCallerID = null; + + private CallerID _acceptingPartyCallerID = null; + + /** + * When we attempt to transfer a call to a third party we save the transfer + * target. This allows us to automatically re-try the transfer if the + * initial attempt failed. + */ + private EndPoint _transferTarget = null; + + private TransferType transferType = TransferType.NONE; + + private CallerID _transferTargetCallerID = null; + + private Date _callStarted; + + private Date _holdStarted = null; + + private EndPoint _parkingLot = null; + + private Date _timeAtDialin = null; + + private boolean _parked = false; + + /** + * The primary key for the Contact record. + * + * @return + */ + private Integer _contactId; + + private ArrayList _hangupListeners = new ArrayList<>(); + + /** + * Used to indicate the ownership of the call. SELF - this instance of NJR + * has answered the call and is now considered the owner. REMOTE - some + * other instance of NJR has answered the call. UNOWNED - the call has + * entered the inbound extension but has not been answered by any instance + * of NJR. Note: a calls ownership can change over time. All calls start as + * UNOWNED. If we answer a call it becomes SELF. If we put a call on hold + * and another NJR instances answers it then it can then become REMOTE. + * + * @author bsutton + */ + public enum OWNER { + SELF + } + + private OWNER _owner; + + protected BlindTransferActivity _transferActivity; + + public CallImpl(Channel originatingChannel, CallDirection direction) throws PBXException { + logger.debug("Created call=" + originatingChannel + " direction=" + direction); //$NON-NLS-1$ //$NON-NLS-2$ + this._owner = OWNER.SELF; + this._uniquecallID = CallImpl.global_call_identifier_index.incrementAndGet(); + this._direction = direction; + this._callStarted = DateUtil.getDate(); + this.setOriginatingParty(originatingChannel); + + } + + public CallImpl(Channel originatingChannel, Channel acceptingChannel, CallDirection direction) throws PBXException { + logger.debug("Created call=" + originatingChannel + " direction=" + direction); //$NON-NLS-1$ //$NON-NLS-2$ + this._owner = OWNER.SELF; + this._uniquecallID = CallImpl.global_call_identifier_index.incrementAndGet(); + this._direction = direction; + this._callStarted = DateUtil.getDate(); + this.setOriginatingParty(originatingChannel); + this.setAcceptingParty(acceptingChannel); + + } + + public CallImpl(Channel agent, Channel callee) throws PBXException { + this._owner = OWNER.SELF; + this._uniquecallID = CallImpl.global_call_identifier_index.incrementAndGet(); + this._direction = CallDirection.OUTBOUND; + this._callStarted = DateUtil.getDate(); + this.setOriginatingParty(agent); + this.setAcceptingParty(callee); + + } + + /** + * Joins a specific channel from this call with a specific channel from + * another call which results in a new Call object being created. Channels + * that do not participate in the join are left in their original Call. + * + * @param originatingOperand the channel from this call that will + * participate in the join as the originating Channel + * @param rhs the call we are joining to. + * @param acceptingOperand the channel from the rhs call that will + * participate in the join as the accepting channel. + * @return + * @throws PBXException + */ + public CallImpl join(OperandChannel originatingOperand, Call rhs, OperandChannel acceptingOperand, + CallDirection direction) throws PBXException { + CallImpl joinTo = (CallImpl) rhs; + + Channel originatingParty = null; + Channel acceptingParty = null; + + // Pull the originating party from the this call. + originatingParty = this.getOperandChannel(originatingOperand); + if (originatingParty != null && originatingParty.isLive()) + originatingParty.removeListener(this); + + // Pull the accepting party from the other 'call' as the accepting + // party. + acceptingParty = rhs.getOperandChannel(acceptingOperand); + if (acceptingParty != null && acceptingParty.isLive()) + acceptingParty.removeListener((CallImpl) rhs); + + if (originatingParty == null || !originatingParty.isLive() || acceptingParty == null || !acceptingParty.isLive()) + throw new PBXException("Call.HangupDuringJoin"); //$NON-NLS-1$ + + CallImpl joined = new CallImpl(originatingParty, direction); + joined.setAcceptingParty(acceptingParty); + joined._owner = OWNER.SELF; + + joined._callStarted = minDate(this._callStarted, joinTo._callStarted); + + joined._holdStarted = minDate(this._holdStarted, joinTo._holdStarted); + + joined._timeAtDialin = minDate(this._timeAtDialin, joinTo._timeAtDialin); + + logger.debug("Joined two calls lhs=" + this + ", rhs=" + joinTo); //$NON-NLS-1$//$NON-NLS-2$ + + return joined; + } + + private Date minDate(Date d1, Date d2) { + + if (d1 == null) { + return d2; + } + if (d2 == null) { + return d1; + } + if (d1.before(d2)) { + return d1; + } + return d2; + } + + // + // /** + // * Joins a specific channel from this call with a specific channel from + // another call which results in a new Call object + // * being created. + // * + // * Channels that do not participate in the join are left in their original + // Call. + // * + // * @param lhsOperand the channel from this call that will participate in + // the join + // * @param rhs the call we are joining to. + // * @param rhsOperand the channel from the rhs call that will participate + // in the join. + // * @return + // * @throws PBXException + // */ + // public Call join(OperandChannel lhsOperand, iCall rhs, OperandChannel + // rhsOperand) throws PBXException + // { + // Call joinTo = (Call) rhs; + // + // // // Check there is no transfer party. + // // if (this._transferTargetParty != null || joinTo._transferTargetParty + // != null) + //// throw new IllegalArgumentException("Neither call in a 'Join' may have a + // third party"); //$NON-NLS-1$ + // // + // // // Check that we only have one active party + // // if (this._originatingParty != null && this._acceptingParty != null) + // // throw new IllegalArgumentException( + //// "The call " + this + " has more than one active channel which is not + // allowed."); //$NON-NLS-1$ //$NON-NLS-2$ + // // + // // if (joinTo._originatingParty != null && joinTo._acceptingParty != + // null) + // // throw new IllegalArgumentException( + //// "The call " + joinTo + " has more than one active channel which is not + // allowed."); //$NON-NLS-1$ //$NON-NLS-2$ + // + // iChannel originatingParty = null; + // iChannel acceptingParty = null; + // + // // First select the remote party from this call. + // // For no particular reason we use 'this' as the originating party. + // originatingParty = this.getRemoteParty(); + // if (originatingParty != null && originatingParty.isLive()) + // originatingParty.removeListener(this); + // + // // Now select the remote party from the other 'call' as the accepting + // // party. + // acceptingParty = rhs.getRemoteParty(); + // if (acceptingParty != null && acceptingParty.isLive()) + // acceptingParty.removeListener((Call) rhs); + // + // if (originatingParty == null || acceptingParty == null) + // throw new PBXException(Messages.getString("Call.HangupDuringJoin")); + // //$NON-NLS-1$ + // + // /** + // * We just choose one of the directions as it doesn't really matter + // */ + // Call joined = new Call(originatingParty, this._direction); + // joined.setAcceptingParty(acceptingParty); + // joined._owner = OWNER.SELF; + // + // + // joined._callStarted = DateUtils.min(this._callStarted, + // joinTo._callStarted); + // + // joined._holdStarted = DateUtils.min(this._holdStarted, + // joinTo._holdStarted); + // + // joined._timeAtDialin = DateUtils.min(this._timeAtDialin, + // joinTo._timeAtDialin); + // + // // The selection of _didEntity is arbitrary + // if (this._didEntity != null) + // joined._didEntity = this._didEntity; + // else + // joined._didEntity = joinTo._didEntity; + // + // logger.debug("Joined two calls lhs=" + this + ", rhs=" + joinTo); + // //$NON-NLS-1$//$NON-NLS-2$ + // + // return joined; + // } + + /** + * Splits a channel out of a call into a separate call. This method should + * only be called from the SplitActivity. + * + * @return the resulting call. + * @throws PBXException + */ + public Call split(OperandChannel channelToSplit) throws PBXException { + Channel channel = this.getOperandChannel(channelToSplit); + channel.removeListener(this); + + CallDirection direction = CallDirection.INBOUND; + + // If this is the operator channel we need to flip the default + // direction. + if (this.getLocalParty() != null && this.getLocalParty().isSame(channel)) { + direction = CallDirection.OUTBOUND; + } + + CallImpl call = new CallImpl(channel, direction); + call._owner = OWNER.SELF; + + // clear the channel have just split out. + switch (channelToSplit) { + case ACCEPTING_PARTY: + this.setAcceptingParty(null); + break; + case LOCAL_PARTY: + if (this._direction == CallDirection.INBOUND) { + this.setAcceptingParty(null); + } else { + this.setOriginatingParty(null); + } + break; + case ORIGINATING_PARTY: + this.setOriginatingParty(null); + break; + case REMOTE_PARTY: + if (this._direction == CallDirection.INBOUND) + this.setOriginatingParty(null); + else + this.setAcceptingParty(null); + break; + case TRANSFER_TARGET_PARTY: + this.setTransferTargetParty(null); + break; + default: + break; + } + + return call; + } + + public Call split(Channel channelToSplit) throws PBXException { + channelToSplit.removeListener(this); + CallDirection direction = CallDirection.INBOUND; + // If this is the operator channel we need to flip the default + // direction. + if (this.getLocalParty() != null && this.getLocalParty().isSame(channelToSplit)) { + direction = CallDirection.OUTBOUND; + } + + CallImpl call = new CallImpl(channelToSplit, direction); + call._owner = OWNER.SELF; + if (_acceptingParty != null && _acceptingParty.isSame(channelToSplit)) + _acceptingParty = null; + if (_originatingParty != null && _originatingParty.isSame(channelToSplit)) + _originatingParty = null; + if (_transferTargetParty != null && _transferTargetParty.isSame(channelToSplit)) + _transferTargetParty = null; + return call; + + } + + @Override + public void channelHangup(Channel channel, Integer cause, String causeText) { + try { + if (isSameChannel(this._originatingParty, channel)) { + this.setOriginatingParty(null); + logger.debug("Removed originatingParty=" + channel + " from Call=" + this._uniquecallID //$NON-NLS-1$ //$NON-NLS-2$ + + " as channel was hung up"); //$NON-NLS-1$ + } else if (isSameChannel(this._acceptingParty, channel)) { + this.setAcceptingParty(null); + logger.debug("Removed acceptingParty=" + channel + " from Call=" + this._uniquecallID //$NON-NLS-1$ //$NON-NLS-2$ + + " as channel was hung up"); //$NON-NLS-1$ + + } else if (isSameChannel(this._transferTargetParty, channel)) { + this.setTransferTargetParty(null); + logger.debug("Removed transferTarget=" + channel + " from Call=" + this._uniquecallID //$NON-NLS-1$ //$NON-NLS-2$ + + " as channel was hung up"); //$NON-NLS-1$ + } else { + logger.warn("Received hangup for unknown channel=" + channel.getChannelId() + " on Call=" //$NON-NLS-1$ //$NON-NLS-2$ + + this._uniquecallID + " as channel was hung up"); //$NON-NLS-1$ + } + if (!this.isLive()) { + notifyCallHangupListeners(); + } + } catch (PBXException e) { + // not much we can do here so just log it + logger.error(e, e); + } + } + + private boolean isSameChannel(Channel lhs, Channel rhs) { + return lhs != null && rhs != null && lhs.isSame(rhs); + } + + private void notifyCallHangupListeners() { + for (CallHangupListener listener : this._hangupListeners) { + listener.callHungup(this); + } + + } + + /** + * Returns the originating channel for this call. e.g. the first channel + * that came up. Whilst a call must always start with an originating channel + * as a call is shutting down it will get to the point where it will have no + * channels. In these cases the return will be null. + * + * @return null or the originating channel. + */ + + @Override + public Channel getOriginatingParty() { + return this._originatingParty; + } + + // /** + // * Call this method to mark this call as owned by another instance of NJR + // as + // * that instance has answered the call. The only time a calls ownership + // can + // * transition is when the call is answered by an instances of NJR or the + // * call is transfered to the vacant transfer extension. Roaming calls are + // * still owned by the NJR instance that originally answered the call. + // */ + // public void callAnsweredRemotely() + // { + // this._owner = OWNER.REMOTE; + // + // } + + // private void callIsTransferring() throws PBXException + // { + // if (this.holdStarted == null) + // { + // this.holdStarted = DateUtil.getDate(); + // } + // this._state = Call.CallState.TRANSFER; + // } + + /** + * Call this method to indicate that this is an outbound call originated by + * this NJR instance. These type of calls are not seen by a remote operator + * unless they are put on hold. + * + * @param remoteChannel - the remote channel this call connected to when + * dialing. + * @throws PBXException + */ + public void callDialedOut(Channel remoteChannel, CallerID fromClid, CallerID toClid) throws PBXException { + + // -- moved to ANSWER + } + + @Override + public Date getCallStartTime() { + return this._callStarted; + } + + public Integer getContactId() { + return this._contactId; + } + + /** + * The current transfer target. + * + * @return + */ + public EndPoint getTransferTarget() { + return this._transferTarget; + } + + public CallerID getTransferTargetCallerID() { + return this._transferTargetCallerID; + } + + @Override + public CallerID getAcceptingPartyCallerID() { + return this._acceptingPartyCallerID; + } + + @Override + public CallerID getOriginatingPartyCallerID() { + return this._originatingPartyCallerID; + } + + @Override + public CallerID getRemotePartyCallerID() { + CallerID remoteCallerID = null; + + if (this.getDirection() == CallDirection.INBOUND) { + remoteCallerID = this.getOriginatingPartyCallerID(); + } else { + remoteCallerID = this.getAcceptingPartyCallerID(); + } + return remoteCallerID; + } + + public Date getHoldStartTime() { + return this._holdStarted; + } + + public EndPoint getParkingLot() { + return this._parkingLot; + } + + public Date getTimeAtDialIn() { + return this._timeAtDialin; + } + + public TransferType getTransferType() { + return this.transferType; + } + + public String getUniqueCallID() { + /* + * this is a unique call identifier. + */ + return "" + this._uniquecallID; //$NON-NLS-1$ + } + + public boolean isCallParked() { + return this._parked; + } + + private void setOriginatingParty(Channel originatingParty) throws PBXException { + this._originatingParty = originatingParty; + + if (originatingParty != null) { + if (!this._originatingParty.canDetectHangup() && this._acceptingParty != null + && !this._acceptingParty.canDetectHangup()) + throw new PBXException("Call.BothWithNoHangupDetection"); //$NON-NLS-1$ + + this._originatingParty.addHangupListener(this); + } + } + + private void setAcceptingParty(Channel acceptingParty) throws PBXException { + this._acceptingParty = acceptingParty; + + if (acceptingParty != null) { + if (!this._acceptingParty.canDetectHangup() && this._originatingParty != null + && !this._originatingParty.canDetectHangup()) + throw new PBXException("Call.BothWithNoHangupDetection"); //$NON-NLS-1$ + + this._acceptingParty.addHangupListener(this); + } + } + + private void setTransferTargetParty(Channel transferTargetParty) { + this._transferTargetParty = transferTargetParty; + + if (transferTargetParty != null) { + this._transferTargetParty.addHangupListener(this); + } + } + + /** + * The contact id is just used when refilling the list of contacts so we + * know which one is selected at the moment. It probably should be stored + * here! + * + * @param _contactId + */ + public void setContactId(final Integer _contactId) { + this._contactId = _contactId; + + } + + // private void setTransferType(final TransferType tType) + // { + // this.transferType = tType; + // } + + @Override + public CallDirection getDirection() { + return this._direction; + } + + /** + * Call this method to get a notification when this call hangs up. + * + * @param listener + * @return true if the hangup listener was added. False if the call has + * already been hungup. + */ + public boolean addHangupListener(CallHangupListener listener) { + boolean callStillUp = true; + + if ((this._originatingParty != null && this._originatingParty.isLive()) + || (this._acceptingParty != null && this._acceptingParty.isLive()) + || (this._transferTargetParty != null && this._transferTargetParty.isLive())) + this._hangupListeners.add(listener); + else + callStillUp = false; + return callStillUp; + + } + + /** + * returns true if the call has any active channels. + * + * @return + */ + public boolean isLive() { + boolean live = false; + if ((this._originatingParty != null && this._originatingParty.isLive()) + || (this._acceptingParty != null && this._acceptingParty.isLive()) + || (this._transferTargetParty != null && this._transferTargetParty.isLive())) + live = true; + return live; + } + + /** + * @return true if this call is owned by another instance of NJR. + */ + public OWNER getOwner() { + return this._owner; + } + + @Override + public String toString() { + return "State: Originating Channel:" + getOriginatingParty() + " Direction: " //$NON-NLS-1$ //$NON-NLS-2$ + // //$NON-NLS-3$ + + this.getDirection() + " accepting:" + this._acceptingParty; //$NON-NLS-1$ + } + + @Override + public boolean contains(Channel parkChannel) { + boolean found = false; + + if (isSameChannel(this._originatingParty, parkChannel)) { + found = true; + } else if (isSameChannel(this._acceptingParty, parkChannel)) { + found = true; + } else if (isSameChannel(this._transferTargetParty, parkChannel)) { + found = true; + } + + return found; + } + + @Override + public Channel getAcceptingParty() { + return this._acceptingParty; + } + + @Override + public Channel getTransferTargetParty() { + return this._transferTargetParty; + } + + @Override + /** + * This method use the CallDirection to determine which leg of the call is + * the local call and which is the called/calling party. It then returns the + * called/calling party. + * + * @return + */ + public Channel getRemoteParty() { + Channel remoteChannel = null; + + if (this.getDirection() == CallDirection.INBOUND) { + remoteChannel = this.getOriginatingParty(); + } else { + remoteChannel = this.getAcceptingParty(); + } + if (remoteChannel == null) { + logger.error("remoteChannel is null for {}" + this.getDirection()); + } + return remoteChannel; + + } + + /** + * This method use the CallDirection to determine which leg of the call is + * the local call and which is the called/calling party. It then returns the + * local call . + * + * @return + */ + @Override + public Channel getLocalParty() { + + if (this.getDirection() == CallDirection.OUTBOUND) + return this.getOriginatingParty(); + + return this.getAcceptingParty(); + + } + + @Override + public boolean canSplit() { + return (this._originatingParty != null && this._acceptingParty != null && this._transferTargetParty == null); + } + + @Override + public Channel getOperandChannel(OperandChannel operand) { + final Channel channel; + + switch (operand) { + case ACCEPTING_PARTY: + channel = this._acceptingParty; + break; + case ORIGINATING_PARTY: + channel = this._originatingParty; + break; + case REMOTE_PARTY: + channel = getRemoteParty(); + break; + case TRANSFER_TARGET_PARTY: + channel = this._transferTargetParty; + break; + case LOCAL_PARTY: + channel = this.getLocalParty(); + break; + default: + // should never happen + throw new IllegalArgumentException("An unsupported operand was passed:" + operand); //$NON-NLS-1$ + } + if (channel == null) { + logger.warn("failed to get channel for " + operand); + } + return channel; + } + + public boolean isSame(Call rhs) { + return this._uniquecallID == ((CallImpl) rhs)._uniquecallID; + } + + /** + * Returns all of the Channels associated with this call. + */ + @Override + public List getChannels() { + List channels = new LinkedList<>(); + if (_acceptingParty != null) + channels.add(_acceptingParty); + if (_originatingParty != null) + channels.add(_originatingParty); + if (_transferTargetParty != null) + channels.add(_transferTargetParty); + return channels; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/CallStateAnswered.java b/src/main/java/org/asteriskjava/pbx/CallStateAnswered.java new file mode 100644 index 000000000..5d9a0309e --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CallStateAnswered.java @@ -0,0 +1,21 @@ +package org.asteriskjava.pbx; + +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class CallStateAnswered extends CallStateData { + @SuppressWarnings("unused") + private static final Log logger = LogFactory.getLog(CallStateAnswered.class); + + // The channel that accepted the call. + private Channel _acceptingParty; + + public CallStateAnswered(Channel acceptingParty) { + this._acceptingParty = acceptingParty; + } + + public Channel getAcceptingParty() { + return this._acceptingParty; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/CallStateData.java b/src/main/java/org/asteriskjava/pbx/CallStateData.java new file mode 100644 index 000000000..656421811 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CallStateData.java @@ -0,0 +1,4 @@ +package org.asteriskjava.pbx; + +public class CallStateData { +} diff --git a/src/main/java/org/asteriskjava/pbx/CallStateDataNewInbound.java b/src/main/java/org/asteriskjava/pbx/CallStateDataNewInbound.java new file mode 100644 index 000000000..4541e161f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CallStateDataNewInbound.java @@ -0,0 +1,26 @@ +package org.asteriskjava.pbx; + +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class CallStateDataNewInbound extends CallStateData { + @SuppressWarnings("unused") + private static final Log logger = LogFactory.getLog(CallStateDataNewInbound.class); + + CallerID _originatingPartyCallerID; + + private final String _fromDID; + + public CallStateDataNewInbound(String fromDID, CallerID originatingPartyCallerID) { + this._originatingPartyCallerID = originatingPartyCallerID; + this._fromDID = fromDID; + } + + public CallerID getOriginatingPartyCallerID() { + return this._originatingPartyCallerID; + } + + public String getFromDID() { + return this._fromDID; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/CallStateDataParked.java b/src/main/java/org/asteriskjava/pbx/CallStateDataParked.java new file mode 100644 index 000000000..e1ac74a7d --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CallStateDataParked.java @@ -0,0 +1,11 @@ +package org.asteriskjava.pbx; + +public class CallStateDataParked extends CallStateData { + + EndPoint _parkingLot; + + public CallStateDataParked(EndPoint parkingLot) { + this._parkingLot = parkingLot; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/CallStateDataTransfer.java b/src/main/java/org/asteriskjava/pbx/CallStateDataTransfer.java new file mode 100644 index 000000000..c0f2d4b96 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CallStateDataTransfer.java @@ -0,0 +1,41 @@ +package org.asteriskjava.pbx; + +import org.asteriskjava.pbx.CallImpl.TransferType; +import org.asteriskjava.pbx.activities.BlindTransferActivity; + +public class CallStateDataTransfer extends CallStateData { + + private TransferType _transferType; + /** + * the end point we are attempting to transfer the call to. + */ + private EndPoint _transferTarget; + + private CallerID _transferTargetCallerID; + + private BlindTransferActivity _transferActivity; + + public CallStateDataTransfer(TransferType transferType, EndPoint transferTarget, CallerID transferTargetCallerID, + BlindTransferActivity transferActivity) { + this._transferType = transferType; + this._transferTarget = transferTarget; + this._transferTargetCallerID = transferTargetCallerID; + this._transferActivity = transferActivity; + } + + public EndPoint getTransferTarget() { + return this._transferTarget; + } + + public CallerID getTransferTargetCallerID() { + return this._transferTargetCallerID; + } + + public TransferType getTransferType() { + return this._transferType; + } + + public BlindTransferActivity getActivity() { + return this._transferActivity; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/CallerID.java b/src/main/java/org/asteriskjava/pbx/CallerID.java new file mode 100644 index 000000000..7c32c9ea3 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CallerID.java @@ -0,0 +1,37 @@ +package org.asteriskjava.pbx; + +public interface CallerID { + /** + * Gets the number component of the caller id. + * + * @return the callerid's number + */ + String getNumber(); + + /** + * Gets the name component of the caller id. + * + * @return the callerid's name + */ + String getName(); + + /** + * Controls whether this caller id should be presented to the remote end. + * + * @param hide - if true then the caller id will be hidden. + */ + void setHideCallerID(boolean hide); + + /** + * @return true if the caller id is marked as hidden. + */ + boolean isHideCallerID(); + + /** + * Returns true if the caller id number is blank or equal to 'unknown'. + * + * @return + */ + boolean isUnknown(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/Channel.java b/src/main/java/org/asteriskjava/pbx/Channel.java new file mode 100644 index 000000000..93302abef --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/Channel.java @@ -0,0 +1,188 @@ +package org.asteriskjava.pbx; + +import java.util.concurrent.TimeUnit; + +/** + * Provides an abstraction for an channel object which is independant of the + * underlying PBX. + * + * @author bsutton + */ +public interface Channel { + /** + * Compares if two channels are the same logical channel on the pbx. This + * comparison uses the full unique name of the channel not just the + * abbreviated peer name. e.g. SIP/100-00000100 + * + * @param rhs + * @return + */ + boolean isSame(Channel rhs); + + boolean isSame(String channelName, String uniqueID); + + /* + * This comparision uses just the peer name. e.g. SIP/100 + */ + boolean sameEndPoint(Channel rhs); + + /* + * This comparision uses just the peer name. e.g. SIP/100 + */ + boolean sameEndPoint(EndPoint extensionRoaming); + + /** + * Compares if this channel is the same as the named channel. + * + * @param channelName + * @return + */ + boolean sameExtenededChannelName(String channelName); + + /** + * This method does not actually change the state of the channel, rather it + * is intended to be used to record the fact that the state has changed. + * + * @see public iPBX.iParkCallActivity park(iChannel channel, Direction + * direction, boolean parkState) for a method which actually parks the + * channel. + */ + void setParked(boolean parked); + + /** + * This method does not actually change the state of the channel, rather it + * is intended to be used to record the fact that the state has changed. + * + * @see public iPBX.iMuteCallActivity mute(iChannel channel, Direction + * direction, boolean muteState) for a method which actually mutes the + * channel. + */ + void setMute(boolean muteState); + + /** + * Each channel is assigned a unique PBX independent id to help track the + * channels when logging. + * + * @return + */ + long getChannelId(); + + /** + * Returns true if the channel is alive. A channel is considered to be alive + * from the moment it is created until we get a notification that it has + * been hungup. + * + * @return + */ + boolean isLive(); + + /** + * Adds a listener to the channel. The channel will send a hungup + * notification to the listener when it hungup. A channel must be able to + * support multiple listeners. + * + * @param call + */ + void addHangupListener(ChannelHangupListener listener); + + void removeListener(ChannelHangupListener listener); + + /** + * Returns true if the given endpont is currently connected to this channel. + * + * @param extension + * @return + */ + boolean isConnectedTo(EndPoint endPoint); + + /** + * returns a fully qualifed channel name which includes the tech. e.g. + * SIP/100-00000342 + * + * @return + */ + String getChannelName(); + + EndPoint getEndPoint(); + + /** + * Checks if this channel is currently mute. A channel is mute if the party + * connected to this channel cannot hear any audio. + * + * @return + */ + boolean isMute(); + + /** + * In Asterisk speak, this method returns true if it is a LOCAL/ channel Not + * quite certain how this will map to other pbx's + * + * @return + */ + boolean isLocal(); + + /** + * @return true if the channel is currently parked. + */ + boolean isParked(); + + /** + * Returns true if the channel has been marked as in a zombie state. + * + * @return + */ + boolean isZombie(); + + /** + * @return true if the channel was originated from the console + * (Console/DSP). + */ + boolean isConsole(); + + /** + * Returns the current callerid for this channel. Note: on some systems this + * involves a round trip to the pbx. + * + * @return + */ + CallerID getCallerID(); + + /** + * Returns a PBX specific version of the Channel name. + * + * @return + */ + String getExtendedChannelName(); + + void notifyHangupListeners(Integer cause, String causeText); + + boolean canDetectHangup(); + + boolean isQuiescent(); + + boolean hasCallerID(); + + AgiChannelActivityAction getCurrentActivityAction(); + + void setCurrentActivityAction(AgiChannelActivityAction action); + + void setIsInAgi(boolean b); + + boolean isInAgi(); + + String getUniqueId(); + + boolean waitForChannelToReachAgi(long timeout, TimeUnit timeunit) throws InterruptedException; + + void setCallerId(CallerID buildCallerID); + + /** + * Called to rename a channel + * + * @param newname the new name of the channel + * @throws InvalidChannelName + */ + + void rename(String newName, String uniqueId) throws InvalidChannelName; + +} diff --git a/src/main/java/org/asteriskjava/pbx/ChannelFactory.java b/src/main/java/org/asteriskjava/pbx/ChannelFactory.java new file mode 100644 index 000000000..b49adb4a3 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/ChannelFactory.java @@ -0,0 +1,18 @@ +package org.asteriskjava.pbx; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * Currently this factories only purposes is to serve up globally unique channel + * id's which every new channel must be assigned. + * + * @author bsutton + */ +public class ChannelFactory { + + private final static AtomicLong nextChannelId = new AtomicLong(); + + public static long getNextChannelId() { + return nextChannelId.incrementAndGet(); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/ChannelHangupListener.java b/src/main/java/org/asteriskjava/pbx/ChannelHangupListener.java new file mode 100644 index 000000000..504e36225 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/ChannelHangupListener.java @@ -0,0 +1,12 @@ +package org.asteriskjava.pbx; + +/** + * Used to notify channel listeners of state changes to a channel. + * + * @author bsutton + */ +public interface ChannelHangupListener { + // Called by the channel when it is being hungup + void channelHangup(Channel channel, Integer cause, String causeText); + +} diff --git a/src/main/java/org/asteriskjava/pbx/CompletionAdaptor.java b/src/main/java/org/asteriskjava/pbx/CompletionAdaptor.java new file mode 100644 index 000000000..9e36e5cdc --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/CompletionAdaptor.java @@ -0,0 +1,44 @@ +package org.asteriskjava.pbx; + +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * This is a utility class designed to wait for an activity to complete. When + * starting an activity for that you want to wait until completion pass this + * class as the iCallback listener and then call waitForCompletion. + * waitForCompletion will not return until the activity completes. + * + * @param + * @author bsutton + */ +public class CompletionAdaptor implements ActivityCallback { + private static final Log logger = LogFactory.getLog(CompletionAdaptor.class); + + CountDownLatch _latch = new CountDownLatch(1); + + @Override + public void progress(final T activity, ActivityStatusEnum status, String message) { + if (status == ActivityStatusEnum.FAILURE || status == ActivityStatusEnum.SUCCESS) { + _latch.countDown(); + } + } + + public void waitForCompletion(long timeout, TimeUnit unit) { + // wait until the activity completes + try { + if (!_latch.await(timeout, unit)) { + Exception e = new Exception("Timeout waiting for activity to complete (" + timeout + " " + unit + ")"); + logger.error(e, e); + } + } catch (final InterruptedException e) { + // should never happen + CompletionAdaptor.logger.error(e, e); + } + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/DTMFTone.java b/src/main/java/org/asteriskjava/pbx/DTMFTone.java new file mode 100644 index 000000000..0eab4c25e --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/DTMFTone.java @@ -0,0 +1,23 @@ +package org.asteriskjava.pbx; + +/** + * Used to indicate the set of possible DTMF tones which can be sent. + * + * @author bsutton + */ +public enum DTMFTone { + ZERO('0'), ONE('1'), TWO('2'), THREE('3'), FOUR('4'), FIVE('5'), SIX('6'), SEVEN('7'), EIGHT('8'), NINE('9'), + HASH('#'), STAR('*'); + + private final String character; + + DTMFTone(final char character) { + this.character = new String(new char[]{character}); + } + + @Override + public String toString() { + return this.character; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/DefaultAsteriskSettings.java b/src/main/java/org/asteriskjava/pbx/DefaultAsteriskSettings.java new file mode 100644 index 000000000..5dc7f73c2 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/DefaultAsteriskSettings.java @@ -0,0 +1,95 @@ +package org.asteriskjava.pbx; + +/** + * A convenience class that provides a set of defaults that will work + * for most people. + *

      + * You can over-ride any specific methods for settings that you need to change. + *

      + * Key thing to watch out for is that we user a meetme range of 3000-3200. + * If you are already using this range for other meetme rooms then you need + * to over-ride the getMeetMeBaseAddress. + *

      + * If you are using handsets other than yealink or snom you should also over-ride + * the getAutoAnswer settings. + * + * @author bsutton + */ +public abstract class DefaultAsteriskSettings implements AsteriskSettings { + + @Override + public int getManagerPortNo() { + return 5060; + } + + @Override + public Integer getMeetmeBaseAddress() { + // We use conference rooms. Just make certain that the base address + // doesn't overlap any conference rooms you are currently running on your pbx. + // You should probably allow 200 conference rooms here e.g. (3000-3200) + // Actions like transfers (and conference calls) use a conference room. + return 3000; + } + + @Override + public boolean getDisableBridge() { + // Return false if you version of asterisk supports bridging channels. + // All version after 1.8 support bridging. + return false; + } + + @Override + public String getManagementContext() { + // This is an asterisk dialplan context. + // Simply pick a context which doesn't already exist + // and use AsteriskPBX.createAgiEntryPoint() + // to inject the necessary dialplan used by asterisk-java + return "asteriskjava"; + } + + @Override + public String getExtensionPark() { + // Return an asterisk dialplan extension (within the Management Context) + // that will be used to park calls. + // Just ensure that its a unique asterisk dialplan extension name. + return "asterisk-java-park"; + } + + @Override + public int getDialTimeout() { + // Return the amount of time to wait (in seconds) when dialing before we give up + // when the call isn't answered + return 30; + } + + /* + * If you are using handsets other than yealink or snom you should over-ride + * these method to return the correct auto-answer string for you handset type. + * + * If you neve use the auto answer feature in the dial command you can + * ignore this setting. + */ + @Override + public String getAutoAnswer() { + // Return the auto-answer heading used by your organisations handsets + // to force them to auto-answer when we ring the handset. + // Bad luck if you have incompatible handsets. + return "Call-Info:\\; answer-after=0"; + } + + @Override + public String getAgiExtension() { + // Return an asterisk dialplan extension (within the Management Context) + // that will be used to inject the agi dialplan entry point used by Activites.. + // Just ensure that its a unique asterisk dialplan extension name. + return "asterisk-java-agi"; + } + + @Override + public boolean getCanDetectHangup() { + // Return try if the telephony tech you are dialing from can reliabily + // detect hangups. + return true; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/DialPlanExtension.java b/src/main/java/org/asteriskjava/pbx/DialPlanExtension.java new file mode 100644 index 000000000..9e0154aee --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/DialPlanExtension.java @@ -0,0 +1,85 @@ +package org.asteriskjava.pbx; + +/** + * Represents an asterisk dial plan extension such as: [njr-operator] + * njr-inbound,1,xxxxx In the above example njr-inbound is the dialplan + * extension. This class primarily exists to stop common mistakes that can occur + * if we pass this around as a simple string. + * + * @author bsutton + */ +public class DialPlanExtension implements EndPoint { + + // the dial plan extension. + String _extension; + final boolean _empty; + + public DialPlanExtension(String extension) { + if (extension == null || extension.trim().length() == 0) { + this._empty = true; + this._extension = ""; + } else { + this._extension = extension.trim(); + this._empty = false; + } + } + + @Override + public int compareTo(EndPoint rhs) { + return this._extension.compareTo(rhs.getSimpleName()); + } + + @Override + public boolean isSame(EndPoint rhs) { + return this.compareTo(rhs) == 0; + } + + @Override + public boolean isLocal() { + return false; + } + + @Override + public boolean isSIP() { + return false; + } + + /** + * The same as getSimpleName as in this case the Tech is really just an + * identifier rather than a legitimate tech that the pbx understands. + */ + @Override + public String getFullyQualifiedName() { + return this._extension; + } + + @Override + public String getSimpleName() { + return this._extension; + } + + @Override + public String getSIPSimpleName() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isUnknown() { + // TODO Auto-generated method stub + return false; + } + + @Override + public TechType getTech() { + return TechType.DIALPLAN; + } + + public String toString() { + return this._extension; + } + + @Override + public boolean isEmpty() { + return false; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/EndPoint.java b/src/main/java/org/asteriskjava/pbx/EndPoint.java new file mode 100644 index 000000000..0288f3995 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/EndPoint.java @@ -0,0 +1,66 @@ +package org.asteriskjava.pbx; + +/** + * Provides an abstract interface for entities which can be dialed. + *

      + * This encompasses entities such as: Phone extensions SIPPeers Asterisk + * extensions External phone numbers + * + * @author bsutton + */ +public interface EndPoint extends Comparable { + boolean isSame(EndPoint rhs); + + boolean isLocal(); + + boolean isSIP(); + + /** + * Returns the fully qualified name of the EndPoint including the tech. e.g. + * SIP/100 + * + * @return + */ + String getFullyQualifiedName(); + + /** + * Returns the simple name of the EndPoint sans the tech. e.g. SIP/100 would + * be returned as 100. + * + * @return + */ + String getSimpleName(); + + /** + * Returns the simple name of a SIP EndPoint sans the tech. e.g. SIP/100 + * would be returned as 100. If the endpoint is not actually a SIP end point + * then this method returns the full end point name. + * + * @return + */ + String getSIPSimpleName(); + + /** + * Returns true if the tech is not know for this end point. + * + * @return + */ + boolean isUnknown(); + + /** + * Returns the Tech that is used to reach this endpoint. + * + * @return + */ + TechType getTech(); + + boolean isEmpty(); + + /** + * Sets the tech on the end point to the specified tech. + * + * @param sip + */ + // public void setTech(Tech tech); + +} diff --git a/src/main/java/org/asteriskjava/pbx/InvalidChannelName.java b/src/main/java/org/asteriskjava/pbx/InvalidChannelName.java new file mode 100644 index 000000000..834ad3287 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/InvalidChannelName.java @@ -0,0 +1,10 @@ +package org.asteriskjava.pbx; + +public class InvalidChannelName extends Exception { + private static final long serialVersionUID = 1L; + + public InvalidChannelName(final String message) { + super(message); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/ListenerPriority.java b/src/main/java/org/asteriskjava/pbx/ListenerPriority.java new file mode 100644 index 000000000..de211bbb0 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/ListenerPriority.java @@ -0,0 +1,32 @@ +package org.asteriskjava.pbx; + +public enum ListenerPriority { + /** + * Provide access to events in near real time for specialised services that + * need priority access to events. Realtime events are sent before any other + * listeners get a chance to process the events. With the event dispatcher + * running in its own thread. This means that they are passed without delay. + * You must also ensure that you don't delay the processing of these + * messages as there may be real time event listeners. If you are concerned + * that you are going to delay the processing then you need to add in your + * own ManagerEventQueue to insulate other priority listeners from your + * tardiness. NOTE: you cannot rely on the LiveChannelManager as it + * processes events from the standard event queue. This means that Rename + * and Masquerade events MAY (very likely) not have been process when the + * realtime listener recieves an event. + */ + + REALTIME(100), CRITICAL(10), HIGH(8), NORMAL(6), LOW(4); + + // The priority of the listeners. Higher priority listeners receive + // events first. + private int _priority; + + ListenerPriority(int priority) { + this._priority = priority; + } + + public int compare(ListenerPriority rhs) { + return rhs._priority - this._priority; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/NewChannelListener.java b/src/main/java/org/asteriskjava/pbx/NewChannelListener.java new file mode 100644 index 000000000..4f1d8241f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/NewChannelListener.java @@ -0,0 +1,23 @@ +package org.asteriskjava.pbx; + +public interface NewChannelListener { + /** + * Allows a listener to be informed as new channels come up during an + * originate. + *

      + * The OriginateBase class will call this for each channel that comes up (as + * a result of the originate). + *

      + * Intermediate channels (local etc) that the underlying pbx may create on + * the way through are ignored with only the final channels being notified. + *

      + * This listener should be used by anyone that needs to have the channel at + * the earliest possible moment. + *

      + * Listeners should not run long lived process from this call as it will + * stall the dialer. + * + * @param channel + */ + void channelUpdate(Channel channel); +} diff --git a/src/main/java/org/asteriskjava/pbx/NewExtensionListener.java b/src/main/java/org/asteriskjava/pbx/NewExtensionListener.java new file mode 100644 index 000000000..edcf5f524 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/NewExtensionListener.java @@ -0,0 +1,13 @@ +package org.asteriskjava.pbx; + +/** + * Used to notify interested parties when a new extension has been read from the + * pbx configuration. + * + * @author bsutton + */ +public interface NewExtensionListener { + + void newExtension(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/PBX.java b/src/main/java/org/asteriskjava/pbx/PBX.java new file mode 100644 index 000000000..a42d81a9b --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/PBX.java @@ -0,0 +1,278 @@ +package org.asteriskjava.pbx; + +import org.asteriskjava.pbx.Call.OperandChannel; +import org.asteriskjava.pbx.activities.*; + +import java.util.List; + +/** + * Provides an abstracted interface for communicating with a PBX. + * + * @author bsutton + */ +public interface PBX { + + /** + * Call this method when shutting down the PBX interface to allow it to + * cleanup. + */ + void shutdown(); + + /** + * Returns true if the bridge function is supported. + */ + boolean isBridgeSupported(); + + /** + * The BlindTransferActivity is used by the AsteriksPBX to transfer a live + * channel to an endpoint that may need to be dialed. Note: this action is a + * long running action which is dependent on a user action to complete. The + * action will only complete when the call is answered by the tranferTarget. + * It is recommended that you use the blindTransfer method which takes a + * callback as there is no way to cancel this action. Until the + * transferTarget answers the call or the blind transfer times out. + * + * @param channelToTransfer the channel which is to be blind transfered + * @param transferTarget the endPoint to which the channel is to be + * tranferred. + * @param toCallerID - the callerID to display to the transferTarget during + * the transfer. + * @param autoAnswer - if true then the transferTarget is to be sent an auto + * answer header + * @param timeout - timeout (in seconds) for the blind transfer attempt. + * When the timeout is reached the Blind Transfer will be + * cancelled. + * @param ActivityCallback + */ + BlindTransferActivity blindTransfer(final Call call, OperandChannel channelToTransfer, final EndPoint transferTarget, + final CallerID toCallerID, boolean autoAnswer, long timeout, String dialOptions); + + /** + * The BlindTransferActivity is used by the AsteriksPBX to transfer a live + * channel to an endpoint that may need to be dialed. Note: this action is a + * long running action which is defendant on a user action to complete. The + * action will only complete when the call is answered by the tranferTarget. + * You can cancel the action at any time by using the activity object + * returned from the callback start method. + * + * @param channelToTransfer the channel which is to be blind transfered + * @param transferTarget the endPoint to which the channel is to be + * transferred. + * @param toCallerID - the callerID to display to the transferTarget during + * the transfer. + * @param autoAnswer - if true then the transferTarget is to be sent an auto + * answer header + * @param timeout - timeout for the blind transfer attempt. When the timeout + * is reached the Blind Transfer will be cancelled. + */ + void blindTransfer(Call call, OperandChannel channelToTransfer, final EndPoint transferTarget, final CallerID toCallerID, + boolean autoAnswer, long timeout, ActivityCallback callback, String dialOptions); + + /** + * Sends a DTMF tone to given channel. Not returning until the tone has been + * sent. + * + * @param channel + */ + void conference(Channel channelOne, Channel channelTwo, Channel channelThree); + + /** + * Sends a DTMF tone to the given channel. This method returns immediately + * with progress information passed to the given callback. Note: the + * callback method will be called from a different thread. + * + * @param channel + * @param callback + */ + void conference(Channel channelOne, Channel channelTwo, Channel channelThree, ActivityCallback callback); + + /** + * Dials the given phone number using the specified trunk. Not returning + * until the call has been dialled. The dial will return as soon as the + * trunk comes up, it does not wait for remote end to answer. + * + * @return Call - the call resulting from dialing the number. + */ + DialActivity dial(EndPoint from, CallerID fromCallerID, EndPoint to, CallerID toCallerID, String dialOptions); + + /** + * Dials the given phone number using the specified trunk. Not returning + * until the call has been dialled. The dial will return as soon as the + * trunk comes up, it does not wait for remote end to answer. + * + * @return Call the call resulting from dialing the number. + */ + void dial(EndPoint from, CallerID fromCallerID, EndPoint to, CallerID toCallerID, + ActivityCallback callback, String dialOptions); + + /** + * Hangs up the given channel. Not returning until the call is hungup. + * + * @param channel + * @throws PBXException + */ + void hangup(Channel channel) throws PBXException; + + /** + * Hangs up the given channel. This method returns immediately with progress + * information passed to the given callback. Note: the callback method will + * be called from a different thread. + * + * @param channel + * @param callback + */ + void hangup(Channel channel, ActivityCallback callback); + + /** + * Hangup the given call, not returning until the call is hungup. + * + * @param call + */ + void hangup(Call call) throws PBXException; + + /** + * Put the given channel on hold. + * + * @param channel + * @return + */ + HoldActivity hold(Channel channel); + + /** + * Returns true if the mute function is supported. + */ + boolean isMuteSupported(); + + /** + * Parks a call by moving the parkChannel to the parking lot and hanging up + * the hangupChannel. This method will not return until the park has + * completed. The park expects two channels which are two legs legs of the + * same call. The parkChannel will be redirect to the njr-park extension. + * The hangupChannel (the second leg of the call) will be hung up. The + * (obvious?) limitation is that we can't park something like a conference + * call as it has more than two channels. The returned iParkActivty can be + * used to obtain the extension the call was parked on. + * + * @param the call which is to be parked. + * @param parkChannel - the channel which is going to be redirect to the + * njr-park extension. + * @param hangupChannel - the channel which is going to be hungup. + */ + ParkActivity park(Call call, Channel parkChannel); + + /** + * Parks a call by moving the parkChannel to the parking lot and hanging up + * the hangupChannel. This method returns almost immediately call progress + * can be tracked via the callback. The park expects two channels which are + * two legs legs of the same call. The parkChannel will be redirect to the + * njr-park extension. The hangupChannel (the second leg of the call) will + * be hung up. The (obvious?) limitation is that we can't park something + * like a conference call as it has more than two channels. The returned + * iParkActivty can be used to obtain the extension the call was parked on. + * + * @param the call which is to be parked. + * @param parkChannel - the channel which is going to be redirect to the + * njr-park extension. + */ + void park(Call call, Channel parkChannel, ActivityCallback callback); + + /** + * Sends a DTMF tone to given channel. Not returning until the tone has been + * sent. + * + * @param channel + * @throws PBXException + */ + void sendDTMF(Channel channel, DTMFTone tone) throws PBXException; + + /** + * Sends a DTMF tone to the given channel. This method returns immediately + * with progress information passed to the given callback. Note: the + * callback method will be called from a different thread. + * + * @param channel + * @param callback + */ + void sendDTMF(Channel channel, DTMFTone tone, ActivityCallback callback); + + /** + * Splits a call (with two channels) This call returns once the split action + * has completed. + */ + + SplitActivity split(final Call callToSplit, final ActivityCallback listener) throws PBXException; + + RedirectToActivity redirectToActivity(final Channel channel, final ActivityCallback listener); + + void split(final Call callToSplit) throws PBXException; + + /** + * Joins two calls not returning until the join completes. Each call must + * only have one active channel + */ + JoinActivity join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel acceptingOperand, + CallDirection direction); + + void join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel acceptingOperand, + CallDirection direction, ActivityCallback listener); + + /** + * Returns the channel currently attached to the given end point, if one + * exists. If no channel is attached to the given end point then null is + * returned. + * + * @return the channel attached to the end point or null if the endpoint is + * not currently in a call. + */ + Channel getChannelByEndPoint(EndPoint endPoint); + + // /** + // * Converts a String representation of an extension into an extension + // object. + // * + // * The conversion is PBX specific. + // * + // * @param extension + // * @return + // */ + // iExtension getExtension(String extension); + + /** + * Builds an end point from a fully qualified end point name. A fully + * qualified name includes the tech. How the tech is encoded is pbx + * specific. + * + * @param fullyQualifiedEndPointName + * @return + */ + EndPoint buildEndPoint(String fullyQualifiedEndPointName); + + /** + * Builds an iEndPoint from an end point name. If the tech isn't passed in + * the endPointName the tech is set to the defaultTech The encoding for an + * end point name is pbx specific. + * + * @param endPointName + * @return + */ + EndPoint buildEndPoint(TechType defaultTech, String endPointName); + + EndPoint buildEndPoint(TechType tech, Trunk trunk, String endPointName); + + void transferToMusicOnHold(Channel channel) throws PBXException; + + CallerID buildCallerID(String number, String name); + + boolean isChannel(String channel); + + boolean waitForChannelsToQuiescent(List channels, long timeout); + + EndPoint getExtensionAgi(); + + boolean waitForChannelToQuiescent(Channel channel, int timeout); + + Trunk buildTrunk(String string); + + void performPostCreationTasks(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/PBXException.java b/src/main/java/org/asteriskjava/pbx/PBXException.java new file mode 100644 index 000000000..5d7a6136c --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/PBXException.java @@ -0,0 +1,17 @@ +package org.asteriskjava.pbx; + +public class PBXException extends Exception { + private static final long serialVersionUID = 1L; + + public PBXException(String message, final Exception e) { + super(message, e); + } + + public PBXException(final String message) { + super(message); + } + + public PBXException(Throwable e) { + super(e); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/PBXFactory.java b/src/main/java/org/asteriskjava/pbx/PBXFactory.java new file mode 100644 index 000000000..3e99f79fa --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/PBXFactory.java @@ -0,0 +1,32 @@ +package org.asteriskjava.pbx; + +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +import java.util.concurrent.atomic.AtomicReference; + +public class PBXFactory { + + public static PBX getActivePBX() { + return AsteriskPBX.SELF; + + } + + final static AtomicReference profile = new AtomicReference<>(); + + public static void init(AsteriskSettings newProfile) { + profile.set(newProfile); + getActivePBX().performPostCreationTasks(); + + } + + public static AsteriskSettings getActiveProfile() { + AsteriskSettings activeProfile = profile.get(); + if (activeProfile == null) { + throw new RuntimeException( + "you must call setAsteriskSettings() before getActiveProfile() is called the first time"); + } + + return activeProfile; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/PhoneNumber.java b/src/main/java/org/asteriskjava/pbx/PhoneNumber.java new file mode 100644 index 000000000..501e3cc2c --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/PhoneNumber.java @@ -0,0 +1,16 @@ +package org.asteriskjava.pbx; + +/** + * Provides an abstraction of a phone number. This allows different PBX's to + * store the phone numbers in a way that may be specific to the pbx. + *

      + * In general most PBX's there is no need for a special abstraction, however + * using the interface just makes the code clearer that we are passing a phone + * number. + * + * @author bsutton + */ +public interface PhoneNumber { + // TODO + +} diff --git a/src/main/java/org/asteriskjava/pbx/Tech.java b/src/main/java/org/asteriskjava/pbx/Tech.java new file mode 100644 index 000000000..2699cb641 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/Tech.java @@ -0,0 +1,5 @@ +package org.asteriskjava.pbx; + +public interface Tech { + // TODO: do we need this? +} diff --git a/src/main/java/org/asteriskjava/pbx/TechType.java b/src/main/java/org/asteriskjava/pbx/TechType.java new file mode 100644 index 000000000..f3307f150 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/TechType.java @@ -0,0 +1,86 @@ +package org.asteriskjava.pbx; + +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public enum TechType implements Tech { + + // + UNKNOWN, SIP, DAHDI, LOCAL, IAX, IAX2 + // The DIALPLAN tech is used to suppresses output of the tech + // when obtaining the fully qualified name of the endpoint. + // Basically if you want to call into an asterisk dialplan extension + // then the tech needs to be suppressed. + , DIALPLAN + // CONSOLE is sent when a call is made from the asterisk console. + // These type of channels are ignored. + , CONSOLE, + + PJSIP + + // PARKING & SIPPEER are used during call parking + , PARKING, SIPPEER; + + private static final Log logger = LogFactory.getLog(TechType.class); + + /** + * Extracts the technology from a fully qualified endpoint string of the form: + * TECH/NNNN + * + * @param fullyQualifiedEndPoint + * @return + */ + public static TechType getTech(final String fullyQualifiedEndPoint) { + if (!TechType.hasValidTech(fullyQualifiedEndPoint)) { + throw new IllegalArgumentException("The provided end point '" //$NON-NLS-1$ + + fullyQualifiedEndPoint + "' must contain a tech prefix. e.g. SIP/100"); //$NON-NLS-1$ + } + + final String techName = fullyQualifiedEndPoint.substring(0, fullyQualifiedEndPoint.indexOf("/")); //$NON-NLS-1$ + return TechType.valueOf(techName.toUpperCase()); + } + + /** + * returns true if the endPoint name contains a valid tech descriptor. + * + * @param endPointName + * @return + */ + public static boolean hasValidTech(final String endPointName) { + TechType tech = UNKNOWN; + final int index = endPointName.indexOf("/"); //$NON-NLS-1$ + + if (index >= 1) { + final String techName = endPointName.substring(0, index); + try { + tech = TechType.valueOf(techName.toUpperCase()); + } catch (final IllegalArgumentException e) { + TechType.logger.error("Invalid tech for endpoint:" + endPointName); //$NON-NLS-1$ + } + } + + return tech != UNKNOWN; + + } + + /** + * returns true if the endPoint name contains a tech descriptor even if it isn't + * a known descriptor. + * + * @param endPointName + * @return + */ + public static boolean hasTech(final String endPointName) { + boolean hasTech = false; + + final int index = endPointName.indexOf("/"); //$NON-NLS-1$ + + if (index != -1) { + hasTech = true; + } + + return hasTech; + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/Trunk.java b/src/main/java/org/asteriskjava/pbx/Trunk.java new file mode 100644 index 000000000..005165b1f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/Trunk.java @@ -0,0 +1,8 @@ +package org.asteriskjava.pbx; + +/** + * Provides an abstraction of a trunk * @author bsutton + */ +public interface Trunk { + String getTrunkAsString(); +} diff --git a/src/main/java/org/asteriskjava/pbx/activities/BlindTransferActivity.java b/src/main/java/org/asteriskjava/pbx/activities/BlindTransferActivity.java new file mode 100644 index 000000000..802cc3104 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/activities/BlindTransferActivity.java @@ -0,0 +1,56 @@ +package org.asteriskjava.pbx.activities; + +import org.asteriskjava.pbx.*; + +public interface BlindTransferActivity extends Activity { + /** + * A bridged call is a successful transfer all other options are a failed + * transfer. + * + * @author bsutton + */ + enum CompletionCause { + // The call was bridged. + BRIDGED("Connected") + // The call hungup + , HANGUP("Transfer Failed, Caller Hungup or Destination Busy") + // A timeout occur during the transfer + // which essentially means the transferTarget didn't answer the phone + , TIMEOUT("Transfer Failed, Timeout") + // The cancel method was called. + , CANCELLED("Transfer Cancelled") + // Failed + , FAILED("Transfer Failed"); + + String message; + + CompletionCause(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + } + + Channel getChannelToTransfer(); + + CallerID getTransferTargetCallerID(); + + EndPoint getTransferTarget(); + + Channel getTransferTargetChannel(); + + CompletionCause getCompletionCause(); + + void cancel(); + + /** + * The call created as a result of the blind transfer being answered. + * + * @return + * @throws PBXException + */ + Call getNewCall() throws PBXException; + +} diff --git a/src/main/java/org/asteriskjava/pbx/activities/BridgeActivity.java b/src/main/java/org/asteriskjava/pbx/activities/BridgeActivity.java new file mode 100644 index 000000000..62a6aa8d5 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/activities/BridgeActivity.java @@ -0,0 +1,7 @@ +package org.asteriskjava.pbx.activities; + +import org.asteriskjava.pbx.Activity; + +public interface BridgeActivity extends Activity { + // TODO +} diff --git a/src/main/java/org/asteriskjava/pbx/activities/DialActivity.java b/src/main/java/org/asteriskjava/pbx/activities/DialActivity.java new file mode 100644 index 000000000..0565676ca --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/activities/DialActivity.java @@ -0,0 +1,53 @@ +package org.asteriskjava.pbx.activities; + +import org.asteriskjava.pbx.Activity; +import org.asteriskjava.pbx.Call; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.EndPoint; + +public interface DialActivity extends Activity { + /** + * Returns the end point which originated the dial. + */ + EndPoint getOriginatingEndPoint(); + + /** + * Returns the end point which is being dialed. This is available even + * before the dial commences. + */ + EndPoint getAcceptingEndPoint(); + + /** + * Returns the 'originating' channel which is brought up as part of the dial + * activity. The 'originating' channel may return null if the channel is not + * up. + * + * @return the 'originating' channel if it has been brought up otherwise + * null. + */ + Channel getOriginatingChannel(); + + /** + * Returns the 'accepting' channel which is brought up as part of the dial + * activity. The accepting party is the party that answers the call. The + * 'accepting' channel may return null if the channel is not up. + * + * @return the 'accepting' channel if it has been brought up otherwise null + */ + Channel getAcceptingChannel(); + + /** + * Call markCancelled if you want to stop a dial which is in progress from + * completing. This allows a user to cancel a dial. + */ + void markCancelled(); + + /** + * Returns true if markCancelled was called during the dial attempt. + * + * @return + */ + boolean cancelledByOperator(); + + Call getNewCall(); +} diff --git a/src/main/java/org/asteriskjava/pbx/activities/DialToAgiActivity.java b/src/main/java/org/asteriskjava/pbx/activities/DialToAgiActivity.java new file mode 100644 index 000000000..27a17dda6 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/activities/DialToAgiActivity.java @@ -0,0 +1,21 @@ +package org.asteriskjava.pbx.activities; + +import org.asteriskjava.pbx.Activity; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.EndPoint; + +public interface DialToAgiActivity extends Activity { + + void markCancelled(); + + boolean cancelledByOperator(); + + EndPoint getOriginatingEndPoint(); + + Channel getOriginatingChannel(); + + void abort(); + + void dial(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/activities/HoldActivity.java b/src/main/java/org/asteriskjava/pbx/activities/HoldActivity.java new file mode 100644 index 000000000..bc4e62322 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/activities/HoldActivity.java @@ -0,0 +1,9 @@ +package org.asteriskjava.pbx.activities; + +import org.asteriskjava.pbx.Activity; +import org.asteriskjava.pbx.Channel; + +public interface HoldActivity extends Activity { + // Returns the Channel that is on hold + Channel getChannel(); +} diff --git a/src/main/java/org/asteriskjava/pbx/activities/JoinActivity.java b/src/main/java/org/asteriskjava/pbx/activities/JoinActivity.java new file mode 100644 index 000000000..e7430dc7c --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/activities/JoinActivity.java @@ -0,0 +1,9 @@ +package org.asteriskjava.pbx.activities; + +import org.asteriskjava.pbx.Activity; +import org.asteriskjava.pbx.Call; + +public interface JoinActivity extends Activity { + Call getJoinedCall(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/activities/ParkActivity.java b/src/main/java/org/asteriskjava/pbx/activities/ParkActivity.java new file mode 100644 index 000000000..ab15228ad --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/activities/ParkActivity.java @@ -0,0 +1,15 @@ +package org.asteriskjava.pbx.activities; + +import org.asteriskjava.pbx.Activity; +import org.asteriskjava.pbx.EndPoint; + +public interface ParkActivity extends Activity { + + /** + * Returns the endpoint (parking lot) that the call was park on. + * + * @return + */ + EndPoint getParkingLot(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/activities/RedirectToActivity.java b/src/main/java/org/asteriskjava/pbx/activities/RedirectToActivity.java new file mode 100644 index 000000000..1352d8077 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/activities/RedirectToActivity.java @@ -0,0 +1,18 @@ +package org.asteriskjava.pbx.activities; + +import org.asteriskjava.pbx.Activity; +import org.asteriskjava.pbx.Call; + +public interface RedirectToActivity extends Activity { + + /** + * After a call has been split we get a new calls. The call created as a + * result of the lhsOperandChannel being split can be retrieved by calling + * this method. + * + * @return the call which holds the call associated with the + * lhsOperandChannel + */ + Call getCall(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/activities/SplitActivity.java b/src/main/java/org/asteriskjava/pbx/activities/SplitActivity.java new file mode 100644 index 000000000..3af630d70 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/activities/SplitActivity.java @@ -0,0 +1,31 @@ +package org.asteriskjava.pbx.activities; + +import org.asteriskjava.pbx.Activity; +import org.asteriskjava.pbx.Call; + +public interface SplitActivity extends Activity { + + /** + * After a call has been split we get a new calls. The call created as a + * result of the lhsOperandChannel being split can be retrieved by calling + * this method. + * + * @return the call which holds the call associated with the + * lhsOperandChannel + */ + Call getLHSCall(); + + /** + * After a call has been split we get a new calls. The call created as a + * result of the rhsOperandChannel being split can be retrieved by calling + * this method. + *

      + * This method will return now if split was called with only a single + * operand channel. + * + * @return the call which holds the call associated with the + * lhsOperandChannel + */ + Call getRHSCall(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/ActivityAgi.java b/src/main/java/org/asteriskjava/pbx/agi/ActivityAgi.java new file mode 100644 index 000000000..f3a08c1b1 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/ActivityAgi.java @@ -0,0 +1,126 @@ +package org.asteriskjava.pbx.agi; + +import com.google.common.util.concurrent.RateLimiter; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiHangupException; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.agi.config.ServiceAgiScriptImpl; +import org.asteriskjava.pbx.asterisk.wrap.actions.OriginateAction; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +public abstract class ActivityAgi extends ServiceAgiScriptImpl { + + public static final String ARRIVAL_KEY = "ActivityAgiArrivalKey"; + + private final static Log logger = LogFactory.getLog(ActivityAgi.class); + + private static final Map arrivalListeners = new ConcurrentHashMap<>(); + + public static AutoCloseable addArrivalListener(OriginateAction originate, ActivityArrivalListener listener) { + + final String key = UUID.randomUUID().toString(); + arrivalListeners.put(key, listener); + if (arrivalListeners.size() > 100) { + // pick one at random to remove + ActivityArrivalListener leaked = arrivalListeners.remove(arrivalListeners.keySet().iterator().next()); + logger.error("Arrival Listeners are leaking" + leaked.getClass().getCanonicalName()); + } + + Map vars = new HashMap<>(); + vars.put("_" + ARRIVAL_KEY, key); + originate.setVariables(vars); + return new AutoCloseable() { + + @Override + public void close() throws Exception { + arrivalListeners.remove(key); + + } + }; + } + + @Override + public void service() throws AgiException { + Channel channelProxy = null; + String channelName = channel.getName(); + + try { + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + String proxyId = getVariable("proxyId"); + if (proxyId != null && proxyId.length() > 0) { + channelProxy = pbx.getProxyById(proxyId); + } + if (channelProxy == null) { + logger.info("'proxyId' var not set or proxy doesn't exist anymore, trying to match the channel name... " + + channelName); + channelProxy = pbx.internalRegisterChannel(channel.getName(), channel.getUniqueId()); + + } + + logger.info("Channel " + channelName + " arrived in agi"); + + channelProxy.setIsInAgi(true); + channelProxy.addHangupListener(new ChannelHangupListener() { + + @Override + public void channelHangup(Channel channel, Integer cause, String causeText) { + final AgiChannelActivityAction currentActivityAction = channel.getCurrentActivityAction(); + if (currentActivityAction != null) { + currentActivityAction.cancel(); + } + + } + }); + + AgiChannelActivityAction action = channelProxy.getCurrentActivityAction(); + if (action == null) { + action = new AgiChannelActivityHold(); + } + + String arrivalKey = channel.getVariable(ARRIVAL_KEY); + if (arrivalKey != null && arrivalKey.length() > 0) { + ActivityArrivalListener listener = arrivalListeners.get(arrivalKey); + if (listener != null) { + listener.channelArrived(channelProxy); + } + } + + boolean isAlive = true; + RateLimiter slowRateLimiter = RateLimiter.create(2); + while (!action.isDisconnect(this) && isAlive) { + action.execute(this.channel, channelProxy); + + action = channelProxy.getCurrentActivityAction(); + logger.debug("Action for proxy " + channelProxy + " is " + action.getClass().getSimpleName()); + isAlive = checkChannelIsStillUp(); + slowRateLimiter.acquire(); + } + + } catch (AgiHangupException e) { + logger.warn("Channel hungup " + channelName); + } catch (InvalidChannelName | InterruptedException e) { + logger.error(e, e); + } + + logger.debug("Channel leaving agi " + channelName); + + } + + private boolean checkChannelIsStillUp() { + try { + this.answer(); + return true; + } catch (Exception e) { + + } + return false; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/ActivityArrivalListener.java b/src/main/java/org/asteriskjava/pbx/agi/ActivityArrivalListener.java new file mode 100644 index 000000000..877de668b --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/ActivityArrivalListener.java @@ -0,0 +1,9 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.pbx.Channel; + +public interface ActivityArrivalListener { + + void channelArrived(Channel channel); + +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBlindTransfer.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBlindTransfer.java new file mode 100644 index 000000000..c25e89a4b --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBlindTransfer.java @@ -0,0 +1,56 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.Channel; + +import java.util.concurrent.CountDownLatch; + +public class AgiChannelActivityBlindTransfer implements AgiChannelActivityAction { + + CountDownLatch latch = new CountDownLatch(1); + private String target; + private String sipHeader; + int timeout = 30; + private String callerId; + private String dialOptions; + private BlindTransferResultListener listener; + + public AgiChannelActivityBlindTransfer(String fullyQualifiedName, String sipHeader, String callerId, String dialOptions, + BlindTransferResultListener listener) { + this.target = fullyQualifiedName; + this.sipHeader = sipHeader; + this.callerId = callerId; + this.dialOptions = dialOptions; + if (sipHeader == null) { + this.sipHeader = ""; + } + this.listener = listener; + } + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + + channel.setVariable("__SIPADDHEADER", sipHeader); + channel.setCallerId(callerId); + ichannel.setCurrentActivityAction(new AgiChannelActivityHold()); + channel.dial(target, timeout, dialOptions); + String status = channel.getVariable("DIALSTATUS"); + boolean success = "ANSWER".equalsIgnoreCase(status); + if (listener != null) { + listener.result(status, success); + } + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return false; + } + + @Override + public void cancel() { + latch.countDown(); + + } +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBridge.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBridge.java new file mode 100644 index 000000000..458c8920a --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBridge.java @@ -0,0 +1,58 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiHangupException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.concurrent.CountDownLatch; + +public class AgiChannelActivityBridge implements AgiChannelActivityAction { + + private Channel target; + private final Log logger = LogFactory.getLog(this.getClass()); + + CountDownLatch latch = new CountDownLatch(1); + + public AgiChannelActivityBridge(Channel target) { + this.target = target; + } + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + try { + // TODO: this should probably pass the 'F' option to allow the + // bridgee + // to go back to dialplan. + // I'm not currently prepared to do it as it is called from a number + // of places, and + // I can't currently see it causing problems. + channel.bridge(target.getChannelName(), ""); + channel.hangup(); + } catch (AgiHangupException e) { + logger.warn(e); + } finally { + latch.countDown(); + } + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return false; + } + + @Override + public void cancel() { + latch.countDown(); + + } + // Logger logger = LogManager.getLogger(); + + public void sleepWhileBridged() throws InterruptedException { + latch.await(); + + } +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityDial.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityDial.java new file mode 100644 index 000000000..9b3ae4f07 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityDial.java @@ -0,0 +1,54 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.Channel; + +import java.util.concurrent.CountDownLatch; + +public class AgiChannelActivityDial implements AgiChannelActivityAction { + + CountDownLatch latch = new CountDownLatch(1); + private String target; + private String sipHeader; + private String dialOptions; + + public AgiChannelActivityDial(String target, String dialOptions) { + this.target = target; + this.dialOptions = dialOptions; + } + + public AgiChannelActivityDial(String fullyQualifiedName, String sipHeader, String dialOptions) { + target = fullyQualifiedName; + this.sipHeader = sipHeader; + this.dialOptions = dialOptions; + } + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + if (sipHeader != null) { + channel.setVariable("__SIPADDHEADER", sipHeader); + } + // setting the activity to hold, means that when the call falls out of + // the dial it'll go to hold. + + // also if some other code sets and activity and then redirects, we + // won't over write it on the way out (if we did it after the dial + // command) + ichannel.setCurrentActivityAction(new AgiChannelActivityHold()); + channel.dial(target, 30, dialOptions); + + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return false; + } + + @Override + public void cancel() { + latch.countDown(); + + } +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHangup.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHangup.java new file mode 100644 index 000000000..6963e04cd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHangup.java @@ -0,0 +1,40 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiHangupException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.concurrent.CountDownLatch; + +public class AgiChannelActivityHangup implements AgiChannelActivityAction { + private final Log logger = LogFactory.getLog(this.getClass()); + + CountDownLatch latch = new CountDownLatch(1); + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + try { + + channel.hangup(); + logger.info("Hungup"); + } catch (AgiHangupException e) { + // don't care + } + + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return false; + } + + @Override + public void cancel() { + latch.countDown(); + + } +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHold.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHold.java new file mode 100644 index 000000000..8a80ba9eb --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHold.java @@ -0,0 +1,66 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiHangupException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class AgiChannelActivityHold implements AgiChannelActivityAction { + private final Log logger = LogFactory.getLog(this.getClass()); + + CountDownLatch latch = new CountDownLatch(1); + volatile boolean callReachedAgi = false; + long timer = System.currentTimeMillis(); + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + try { + callReachedAgi = true; + channel.answer(); + channel.playMusicOnHold(); + long secondsOnHold = Math.abs(System.currentTimeMillis() - timer) / 1000; + if (secondsOnHold > 600) { + logger.info(ichannel + " is still on hold after " + secondsOnHold + " seconds"); + } + if (latch.await(10, TimeUnit.SECONDS)) { + try { + channel.stopMusicOnHold(); + } catch (AgiHangupException e) { + logger.info("Channel hungup " + channel.getName()); + } catch (Exception e) { + logger.warn(e); + } + } else { + if (channel.getName().startsWith("Local") && secondsOnHold > 3600) { + // cleanup Local channels older than 1 hour + logger.error("Hanging up local channel that has been on hold for 1 hour " + channel.getName()); + channel.hangup(); + } + } + } catch (AgiHangupException e) { + logger.warn(e); + } + + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return false; + } + + @Override + public void cancel() { + latch.countDown(); + + } + + public boolean hasCallReachedAgi() { + return callReachedAgi; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHoldForBridge.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHoldForBridge.java new file mode 100644 index 000000000..5760a21cf --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHoldForBridge.java @@ -0,0 +1,54 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiHangupException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class AgiChannelActivityHoldForBridge implements AgiChannelActivityAction { + private final Log logger = LogFactory.getLog(this.getClass()); + private AgiChannelActivityBridge bridgeActivity; + private volatile boolean hangup = true; + + public AgiChannelActivityHoldForBridge(AgiChannelActivityBridge bridgeActivity) { + this.bridgeActivity = bridgeActivity; + } + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + try { + channel.playMusicOnHold(); + bridgeActivity.sleepWhileBridged(); + + if (hangup) { + channel.hangup(); + } + } catch (AgiHangupException e) { + logger.warn(e.getMessage() + " " + channel.getName()); + } + + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return false; + } + + @Override + public void cancel() { + // this seems a bit strange, but the logic here is that if you cancel + // this action you want to invoke a new action. We can't end the bridge + // from here, but not hanging up when it does collapse is + // important. + hangup = false; + + } + + public void hangupAfterBridge(boolean b) { + hangup = b; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityMeetme.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityMeetme.java new file mode 100644 index 000000000..3c5acad65 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityMeetme.java @@ -0,0 +1,76 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.manager.TimeoutException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.AsteriskSettings; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.asterisk.wrap.actions.RedirectAction; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.io.IOException; +import java.util.concurrent.CountDownLatch; + +public class AgiChannelActivityMeetme implements AgiChannelActivityAction { + private final Log logger = LogFactory.getLog(this.getClass()); + + CountDownLatch latch = new CountDownLatch(1); + private String room; + private volatile boolean hangup = true; + + private Channel ichannel; + + private String bridgeProfile; + + private String userProfile; + + public AgiChannelActivityMeetme(String room, String bridgeProfile, String userProfile) { + this.room = room; + this.bridgeProfile = bridgeProfile; + this.userProfile = userProfile; + } + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + if (ichannel == null) { + throw new NullPointerException("ichannel cannot be null"); + } + this.ichannel = ichannel; + channel.confbridge(room, bridgeProfile + "," + userProfile); + + if (hangup) { + try { + channel.hangup(); + } catch (Exception e) { + logger.warn(e); + } + } + logger.info(ichannel + " left the meetme"); + + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return false; + } + + @Override + public void cancel() { + hangup = false; + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + final RedirectAction redirect = new RedirectAction(ichannel, profile.getManagementContext(), pbx.getExtensionAgi(), + 1); + try { + pbx.sendAction(redirect, 1000); + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { + logger.error(e, e); + } + + } +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityPlayMessage.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityPlayMessage.java new file mode 100644 index 000000000..f45646b22 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityPlayMessage.java @@ -0,0 +1,54 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.Channel; + +import java.util.concurrent.TimeUnit; + +public class AgiChannelActivityPlayMessage implements AgiChannelActivityAction { + + private String file; + private boolean hangup = false; + + public AgiChannelActivityPlayMessage(String file) { + this.file = file; + } + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + if (ichannel == null) { + throw new NullPointerException("ichannel cannot be null"); + } + String tmp = file; + + channel.exec("Playtones", "beep"); + TimeUnit.MILLISECONDS.sleep(100); + // file, escape, offset, forward, rewind, pause + + // # to exit, 6 forward, 4 back, 5 pause + try { + channel.controlStreamFile(tmp, "#", 15000, "6", "4", "5"); + } catch (Exception e) { + TimeUnit.MILLISECONDS.sleep(100); + throw e; + } + + channel.exec("Playtones", "beep"); + TimeUnit.MILLISECONDS.sleep(100); + channel.hangup(); + hangup = true; + + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return hangup; + } + + @Override + public void cancel() { + hangup = true; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityQueue.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityQueue.java new file mode 100644 index 000000000..d6d50d8dd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityQueue.java @@ -0,0 +1,75 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiHangupException; +import org.asteriskjava.manager.TimeoutException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.AsteriskSettings; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.asterisk.wrap.actions.RedirectAction; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.io.IOException; +import java.util.concurrent.CountDownLatch; + +public class AgiChannelActivityQueue implements AgiChannelActivityAction { + + private final Log logger = LogFactory.getLog(this.getClass()); + + CountDownLatch latch = new CountDownLatch(1); + + final private String queue; + private volatile boolean hangup = true; + // volatile private iChannel ichannel; + + private Channel ichannel; + + public AgiChannelActivityQueue(String queue) { + this.queue = queue; + } + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + this.ichannel = ichannel; + + channel.queue(queue); + if (hangup) { + try { + channel.hangup(); + } catch (AgiHangupException e) { + logger.warn("Channel " + channel.getName() + " hungup"); + } catch (Exception e) { + logger.warn(e); + } + } + logger.info(ichannel + " left the queue"); + + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return false; + } + + @Override + public void cancel() { + + hangup = false; + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + final RedirectAction redirect = new RedirectAction(ichannel, profile.getManagementContext(), pbx.getExtensionAgi(), + 1); + try { + + pbx.sendAction(redirect, 1000); + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { + logger.error(e, e); + } + + } +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityTransientHoldSilence.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityTransientHoldSilence.java new file mode 100644 index 000000000..77e235a20 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityTransientHoldSilence.java @@ -0,0 +1,62 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiHangupException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Waits in silence for 10 seconds, then hangs up. This is useful where channels + * are waiting for some external action to redirect/bridge them. + * + * @author rsutton + */ +public class AgiChannelActivityTransientHoldSilence implements AgiChannelActivityAction { + private final Log logger = LogFactory.getLog(this.getClass()); + + CountDownLatch latch = new CountDownLatch(1); + volatile boolean callReachedAgi = false; + boolean firstPass = true; + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + try { + callReachedAgi = true; + channel.answer(); + if (!firstPass) { + logger.error(ichannel + " is still on hold after first pass, Hanging up"); + channel.hangup(); + } else { + if (!latch.await(10, TimeUnit.SECONDS)) { + logger.warn("Exiting with timeout"); + } + } + } catch (AgiHangupException e) { + logger.warn(e); + } finally { + firstPass = false; + } + + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + return false; + } + + @Override + public void cancel() { + latch.countDown(); + + } + + public boolean hasCallReachedAgi() { + return callReachedAgi; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityVoicemail.java b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityVoicemail.java new file mode 100644 index 000000000..c47945720 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityVoicemail.java @@ -0,0 +1,32 @@ +package org.asteriskjava.pbx.agi; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.pbx.AgiChannelActivityAction; +import org.asteriskjava.pbx.Channel; + +public class AgiChannelActivityVoicemail implements AgiChannelActivityAction { + + public AgiChannelActivityVoicemail(String mailbox) { + // TODO Auto-generated constructor stub + } + + @Override + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + // TODO Auto-generated method stub + + } + + @Override + public boolean isDisconnect(ActivityAgi activityAgi) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void cancel() { + // TODO Auto-generated method stub + + } + // Logger logger = LogManager.getLogger(); +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/BlindTransferResultListener.java b/src/main/java/org/asteriskjava/pbx/agi/BlindTransferResultListener.java new file mode 100644 index 000000000..1f88d5a3e --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/BlindTransferResultListener.java @@ -0,0 +1,7 @@ +package org.asteriskjava.pbx.agi; + +public interface BlindTransferResultListener { + + void result(String status, boolean success); + +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/config/AgiConfiguration.java b/src/main/java/org/asteriskjava/pbx/agi/config/AgiConfiguration.java new file mode 100644 index 000000000..6c107d824 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/config/AgiConfiguration.java @@ -0,0 +1,9 @@ +package org.asteriskjava.pbx.agi.config; + +import java.util.List; + +public interface AgiConfiguration { + + List> getAgiHandlers(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/config/AgiMappingStragegy.java b/src/main/java/org/asteriskjava/pbx/agi/config/AgiMappingStragegy.java new file mode 100644 index 000000000..ccd8cf424 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/config/AgiMappingStragegy.java @@ -0,0 +1,123 @@ +/* + * Copyright 2004-2006 by S. Brett Sutton. Commercial support is provided by + * Asterisk I.T. http://www.asteriskit.com.au + * + * The contents of this file are subject to a modified GPL Version 2 License or + * later version at your discretion. + * + * The sole modification to the GPL is a limitation on use. + * + * The limitation is that AsterFax (and its source components) may only be used + * on a single Channel as defined in AsterFax.xml. The implications of the + * limitation is that the free verions of AsterFax may only be used to send or + * receive a single fax at a time. + * + * Any copied or modified versions of the AsterFax source must retain this + * limitation. + * + * If you wish to use multiple channels then you can purchase a commercial + * license by emailing sales@asteriskit.com.au + * + * Contributor(s): all the names of the contributors are added in the source + * code where applicable. + */ +package org.asteriskjava.pbx.agi.config; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiRequest; +import org.asteriskjava.fastagi.AgiScript; +import org.asteriskjava.fastagi.MappingStrategy; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class AgiMappingStragegy implements MappingStrategy { + + static private final Log logger = LogFactory.getLog(AgiMappingStragegy.class); + + private Map> handlers = new HashMap<>(); + + @Override + public AgiScript determineScript(AgiRequest request, AgiChannel channel) { + AgiScript ret = null; + + String script = request.getScript(); + if (script.indexOf(".") != -1) { + script = script.substring(0, script.indexOf(".")); + } + + if (script.startsWith("/")) { + // this is specifically for the "FastAgiSimulator" + script = script.substring(1); + } + Iterator itr = request.getParameterMap().keySet().iterator(); + logger.debug("*********************************"); + logger.debug("script " + script); + while (itr.hasNext()) { + String key = itr.next(); + String val = request.getParameter(key); + if (key.compareToIgnoreCase("cardNumber") == 0) + val = "suppressed"; + logger.debug(key + ": " + val); + } + logger.debug("******"); + + if (handlers.containsKey(script)) { + try { + ret = handlers.get(script).getDeclaredConstructor().newInstance(); + } catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException + | InstantiationException | IllegalAccessException e) { + logger.error(e, e); + } + + } + + return ret; + } + + /** + * this will be a pluggable extension system for the agi core, it's still a + * work in progress and is not useable + * + * @param handler + * @throws DuplicateScriptException + * @throws IllegalAccessException + * @throws InstantiationException + * @throws SecurityException + * @throws NoSuchMethodException + * @throws InvocationTargetException + * @throws IllegalArgumentException + */ + @SuppressWarnings("unchecked") + public void addServiceAgiScript(Class handler) + throws DuplicateScriptException, InstantiationException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException, NoSuchMethodException, SecurityException { + + logger.info("loading agi handler {}" + handler.getCanonicalName()); + ServiceAgiScript tmpHandler = handler.getDeclaredConstructor().newInstance(); + if (handlers.containsKey(tmpHandler.getScriptName())) { + throw new DuplicateScriptException("Script " + tmpHandler.getScriptName() + " already exists"); + } + String[] parameters = tmpHandler.getParameters(); + String sample = "Agi(agi://localhost/" + tmpHandler.getScriptName() + ".agi"; + logger.info("********************************************"); + logger.info("registered new agi script: " + tmpHandler.getScriptName()); + for (int i = 0; i < parameters.length; i++) { + logger.info("parameter: " + parameters[i]); + if (i == 0) + sample += "?" + parameters[i] + "=testdata"; + else + sample += "&" + parameters[i] + "=testdata"; + } + + logger.info("sample usage..."); + logger.info(sample + ")"); + Class handler2 = (Class) handler; + handlers.put(tmpHandler.getScriptName(), handler2); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/config/ConfiguableAGIServer.java b/src/main/java/org/asteriskjava/pbx/agi/config/ConfiguableAGIServer.java new file mode 100644 index 000000000..aef536075 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/config/ConfiguableAGIServer.java @@ -0,0 +1,54 @@ +/* + * Copyright 2004-2006 by S. Brett Sutton. + * Commercial support is provided by Asterisk I.T. http://www.asteriskit.com.au + * + * The contents of this file are subject to a modified GPL Version 2 License + * or later version at your discretion. + * + * The sole modification to the GPL is a limitation on use. + * + * The limitation is that AsterFax (and its source components) may only be used on a single Channel + * as defined in AsterFax.xml. + * The implications of the limitation is that the free verions of AsterFax may only be used to send + * or receive a single fax at a time. + * + * Any copied or modified versions of the AsterFax source must retain this limitation. + * + * If you wish to use multiple channels then you can purchase a commercial license + * by emailing sales@asteriskit.com.au + * + * Contributor(s): all the names of the contributors are added in the source code + * where applicable. + */ +package org.asteriskjava.pbx.agi.config; + +import org.asteriskjava.fastagi.DefaultAgiServer; + +import javax.naming.ConfigurationException; +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +public class ConfiguableAGIServer extends DefaultAgiServer implements Runnable { + + public ConfiguableAGIServer(AgiConfiguration configuration) + throws DuplicateScriptException, InstantiationException, IllegalAccessException, ConfigurationException, + IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + AgiMappingStragegy mappingStrategy = new AgiMappingStragegy(); + setMaximumPoolSize(500); + loadHandlers(mappingStrategy, configuration); + + this.setMappingStrategy(mappingStrategy); + new Thread(this, "AGIServer:" + this.getPort()).start(); + + } + + private void loadHandlers(AgiMappingStragegy mappingStrategy, AgiConfiguration configuration) + throws DuplicateScriptException, InstantiationException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException, NoSuchMethodException, SecurityException { + List> handlers = configuration.getAgiHandlers(); + for (Class clazz : handlers) { + mappingStrategy.addServiceAgiScript(clazz); + } + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/config/DuplicateScriptException.java b/src/main/java/org/asteriskjava/pbx/agi/config/DuplicateScriptException.java new file mode 100644 index 000000000..ed091c99f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/config/DuplicateScriptException.java @@ -0,0 +1,12 @@ +package org.asteriskjava.pbx.agi.config; + +public class DuplicateScriptException extends Exception { + public DuplicateScriptException(String string) { + super(string); + } + + /** + * + */ + private static final long serialVersionUID = -3931649299622511878L; +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScript.java b/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScript.java new file mode 100644 index 000000000..ffb52f82b --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScript.java @@ -0,0 +1,11 @@ +package org.asteriskjava.pbx.agi.config; + +import org.asteriskjava.fastagi.AgiScript; + +public interface ServiceAgiScript extends AgiScript { + + String getScriptName(); + + String[] getParameters(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScriptImpl.java b/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScriptImpl.java new file mode 100644 index 000000000..16f865b6e --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScriptImpl.java @@ -0,0 +1,55 @@ +package org.asteriskjava.pbx.agi.config; + +import org.asteriskjava.fastagi.AgiChannel; +import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.fastagi.AgiRequest; +import org.asteriskjava.fastagi.BaseAgiScript; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +/** + * Allows for auto configuration of the AGI script.
      + *
      + * Provides a getParameter(..) method which verifies the existence of the + * parameter.
      + *
      + * Requires an implementing agi to provide it's name and parameter list via + * getScriptName() and getParameters. + * + * @author rsutton + */ +abstract public class ServiceAgiScriptImpl extends BaseAgiScript implements ServiceAgiScript { + static transient Log logger = LogFactory.getLog(ServiceAgiScriptImpl.class); + protected AgiRequest request; + protected AgiChannel channel; + + public synchronized void service(AgiRequest request, AgiChannel channel) throws AgiException { + this.request = request; + this.channel = channel; + service(); + } + + /** + * field variables request and channel will be set prior to calling + * service() AgiRequest request AgiChannel channel + * + * @throws AgiException + */ + + public abstract void service() throws AgiException; + + protected String required(String name, String parameter) throws AgiException { + if (parameter == null || parameter.length() == 0) + throw new AgiException("Required parameter " + name + " missing."); + return parameter; + } + + protected String getParameter(String name) throws AgiException { + return required(name, request.getParameter(name)); + } + + public abstract String getScriptName(); + + public abstract String[] getParameters(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/AbstractManagerAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/AbstractManagerAction.java new file mode 100644 index 000000000..30f7a8f62 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/AbstractManagerAction.java @@ -0,0 +1,21 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * Automatically generates a globally unique action id (based on the systems mac + * address + * + * @author bsutton + */ +abstract public class AbstractManagerAction implements ManagerAction { + + private final static AtomicLong _nextActionId = new AtomicLong(); + + private final String _actionId = "" + _nextActionId.incrementAndGet(); + + public String getActionId() { + return this._actionId; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/BridgeAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/BridgeAction.java new file mode 100644 index 000000000..b0bd14a69 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/BridgeAction.java @@ -0,0 +1,27 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.pbx.Channel; + +public class BridgeAction extends AbstractManagerAction { + + private final Channel _lhs; + private final Channel _rhs; + + public BridgeAction(final Channel lhs, final Channel rhs) { + this._lhs = lhs; + this._rhs = rhs; + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.BridgeAction action = new org.asteriskjava.manager.action.BridgeAction(); + action.setActionId(this.getActionId()); + action.setChannel1(this._lhs.getChannelName()); + action.setChannel2(this._rhs.getChannelName()); + return action; + } + + public String toString() { + return "BridgeAction: lhs=" + this._lhs + " rhs=" + this._rhs; //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/CommandAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/CommandAction.java new file mode 100644 index 000000000..128fa5b44 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/CommandAction.java @@ -0,0 +1,27 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +public class CommandAction extends AbstractManagerAction { + + private String _command; + + public CommandAction(final String command) { + this._command = command; + } + + public CommandAction() { + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.CommandAction action = new org.asteriskjava.manager.action.CommandAction(); + action.setCommand(this._command); + action.setActionId(this.getActionId()); + + return action; + } + + public String toString() { + return "CommandAction: command=" + this._command; //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ConfbridgeKickAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ConfbridgeKickAction.java new file mode 100644 index 000000000..21d813898 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ConfbridgeKickAction.java @@ -0,0 +1,30 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +public class ConfbridgeKickAction extends AbstractManagerAction { + + private final String channel; + private String room; + + public ConfbridgeKickAction(final String room, String channel) { + this.channel = channel; + this.room = room; + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.ConfbridgeKickAction action = new org.asteriskjava.manager.action.ConfbridgeKickAction(); + action.setActionId(this.getActionId()); + action.setChannel(channel); + action.setConference(room); + + return action; + } + + public String getChannel() { + return channel; + } + + public String getRoom() { + return room; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ConfbridgeListAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ConfbridgeListAction.java new file mode 100644 index 000000000..7be64573b --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ConfbridgeListAction.java @@ -0,0 +1,19 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.manager.action.ManagerAction; + +public class ConfbridgeListAction extends AbstractManagerAction implements EventGeneratingAction { + + @Override + public ManagerAction getAJAction() { + return new org.asteriskjava.manager.action.ConfbridgeListAction(); + } + // Logger logger = LogManager.getLogger(); + + @Override + public org.asteriskjava.manager.action.EventGeneratingAction getAJEventGeneratingAction() { + org.asteriskjava.manager.action.ConfbridgeListAction action = new org.asteriskjava.manager.action.ConfbridgeListAction(); + action.setActionId(this.getActionId()); + return action; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/DbGetAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/DbGetAction.java new file mode 100644 index 000000000..549cc25d6 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/DbGetAction.java @@ -0,0 +1,29 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.manager.action.ManagerAction; + +public class DbGetAction extends AbstractManagerAction { + + private final String _key; + private final String _family; + + public DbGetAction(final String family, final String key) { + this._family = family; + this._key = key; + } + + @Override + public ManagerAction getAJAction() { + final org.asteriskjava.manager.action.DbGetAction action = new org.asteriskjava.manager.action.DbGetAction(); + action.setActionId(this.getActionId()); + action.setKey(this._key); + action.setFamily(this._family); + + return action; + } + + public String toString() { + return "DbGetAction: key=" + this._key + " family=" + this._family; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/EventGeneratingAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/EventGeneratingAction.java new file mode 100644 index 000000000..781c11b44 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/EventGeneratingAction.java @@ -0,0 +1,7 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +public interface EventGeneratingAction { + + org.asteriskjava.manager.action.EventGeneratingAction getAJEventGeneratingAction(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/GetVarAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/GetVarAction.java new file mode 100644 index 000000000..1680df51f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/GetVarAction.java @@ -0,0 +1,29 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.pbx.Channel; + +public class GetVarAction extends AbstractManagerAction { + + private final Channel _channel; + private String _variableName; + + public GetVarAction(final Channel channel, String variableName) { + this._channel = channel; + this._variableName = variableName; + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.GetVarAction action = new org.asteriskjava.manager.action.GetVarAction(); + action.setActionId(this.getActionId()); + action.setChannel(this._channel.getChannelName()); + action.setVariable(this._variableName); + + return action; + } + + public String toString() { + return "GetVarAction: channel=" + this._channel + " variableName=" + this._variableName; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/HangupAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/HangupAction.java new file mode 100644 index 000000000..bbbcfdc73 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/HangupAction.java @@ -0,0 +1,32 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.pbx.Channel; + +public class HangupAction extends AbstractManagerAction { + + private final Channel _channel; + private Integer _cause; + + public HangupAction(final Channel channel) { + this._channel = channel; + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.HangupAction action = new org.asteriskjava.manager.action.HangupAction(); + action.setActionId(this.getActionId()); + action.setCause(this._cause); + action.setChannel(this._channel.getChannelName()); + + return action; + } + + public Channel getChannel() { + return this._channel; + } + + public String toString() { + return "HangupAction: channel=" + this._channel + " cause=" + this._cause; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ListCommandsAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ListCommandsAction.java new file mode 100644 index 000000000..df9d7f195 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ListCommandsAction.java @@ -0,0 +1,17 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +public class ListCommandsAction extends AbstractManagerAction { + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.ListCommandsAction action = new org.asteriskjava.manager.action.ListCommandsAction(); + action.setActionId(this.getActionId()); + + return action; + } + + public String toString() { + return "ListCommandsAction"; //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ManagerAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ManagerAction.java new file mode 100644 index 000000000..66dd34fbf --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ManagerAction.java @@ -0,0 +1,8 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +public interface ManagerAction { + + // Converts an iManagerAction into an asterisk-java ManagerAction. + org.asteriskjava.manager.action.ManagerAction getAJAction(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/MonitorAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/MonitorAction.java new file mode 100644 index 000000000..521a68804 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/MonitorAction.java @@ -0,0 +1,32 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.pbx.Channel; + +public class MonitorAction extends AbstractManagerAction { + + private final Channel _channel; + private final String _file; + private final String _format; + private final boolean _mix; + + public MonitorAction(final Channel channel, final String file, final String format, final boolean mix) { + this._channel = channel; + this._file = file; + this._format = format; + this._mix = mix; + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.MonitorAction action = new org.asteriskjava.manager.action.MonitorAction( + this._channel.getChannelName(), this._file, this._format, this._mix); + action.setActionId(this.getActionId()); + + return action; + } + + public String toString() { + return "MonitorAction: channel=" + this._channel + " file=" + this._file; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/OriginateAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/OriginateAction.java new file mode 100644 index 000000000..75184235c --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/OriginateAction.java @@ -0,0 +1,143 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.pbx.CallerID; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.EndPoint; +import org.asteriskjava.pbx.internal.asterisk.CallerIDImpl; + +import java.util.Map; + +public class OriginateAction extends AbstractManagerAction { + + /** + * Asterisk uses the term channel but it actually appears to be an endpoint + * or a channel. Hence we support both. Either of the following may be set + * but NOT BOTH. + */ + private EndPoint _endPoint; + private Channel _channel; + + private String _option; + + private String _context; + + private EndPoint _extension; + + private int _priority; + + private int _callingPres; + + private CallerID _callerID; + + private Map _variables; + + private Boolean _async; + + private long _timeout; + + private String channelId; + private String otherChannelId; + + public OriginateAction() { + } + + public String toString() { + return "OriginateAction: endPoint/Channel=" + (this._endPoint == null ? this._channel : this._endPoint) + " context=" //$NON-NLS-1$ //$NON-NLS-2$ + + this._context + " extension=" + this._extension + " callerId=" + this._callerID; //$NON-NLS-1$ //$NON-NLS-2$ + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.OriginateAction action = new org.asteriskjava.manager.action.OriginateAction(); + action.setActionId(getActionId()); + + // Was the channel or an end point passed. + String channel = (this._channel != null ? this._channel.getChannelName() : this._endPoint.getFullyQualifiedName()); + if (this._option != null) { + channel += this._option; + } + action.setChannel((channel)); + action.setContext(this._context); + action.setExten(this._extension.getFullyQualifiedName()); + action.setPriority(this._priority); + action.setCallingPres(this._callingPres); + action.setCallerId(((CallerIDImpl) this._callerID).formatted()); + action.setVariables(this._variables); + action.setAsync(this._async); + action.setTimeout(this._timeout); + + action.setChannelId(channelId); + action.setOtherChannelId(otherChannelId); + + return action; + } + + public void setEndPoint(final EndPoint endPoint) { + this._endPoint = endPoint; + this._channel = null; + } + + public void setChannel(Channel channel) { + this._channel = channel; + this._endPoint = null; + + } + + public void setOption(final String option) { + this._option = option; + + } + + public void setContext(final String context) { + this._context = context; + + } + + public void setExten(final EndPoint extension) { + this._extension = extension; + + } + + public void setPriority(final int priority) { + this._priority = priority; + + } + + public void setCallingPres(final int callingPres) { + this._callingPres = callingPres; + + } + + public void setCallerId(final CallerID callerID) { + this._callerID = callerID; + + } + + public void setVariables(final Map variables) { + if (_variables == null) { + this._variables = variables; + } else { + this._variables.putAll(variables); + } + + } + + public void setAsync(final boolean async) { + this._async = async; + + } + + public void setTimeout(final long timeout) { + this._timeout = timeout; + + } + + public void setChannelId(String channelId) { + this.channelId = channelId; + } + + public void setOtherChannelId(String otherChannelId) { + this.otherChannelId = otherChannelId; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PingAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PingAction.java new file mode 100644 index 000000000..9c2e46b02 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PingAction.java @@ -0,0 +1,16 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +public class PingAction extends AbstractManagerAction { + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.PingAction action = new org.asteriskjava.manager.action.PingAction(); + action.setActionId(this.getActionId()); + return action; + } + + public String toString() { + return "PingAction"; //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PlayDtmfAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PlayDtmfAction.java new file mode 100644 index 000000000..7c0082fc5 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PlayDtmfAction.java @@ -0,0 +1,31 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.manager.action.ManagerAction; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.DTMFTone; + +public class PlayDtmfAction extends AbstractManagerAction { + + private final Channel _channel; + private final DTMFTone _tone; + + public PlayDtmfAction(final Channel channel, final DTMFTone tone) { + this._channel = channel; + this._tone = tone; + } + + @Override + public ManagerAction getAJAction() { + final org.asteriskjava.manager.action.PlayDtmfAction action = new org.asteriskjava.manager.action.PlayDtmfAction(); + action.setActionId(this.getActionId()); + action.setChannel(this._channel.getChannelName()); + action.setDigit(this._tone.toString()); + + return action; + } + + public String toString() { + return "PlayDtmfAction: channel=" + this._channel + " tone=" + this._tone; //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/RedirectAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/RedirectAction.java new file mode 100644 index 000000000..d2dd82d2f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/RedirectAction.java @@ -0,0 +1,76 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.EndPoint; + +public class RedirectAction extends AbstractManagerAction { + + private final Channel _channel; + private final String _context; + private final EndPoint _exten; + private final Integer _priority; + private Channel _extraChannel; + private String _extraContext; + private EndPoint _extraExten; + private Integer _extraPriority; + + public RedirectAction(final Channel channel, final String context, final EndPoint extension, final int priority) { + if (channel == null) { + throw new NullPointerException("channel cannot be null"); + } + if (context == null) { + throw new NullPointerException("context cannot be null"); + } + if (extension == null) { + throw new NullPointerException("extension cannot be null"); + } + + this._channel = channel; + this._context = context; + this._exten = extension; + this._priority = priority; + } + + @Override + public String toString() { + return "RedirectAction: chanel=" + this._channel + " context=" + this._context //$NON-NLS-1$ //$NON-NLS-2$ + + " exten=" + this._exten + " priority=" + this._priority //$NON-NLS-1$ //$NON-NLS-2$ + + " extraContext=" + this._extraContext //$NON-NLS-1$ + + " extraChannel=" + this._extraChannel //$NON-NLS-1$ + + " extraExten=" + this._extraExten; //$NON-NLS-1$ + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.RedirectAction action = new org.asteriskjava.manager.action.RedirectAction(); + action.setActionId(this.getActionId()); + action.setChannel(this._channel.getChannelName().toLowerCase()); + action.setContext(this._context); + action.setExten(this._exten.getFullyQualifiedName()); + action.setPriority(this._priority); + if (this._extraChannel != null) + action.setExtraChannel(this._extraChannel.getChannelName().toLowerCase()); + action.setExtraContext(this._extraContext); + if (this._extraExten != null) + action.setExtraExten(this._extraExten.getFullyQualifiedName()); + action.setExtraPriority(this._extraPriority); + + return action; + } + + public void setExtraChannel(final Channel extraChannel) { + this._extraChannel = extraChannel; + } + + public void setExtraContext(final String extraContext) { + this._extraContext = extraContext; + } + + public void setExtraExten(final EndPoint extraExten) { + this._extraExten = extraExten; + } + + public void setExtraPriority(final int priority) { + this._extraPriority = priority; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SetVarAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SetVarAction.java new file mode 100644 index 000000000..9657f32aa --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SetVarAction.java @@ -0,0 +1,37 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.pbx.Channel; + +public class SetVarAction extends AbstractManagerAction { + + private final Channel _channel; + private String _variableName; + private final String _value; + + public SetVarAction(final Channel channel, final String variableName, final String value) { + this._channel = channel; + this._variableName = variableName; + this._value = value; + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.SetVarAction action = new org.asteriskjava.manager.action.SetVarAction(); + action.setActionId(this.getActionId()); + action.setChannel(this._channel.getChannelName()); + action.setVariable(this._variableName); + action.setValue(this._value); + + return action; + } + + public void setVariable(final String variableName) { + this._variableName = variableName; + + } + + public String toString() { + return "SetVarAction: channel=" + this._channel + " variableName=" + this._variableName + " value=" + this._value; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipPeersAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipPeersAction.java new file mode 100644 index 000000000..4ff04c8f0 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipPeersAction.java @@ -0,0 +1,24 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +public class SipPeersAction extends AbstractManagerAction implements EventGeneratingAction { + + public SipPeersAction() { + } + + @Override + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + return new org.asteriskjava.manager.action.SipPeersAction(); + } + + @Override + public org.asteriskjava.manager.action.EventGeneratingAction getAJEventGeneratingAction() { + org.asteriskjava.manager.action.SipPeersAction action = new org.asteriskjava.manager.action.SipPeersAction(); + action.setActionId(this.getActionId()); + return action; + } + + public String toString() { + return "SipPeersAction"; //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipShowPeerAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipShowPeerAction.java new file mode 100644 index 000000000..1b524b8e1 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipShowPeerAction.java @@ -0,0 +1,26 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.manager.action.ManagerAction; +import org.asteriskjava.pbx.EndPoint; + +public class SipShowPeerAction extends AbstractManagerAction { + + private final EndPoint _peer; + + public SipShowPeerAction(final EndPoint peer) { + this._peer = peer; + } + + @Override + public ManagerAction getAJAction() { + final org.asteriskjava.manager.action.SipShowPeerAction action = new org.asteriskjava.manager.action.SipShowPeerAction(); + action.setActionId(this.getActionId()); + action.setPeer(this._peer.getSimpleName()); + return action; + } + + public String toString() { + return "SipShowPeerAction: peer=" + this._peer; //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/StatusAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/StatusAction.java new file mode 100644 index 000000000..be7ab9b1f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/StatusAction.java @@ -0,0 +1,48 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +public class StatusAction extends AbstractManagerAction implements EventGeneratingAction { + // used when the status of a single channel has been requested. + final private Channel _channel; + + public StatusAction() { + this._channel = null; + } + + public StatusAction(Channel channel) { + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + // channel specific request only available since 1.6 + if (pbx.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) + this._channel = channel; + else + this._channel = null; + } + + public org.asteriskjava.manager.action.ManagerAction getAJAction() { + final org.asteriskjava.manager.action.StatusAction action; + if (_channel == null) + action = new org.asteriskjava.manager.action.StatusAction(); + else + action = new org.asteriskjava.manager.action.StatusAction(_channel.getChannelName()); + + return action; + } + + @Override + public org.asteriskjava.manager.action.EventGeneratingAction getAJEventGeneratingAction() { + final org.asteriskjava.manager.action.StatusAction action = (org.asteriskjava.manager.action.StatusAction) getAJAction(); + action.setActionId(getActionId()); + + return action; + } + + public String toString() { + return "StatusAction"; //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/UserEventAction.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/UserEventAction.java new file mode 100644 index 000000000..9ef4d54fb --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/UserEventAction.java @@ -0,0 +1,21 @@ +package org.asteriskjava.pbx.asterisk.wrap.actions; + +import org.asteriskjava.pbx.asterisk.wrap.userEvents.UserEvent; + +abstract public class UserEventAction extends AbstractManagerAction { + + private String _actionId; + + public UserEventAction(UserEvent event) { + // NOOP + } + + public void setActionId(String actionId) { + this._actionId = actionId; + } + + public String getActionId() { + return this._actionId; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractChannelStateEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractChannelStateEvent.java new file mode 100644 index 000000000..477f58890 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractChannelStateEvent.java @@ -0,0 +1,31 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public abstract class AbstractChannelStateEvent extends ChannelEventHelper { + + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Log logger = LogFactory.getLog(AbstractChannelStateEvent.class); + + private final ChannelState channelState; + private final String channelStateDesc; + + AbstractChannelStateEvent(final org.asteriskjava.manager.event.AbstractChannelStateEvent event) throws InvalidChannelName { + super(event); + this.channelState = ChannelState.valueOfDesc(event.getChannelStateDesc()); + this.channelStateDesc = event.getChannelStateDesc(); + } + + public ChannelState getChannelState() { + return this.channelState; + } + + public String getChannelStateDesc() { + return this.channelStateDesc; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractMeetMeEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractMeetMeEvent.java new file mode 100644 index 000000000..723a080ed --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractMeetMeEvent.java @@ -0,0 +1,30 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class AbstractMeetMeEvent extends ChannelEventHelper { + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Log logger = LogFactory.getLog(AbstractMeetMeEvent.class); + + private final String meetMe; + private final Integer userNum; + + public AbstractMeetMeEvent(final org.asteriskjava.manager.event.AbstractMeetMeEvent event) throws InvalidChannelName { + super(event.getChannel(), event.getUniqueId()); + this.meetMe = event.getMeetMe(); + this.userNum = event.getUser(); + } + + public String getMeetMe() { + return this.meetMe; + } + + public Integer getUserNum() { + return this.userNum; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractParkedCallEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractParkedCallEvent.java new file mode 100644 index 000000000..921424b68 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractParkedCallEvent.java @@ -0,0 +1,29 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class AbstractParkedCallEvent extends ChannelEventHelper { + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Log logger = LogFactory.getLog(AbstractParkedCallEvent.class); + + private final String exten; + private final String parkingLot; + + AbstractParkedCallEvent(final org.asteriskjava.manager.event.AbstractParkedCallEvent event) throws InvalidChannelName { + super(event.getParkeeChannel(), event.getUniqueId(), event.getCallerIdNum(), event.getCallerIdName()); + this.exten = event.getExten(); + this.parkingLot = event.getParkingLot(); + } + + public String getExten() { + return this.exten; + } + + public String getParkingLot() { + return this.parkingLot; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentCalledEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentCalledEvent.java new file mode 100644 index 000000000..e06daa5cd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentCalledEvent.java @@ -0,0 +1,32 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class AgentCalledEvent extends ChannelEventHelper { + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Log logger = LogFactory.getLog(AgentCalledEvent.class); + + private String queue; + + private String agentInterface; + + public AgentCalledEvent(final org.asteriskjava.manager.event.AgentCalledEvent event) throws InvalidChannelName { + super(event.getChannelCalling(), event.getUniqueId(), event.getCallerIdNum(), event.getCallerIdName()); + + agentInterface = event.getAgentCalled(); + queue = event.getQueue(); + } + + public String getQueueName() { + return queue; + } + + public String getAgentInterface() { + return agentInterface; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentConnectEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentConnectEvent.java new file mode 100644 index 000000000..73095025c --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentConnectEvent.java @@ -0,0 +1,32 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class AgentConnectEvent extends ChannelEventHelper { + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Log logger = LogFactory.getLog(AgentConnectEvent.class); + + private String queue; + + private String agentInterface; + + public AgentConnectEvent(final org.asteriskjava.manager.event.AgentConnectEvent event) throws InvalidChannelName { + super(event.getChannel(), event.getUniqueId(), event.getCallerIdNum(), event.getCallerIdName()); + + agentInterface = event.getInterface(); + queue = event.getQueue(); + } + + public String getQueueName() { + return queue; + } + + public String getAgentInterface() { + return agentInterface; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BlindTransferEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BlindTransferEvent.java new file mode 100644 index 000000000..9f4689383 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BlindTransferEvent.java @@ -0,0 +1,267 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.Date; + +public class BlindTransferEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Log logger = LogFactory.getLog(BlindTransferEvent.class); + + org.asteriskjava.manager.event.BlindTransferEvent rawEvent; + + private final Channel transfereeChannel; + + private final Channel transfererChannel; + + public BlindTransferEvent(final org.asteriskjava.manager.event.BlindTransferEvent event) throws InvalidChannelName { + super(event); + rawEvent = event; + + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this.transfereeChannel = pbx.internalRegisterChannel(event.getTransfereeChannel(), event.getTransfereeUniqueId()); + this.transfererChannel = pbx.internalRegisterChannel(event.getTransfererChannel(), event.getTransfererUniqueId()); + + } + + public String getBridgeUniqueId() { + return rawEvent.getBridgeUniqueId(); + } + + public String getBridgeType() { + return rawEvent.getBridgeType(); + } + + public Integer getBridgeNumChannels() { + return rawEvent.getBridgeNumChannels(); + } + + public String getBridgeCreator() { + return rawEvent.getBridgeCreator(); + } + + public String getBridgeName() { + return rawEvent.getBridgeName(); + } + + public String getBridgeTechnology() { + return rawEvent.getBridgeTechnology(); + } + + public String getCallerIdName() { + return rawEvent.getCallerIdName(); + } + + public String getAccountCode() { + return rawEvent.getAccountCode(); + } + + public String getBridgevideosourcemode() { + return rawEvent.getBridgevideosourcemode(); + } + + public String getConnectedLineNum() { + return rawEvent.getConnectedLineNum(); + } + + public String getConnectedLineName() { + return rawEvent.getConnectedLineName(); + } + + public Integer getPriority() { + return rawEvent.getPriority(); + } + + public Integer getChannelState() { + return rawEvent.getChannelState(); + } + + public String getChannelStateDesc() { + return rawEvent.getChannelStateDesc(); + } + + public String getExten() { + return rawEvent.getExten(); + } + + public String getCallerIdNum() { + return rawEvent.getCallerIdNum(); + } + + public String getContext() { + return rawEvent.getContext(); + } + + public Date getDateReceived() { + return rawEvent.getDateReceived(); + } + + public String getPrivilege() { + return rawEvent.getPrivilege(); + } + + public String getExtension() { + return rawEvent.getExtension(); + } + + public String getIsexternal() { + return rawEvent.getIsexternal(); + } + + public String getResult() { + return rawEvent.getResult(); + } + + public final String getServer() { + return rawEvent.getServer(); + } + + public String getFile() { + return rawEvent.getFile(); + } + + public Integer getLine() { + return rawEvent.getLine(); + } + + public String getFunc() { + return rawEvent.getFunc(); + } + + public Integer getSequenceNumber() { + return rawEvent.getSequenceNumber(); + } + + public Object getSource() { + return rawEvent.getSource(); + } + + public String getTransfererUniqueId() { + return rawEvent.getTransfererUniqueId(); + } + + public String getTransfererConnectedLineNum() { + return rawEvent.getTransfererConnectedLineNum(); + } + + public String getTransfererConnectedLineName() { + return rawEvent.getTransfererConnectedLineName(); + } + + public String getTransfererCallerIdName() { + return rawEvent.getTransfererCallerIdName(); + } + + public String getTransfererCallerIdNum() { + return rawEvent.getTransfererCallerIdNum(); + } + + public Channel getTransfererChannel() { + return transfererChannel; + } + + public String getTransfererChannelState() { + return rawEvent.getTransfererChannelState(); + } + + public String getTransfererChannelStateDesc() { + return rawEvent.getTransfererChannelStateDesc(); + } + + public Integer getTransfererPriority() { + return rawEvent.getTransfererPriority(); + } + + public String getTransfererContext() { + return rawEvent.getTransfererContext(); + } + + public String getTransfereeUniqueId() { + return rawEvent.getTransfereeUniqueId(); + } + + public String getTransfereeConnectedLineNum() { + return rawEvent.getTransfereeConnectedLineNum(); + } + + public String getTransfereeConnectedLineName() { + return rawEvent.getTransfereeConnectedLineName(); + } + + public String getTransfereeCallerIdName() { + return rawEvent.getTransfereeCallerIdName(); + } + + public String getTransfereeCallerIdNum() { + return rawEvent.getTransfereeCallerIdNum(); + } + + public Channel getTransfereeChannel() { + return transfereeChannel; + } + + public String getTransfereeChannelState() { + return rawEvent.getTransfereeChannelState(); + } + + public String getTransfereeChannelStateDesc() { + return rawEvent.getTransfereeChannelStateDesc(); + } + + public Integer getTransfereePriority() { + return rawEvent.getTransfereePriority(); + } + + public final Double getTimestamp() { + return rawEvent.getTimestamp(); + } + + public String getTransfereeContext() { + return rawEvent.getTransfereeContext(); + } + + public String getTransfereeExten() { + return rawEvent.getTransfereeExten(); + } + + public String getTransfereeLinkedId() { + return rawEvent.getTransfereeLinkedId(); + } + + public String getTransfererAccountCode() { + return rawEvent.getTransfererAccountCode(); + } + + public String getTransfererExten() { + return rawEvent.getTransfererExten(); + } + + public String getTransfererLanguage() { + return rawEvent.getTransfererLanguage(); + } + + public String getSystemName() { + return rawEvent.getSystemName(); + } + + public String getTransfererLinkedId() { + return rawEvent.getTransfererLinkedId(); + } + + public String getTransfereeLanguage() { + return rawEvent.getTransfereeLanguage(); + } + + public String toString() { + return rawEvent.toString(); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BridgeEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BridgeEvent.java new file mode 100644 index 000000000..fd572411b --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BridgeEvent.java @@ -0,0 +1,70 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class BridgeEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + @SuppressWarnings("unused") + private static final Log logger = LogFactory.getLog(BridgeEvent.class); + + enum BridgeState { + Link, Unlink + } + + private final BridgeState bridgeState; + private final Channel channel1; + private final Channel channel2; + + public BridgeEvent(final org.asteriskjava.manager.event.BridgeEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this.bridgeState = BridgeState.valueOf(event.getBridgeState()); + this.channel1 = pbx.internalRegisterChannel(event.getChannel1(), event.getUniqueId1()); + this.channel2 = pbx.internalRegisterChannel(event.getChannel2(), event.getUniqueId2()); + } + + public BridgeState getBridgeState() { + return this.bridgeState; + } + + public Channel getChannel1() { + return this.channel1; + } + + public Channel getChannel2() { + return this.channel2; + } + + /** + * Returns whether the two channels have been linked. + * + * @return true the two channels have been linked, + * false if they have been unlinked. + * @since 1.0.0 + */ + public boolean isLink() { + return this.bridgeState == BridgeState.Link; + } + + /** + * Returns whether the two channels have been unlinked. + * + * @return true the two channels have been unlinked, + * false if they have been linked. + * @since 1.0.0 + */ + public boolean isUnlink() { + return this.bridgeState == BridgeState.Unlink; + } + + public String toString() { + return "BridgeEvent: channel1:" + this.channel1 + " channel2:" + this.channel2 + " bridgeState:" + this.bridgeState; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEvent.java new file mode 100644 index 000000000..5cec903e3 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEvent.java @@ -0,0 +1,7 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; + +public interface ChannelEvent { + Channel getChannel(); +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEventHelper.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEventHelper.java new file mode 100644 index 000000000..93dbcb111 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEventHelper.java @@ -0,0 +1,55 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +public abstract class ChannelEventHelper extends ManagerEvent implements ChannelEvent { + private static final long serialVersionUID = 1L; + + /** + * The name of the channel. + */ + private final Channel channel; + + protected ChannelEventHelper(final org.asteriskjava.manager.event.AbstractChannelEvent event) throws InvalidChannelName { + this(event.getChannel(), event.getUniqueId(), event.getCallerIdNum(), event.getCallerIdName()); + } + + protected ChannelEventHelper(final String channel, final String uniqueId, final String callerIdNum, + final String callerIdName) throws InvalidChannelName { + super(""); // we must have a source but since don't have one pass + // anything. + if (channel != null) { + this.channel = ChannelEventHelper.registerChannel(channel, uniqueId, callerIdNum, callerIdName); + } else { + this.channel = null; + } + } + + public ChannelEventHelper(final String channel, final String uniqueId) throws InvalidChannelName { + super("");// we must have a source but since don't have one pass + // anything. + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + if (channel != null) { + this.channel = pbx.internalRegisterChannel(channel, uniqueId); + } else { + this.channel = null; + } + } + + @Override + public Channel getChannel() { + return this.channel; + } + + public static Channel registerChannel(final String channelName, final String uniqueId, final String callerIdNum, + final String callerIdName) throws InvalidChannelName { + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + final Channel channel = pbx.internalRegisterChannel(channelName, uniqueId); + channel.setCallerId(pbx.buildCallerID(callerIdNum, callerIdName)); + return channel; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelState.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelState.java new file mode 100644 index 000000000..4e7414ba7 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelState.java @@ -0,0 +1,35 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +/** + * Holds the state of a channel as used by NewStateEvent and NewChannelEvent. + * + * @author bsutton + */ +public enum ChannelState { + Down, Rsrvd, OffHook, Dialing, Ring, Ringing, Up, Busy, DialingOffhook("Dialing Offhook"), PreRing("Pre-ring"); //$NON-NLS-1$ //$NON-NLS-2$ + + String _text; + + static ChannelState valueOfDesc(String description) { + ChannelState theState = null; + + for (ChannelState aState : ChannelState.values()) { + if (aState._text.compareToIgnoreCase(description) == 0) { + theState = aState; + break; + } + } + + return theState; + + } + + ChannelState(String text) { + this._text = text; + } + + ChannelState() { + this._text = this.name(); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListCompleteEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListCompleteEvent.java new file mode 100644 index 000000000..e4427d66a --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListCompleteEvent.java @@ -0,0 +1,10 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class ConfbridgeListCompleteEvent extends ManagerEvent { + + private static final long serialVersionUID = 1L; + + public ConfbridgeListCompleteEvent(org.asteriskjava.manager.event.ConfbridgeListCompleteEvent source) { + super(source); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListEvent.java new file mode 100644 index 000000000..a6e738f9f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListEvent.java @@ -0,0 +1,22 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class ConfbridgeListEvent extends ResponseEvent { + + private static final long serialVersionUID = 1L; + private String conference; + private String channel; + + public ConfbridgeListEvent(org.asteriskjava.manager.event.ConfbridgeListEvent source) { + super(source); + conference = source.getConference(); + channel = source.getChannel(); + } + + public String getChannel() { + return channel; + } + + public String getConference() { + return conference; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConnectEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConnectEvent.java new file mode 100644 index 000000000..08c6f7023 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConnectEvent.java @@ -0,0 +1,20 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class ConnectEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + /** + * The version of the manager protocol. + */ + private final String protocolIdentifier; + + public ConnectEvent(final org.asteriskjava.manager.event.ConnectEvent event) { + super(event); + this.protocolIdentifier = event.getProtocolIdentifier(); + } + + public String getProtocolIdentifier() { + return this.protocolIdentifier; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DbGetResponseEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DbGetResponseEvent.java new file mode 100644 index 000000000..f76c4bc2d --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DbGetResponseEvent.java @@ -0,0 +1,29 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class DbGetResponseEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + private final String family; + private final String key; + private final String val; + + public DbGetResponseEvent(final org.asteriskjava.manager.event.DbGetResponseEvent event) { + super(event); + this.family = event.getFamily(); + this.key = event.getKey(); + this.val = event.getVal(); + } + + public String getVal() { + return this.val; + } + + public String getFamily() { + return this.family; + } + + public String getKey() { + return this.key; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialBeginEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialBeginEvent.java new file mode 100644 index 000000000..c91133940 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialBeginEvent.java @@ -0,0 +1,208 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +import java.util.Date; + +public class DialBeginEvent extends ChannelEventHelper { + private static final long serialVersionUID = 1L; + + /** + * The name of the destination channel. + */ + private final Channel destChannel; + + final org.asteriskjava.manager.event.DialBeginEvent rawEvent; + + public DialBeginEvent(final org.asteriskjava.manager.event.DialBeginEvent event) throws InvalidChannelName { + super(event.getChannel(), event.getUniqueId(), event.getCallerIdNum(), event.getCallerIdName()); + + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + if (event.getDestination() != null) + this.destChannel = pbx.internalRegisterChannel(event.getDestChannel(), event.getDestUniqueId()); + else + this.destChannel = null; + + rawEvent = event; + + } + + public String getDestination() { + return rawEvent.getDestination(); + } + + public String getLanguage() { + return rawEvent.getLanguage(); + } + + public String getDestLanguage() { + return rawEvent.getDestLanguage(); + } + + public String getDestAccountCode() { + return rawEvent.getDestAccountCode(); + } + + public String getDestLinkedId() { + return rawEvent.getDestLinkedId(); + } + + public String getLinkedId() { + return rawEvent.getLinkedId(); + } + + public String getCallerIdName() { + return rawEvent.getCallerIdName(); + } + + public String getConnectedLineNum() { + return rawEvent.getConnectedLineNum(); + } + + public String getConnectedLineName() { + return rawEvent.getConnectedLineName(); + } + + public Integer getPriority() { + return rawEvent.getPriority(); + } + + public Integer getChannelState() { + return rawEvent.getChannelState(); + } + + public String getChannelStateDesc() { + return rawEvent.getChannelStateDesc(); + } + + public String getExten() { + return rawEvent.getExten(); + } + + public String getCallerIdNum() { + return rawEvent.getCallerIdNum(); + } + + public String getContext() { + return rawEvent.getContext(); + } + + public String getSubEvent() { + return rawEvent.getSubEvent(); + } + + public Date getDateReceived() { + return rawEvent.getDateReceived(); + } + + @SuppressWarnings("deprecation") + public String getSrc() { + return rawEvent.getSrc(); + } + + public String getPrivilege() { + return rawEvent.getPrivilege(); + } + + public final Double getTimestamp() { + return rawEvent.getTimestamp(); + } + + public Channel getDestChannel() { + return destChannel; + } + + @SuppressWarnings("deprecation") + public String getCallerId() { + return rawEvent.getCallerId(); + } + + public final String getServer() { + return rawEvent.getServer(); + } + + public String getUniqueId() { + return rawEvent.getUniqueId(); + } + + public String getSystemName() { + return rawEvent.getSystemName(); + } + + @SuppressWarnings("deprecation") + public String getSrcUniqueId() { + return rawEvent.getSrcUniqueId(); + } + + public String getFile() { + return rawEvent.getFile(); + } + + public String getDestUniqueId() { + return rawEvent.getDestUniqueId(); + } + + public Integer getLine() { + return rawEvent.getLine(); + } + + public String getDialString() { + return rawEvent.getDialString(); + } + + public String getDialStatus() { + return rawEvent.getDialStatus(); + } + + public String getFunc() { + return rawEvent.getFunc(); + } + + public Integer getSequenceNumber() { + return rawEvent.getSequenceNumber(); + } + + public Integer getDestChannelState() { + return rawEvent.getDestChannelState(); + } + + public String getDestContext() { + return rawEvent.getDestContext(); + } + + public Integer getDestPriority() { + return rawEvent.getDestPriority(); + } + + public String getDestChannelStateDesc() { + return rawEvent.getDestChannelStateDesc(); + } + + public String getDestExten() { + return rawEvent.getDestExten(); + } + + public String getDestConnectedLineName() { + return rawEvent.getDestConnectedLineName(); + } + + public String getDestConnectedLineNum() { + return rawEvent.getDestConnectedLineNum(); + } + + public String getDestCallerIdName() { + return rawEvent.getDestCallerIdName(); + } + + public String getDestCallerIdNum() { + return rawEvent.getDestCallerIdNum(); + } + + public Object getSource() { + return rawEvent.getSource(); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEndEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEndEvent.java new file mode 100644 index 000000000..89632e4a5 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEndEvent.java @@ -0,0 +1,216 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +import java.util.Date; + +public class DialEndEvent extends ChannelEventHelper { + private static final long serialVersionUID = 1L; + + /** + * The name of the destination channel. + */ + private final Channel destChannel; + + final org.asteriskjava.manager.event.DialEndEvent rawEvent; + + public DialEndEvent(final org.asteriskjava.manager.event.DialEndEvent event) throws InvalidChannelName { + super(event.getChannel(), event.getUniqueId(), event.getCallerIdNum(), event.getCallerIdName()); + + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + if (event.getDestination() != null) + this.destChannel = pbx.internalRegisterChannel(event.getDestChannel(), event.getDestUniqueId()); + else + this.destChannel = null; + + rawEvent = event; + + } + + public String getDestination() { + return rawEvent.getDestination(); + } + + public String getLanguage() { + return rawEvent.getLanguage(); + } + + public String getDestLanguage() { + return rawEvent.getDestLanguage(); + } + + public String getAccountCode() { + return rawEvent.getAccountCode(); + } + + public String getDestAccountCode() { + return rawEvent.getDestAccountCode(); + } + + public String getDestLinkedId() { + return rawEvent.getDestLinkedId(); + } + + public String getLinkedId() { + return rawEvent.getLinkedId(); + } + + public String getForward() { + return rawEvent.getForward(); + } + + public String getCallerIdName() { + return rawEvent.getCallerIdName(); + } + + public String getConnectedLineNum() { + return rawEvent.getConnectedLineNum(); + } + + public String getConnectedLineName() { + return rawEvent.getConnectedLineName(); + } + + public Integer getPriority() { + return rawEvent.getPriority(); + } + + public Integer getChannelState() { + return rawEvent.getChannelState(); + } + + public String getChannelStateDesc() { + return rawEvent.getChannelStateDesc(); + } + + public String getExten() { + return rawEvent.getExten(); + } + + public String getCallerIdNum() { + return rawEvent.getCallerIdNum(); + } + + public String getContext() { + return rawEvent.getContext(); + } + + public String getSubEvent() { + return rawEvent.getSubEvent(); + } + + public Date getDateReceived() { + return rawEvent.getDateReceived(); + } + + @SuppressWarnings("deprecation") + public String getSrc() { + return rawEvent.getSrc(); + } + + public String getPrivilege() { + return rawEvent.getPrivilege(); + } + + public final Double getTimestamp() { + return rawEvent.getTimestamp(); + } + + public Channel getDestChannel() { + return destChannel; + } + + @SuppressWarnings("deprecation") + public String getCallerId() { + return rawEvent.getCallerId(); + } + + public final String getServer() { + return rawEvent.getServer(); + } + + public String getUniqueId() { + return rawEvent.getUniqueId(); + } + + public String getSystemName() { + return rawEvent.getSystemName(); + } + + @SuppressWarnings("deprecation") + public String getSrcUniqueId() { + return rawEvent.getSrcUniqueId(); + } + + public String getFile() { + return rawEvent.getFile(); + } + + public String getDestUniqueId() { + return rawEvent.getDestUniqueId(); + } + + public Integer getLine() { + return rawEvent.getLine(); + } + + public String getDialString() { + return rawEvent.getDialString(); + } + + public String getDialStatus() { + return rawEvent.getDialStatus(); + } + + public String getFunc() { + return rawEvent.getFunc(); + } + + public Integer getSequenceNumber() { + return rawEvent.getSequenceNumber(); + } + + public Integer getDestChannelState() { + return rawEvent.getDestChannelState(); + } + + public String getDestContext() { + return rawEvent.getDestContext(); + } + + public Integer getDestPriority() { + return rawEvent.getDestPriority(); + } + + public String getDestChannelStateDesc() { + return rawEvent.getDestChannelStateDesc(); + } + + public String getDestExten() { + return rawEvent.getDestExten(); + } + + public String getDestConnectedLineName() { + return rawEvent.getDestConnectedLineName(); + } + + public String getDestConnectedLineNum() { + return rawEvent.getDestConnectedLineNum(); + } + + public String getDestCallerIdName() { + return rawEvent.getDestCallerIdName(); + } + + public String getDestCallerIdNum() { + return rawEvent.getDestCallerIdNum(); + } + + public Object getSource() { + return rawEvent.getSource(); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEvent.java new file mode 100644 index 000000000..3574bc5dd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEvent.java @@ -0,0 +1,45 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +public class DialEvent extends ChannelEventHelper { + private static final long serialVersionUID = 1L; + + /** + * The name of the destination channel. + */ + private final Channel destination; + + private final String dialString; + private final String dialStatus; + + public DialEvent(final org.asteriskjava.manager.event.DialEvent event) throws InvalidChannelName { + super(event.getChannel(), event.getUniqueId(), event.getCallerIdNum(), event.getCallerIdName()); + + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + if (event.getDestination() != null) + this.destination = pbx.internalRegisterChannel(event.getDestination(), event.getDestUniqueId()); + else + this.destination = null; + + this.dialString = event.getDialString(); + this.dialStatus = event.getDialStatus(); + + } + + public Channel getDestination() { + return this.destination; + } + + public String getDialString() { + return this.dialString; + } + + public String getDialStatus() { + return this.dialStatus; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DisconnectEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DisconnectEvent.java new file mode 100644 index 000000000..2e457cba0 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DisconnectEvent.java @@ -0,0 +1,9 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class DisconnectEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + public DisconnectEvent(final org.asteriskjava.manager.event.DisconnectEvent event) { + super(event); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DndStateEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DndStateEvent.java new file mode 100644 index 000000000..50ac20832 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DndStateEvent.java @@ -0,0 +1,37 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.core.ChannelImpl; + +public class DndStateEvent extends ManagerEvent implements ChannelEvent { + private static final long serialVersionUID = 1L; + + /** + * The name of the channel. + */ + private final Channel channel; + + /** + * The DND state of the channel. + */ + private final Boolean state; + + public DndStateEvent(final org.asteriskjava.manager.event.DndStateEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + this.channel = pbx.internalRegisterChannel(event.getChannel(), ChannelImpl.UNKNOWN_UNIQUE_ID); + this.state = event.getState(); + } + + @Override + public Channel getChannel() { + return this.channel; + } + + public Boolean getState() { + return this.state; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ExtensionStatusEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ExtensionStatusEvent.java new file mode 100644 index 000000000..1951b7886 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ExtensionStatusEvent.java @@ -0,0 +1,80 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class ExtensionStatusEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + enum Status { + + /** + * No device INUSE or BUSY. + */ + NOT_INUSE(org.asteriskjava.manager.event.ExtensionStatusEvent.NOT_INUSE), + + /** + * One or more devices INUSE. + */ + INUSE(org.asteriskjava.manager.event.ExtensionStatusEvent.INUSE), + + /** + * All devices BUSY. + */ + BUSY(org.asteriskjava.manager.event.ExtensionStatusEvent.BUSY), + + /** + * All devices UNAVAILABLE/UNREGISTERED. + */ + UNAVAILABLE(org.asteriskjava.manager.event.ExtensionStatusEvent.UNAVAILABLE), + + /** + * One or more devices RINGING. + */ + RINGING(org.asteriskjava.manager.event.ExtensionStatusEvent.RINGING); + + int _status; + + Status(int status) { + this._status = status; + } + + static Status valueOf(Integer status) { + Status theStatus = null; + for (Status aStatus : Status.values()) { + if (aStatus._status == status) { + theStatus = aStatus; + break; + } + } + return theStatus; + } + } + + private final String exten; + private final String context; + private final String hint; + private final Status status; + + public ExtensionStatusEvent(final org.asteriskjava.manager.event.ExtensionStatusEvent event) { + super(event); + this.exten = event.getExten(); + this.context = event.getContext(); + this.hint = event.getHint(); + this.status = Status.valueOf(event.getStatus()); + } + + public String getExten() { + return this.exten; + } + + public String getContext() { + return this.context; + } + + public String getHint() { + return this.hint; + } + + public Status getStatus() { + return this.status; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/HangupEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/HangupEvent.java new file mode 100644 index 000000000..144766626 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/HangupEvent.java @@ -0,0 +1,51 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +public class HangupEvent extends ManagerEvent implements ChannelEvent { + private static final long serialVersionUID = 1L; + + /** + * The name of the channel. + */ + private final Channel channel; + + private final Integer cause; + private final String causeTxt; + private final String uniqueId; + + public HangupEvent(final org.asteriskjava.manager.event.HangupEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this.channel = pbx.registerHangupChannel(event.getChannel(), event.getUniqueId()); + this.cause = event.getCause(); + this.causeTxt = event.getCauseTxt(); + this.uniqueId = event.getUniqueId(); + + } + + public Integer getCause() { + return this.cause; + } + + public String getCauseTxt() { + return this.causeTxt; + } + + @Override + public Channel getChannel() { + return this.channel; + } + + public String getUniqueId() { + return this.uniqueId; + } + + public String toString() { + return "HangupEvent: channel:" + this.channel + " cause:" + this.causeTxt; //$NON-NLS-1$//$NON-NLS-2$ + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/LinkEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/LinkEvent.java new file mode 100644 index 000000000..13c6dfc1a --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/LinkEvent.java @@ -0,0 +1,12 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.InvalidChannelName; + +public class LinkEvent extends BridgeEvent { + private static final long serialVersionUID = 1L; + + @SuppressWarnings("deprecation") + public LinkEvent(final org.asteriskjava.manager.event.LinkEvent event) throws InvalidChannelName { + super(event); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ManagerEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ManagerEvent.java new file mode 100644 index 000000000..1f2cff256 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ManagerEvent.java @@ -0,0 +1,12 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import java.util.EventObject; + +public class ManagerEvent extends EventObject { + private static final long serialVersionUID = 1L; + + public ManagerEvent(Object source) { + super(source); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MasqueradeEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MasqueradeEvent.java new file mode 100644 index 000000000..f6695509f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MasqueradeEvent.java @@ -0,0 +1,144 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.core.ChannelImpl; + +/** + * A Masquerade is used when a new channel is created to replace an existing + * channel. The typical cause of this is an action such as a Redirect, Park etc. + * During the Redirect a new channel will be created which has the same name as + * the existing channel but with a Suffix attached such as ASYNCGOTO. The suffix + * selected will depend on the actual action that cause the masquerade. As we + * proxy all channels a key goal for us is for the existing proxy to end up + * containing the new channel. The existing channel will eventually be renamed + * with a suffix and then go on to become a zombie before it is hungup. + * The masquerade event is associated a NewEvent, three renames and one hangup + * event. The terminology used by asterisk is quite confusing. The 'original + * channel' is the channel created as a result of the action (redirect, park + * etc). The 'clone' channel is the pre-existing channel that was acted upon. + * New Event: Original - the Original channel is currently holding the active + * call due to the transfer/park.. event. - the Original name will be something + * like ASYNCGOTO/SIP/101-0000002D:1351178863.121 Masquerade Event: Clone, + * Original (e.g. SIP/101-0000002D:1351178863.121, + * ASYNCGOTO/SIP/101-0000002D:1351178863.121) - swap the guts of the two + * channels - for us this means that we swap the channels between the two parent + * proxies. Some channel information is also copied from the clone to the + * original channel (yes this terminology appears to be arse about. Remember the + * 'clone' is the pre-existing channel). Rename: Clone to Clone (e.g. + * rename the pre-existing channel SIP/101-0000002D:1351178863.121 to + * SIP/101-0000002D:1351178863.121 - start shutting down the clone + * (pre-existing channel). Rename: Original to Clone's initial name Name (e.g + * rename ASYNCGOTO/SIP/101-0000002D:1351178863.121, + * SIP/101-0000002D:1351178863.121) Rename:Clone to Clone (e.g. + * rename SIP/101-0000002D:1351178863.121 to + * SIP/101-0000002D:1351178863.121 Hangup: Clone (e.g. hangup + * SIP/101-0000002D:1351178863.121 Example sequence: RedirectAction: + * chanel=(proxy=2) SIP/101-0000002F:1351181832.124 context=njr-operator + * exten=njr-musiconhold priority=1 extraContext=null extraChannel=null + * extraExten=null Dump of LiveChannels, cause:Add: (proxy=3) + * ASYNCGOTO/SIP/101-0000002F:1351181837.125 ChannelProxy: (proxy=1) + * SIP/110-0000002E:1351181832.123 ChannelProxy: (proxy=2) + * SIP/101-0000002F:1351181832.124 ChannelProxy: (proxy=3) + * ASYNCGOTO/SIP/101-0000002F:1351181837.125 dispatch=NewChannelEvent: channel: + * (proxy=3) ASYNCGOTO/SIP/101-0000002F:1351181837.125 context=from-internal + * exten=null state=Up dispatch=MasqueradeEvent: originalChannel:(proxy=3) + * ASYNCGOTO/SIP/101-0000002F:1351181837.125 cloned from:(proxy=2) + * SIP/101-0000002F:1351181832.124 Dump of LiveChannels, cause:Masquerade: + * (proxy=2) ASYNCGOTO/SIP/101-0000002F:1351181837.125 ChannelProxy: (proxy=1) + * SIP/110-0000002E:1351181832.123 ChannelProxy: (proxy=2) + * ASYNCGOTO/SIP/101-0000002F:1351181837.125 ChannelProxy: (proxy=3) + * SIP/101-0000002F:1351181832.124 RenameEvent: existing channel: (proxy=3) + * SIP/101-0000002F:1351181832.124 + * newname=SIP/101-0000002frawExisting:SIP/101-0000002f + * rawNewname:SIP/101-0000002frawUniquID:1351181832.124 Dump of + * LiveChannels, cause:RenameEvent: (proxy=3) + * SIP/101-0000002F:1351181832.124 ChannelProxy: (proxy=1) + * SIP/110-0000002E:1351181832.123 ChannelProxy: (proxy=2) + * ASYNCGOTO/SIP/101-0000002F:1351181837.125 ChannelProxy: (proxy=3) + * SIP/101-0000002F:1351181832.124 dispatch=RenameEvent: existing channel: + * (proxy=2) ASYNCGOTO/SIP/101-0000002F:1351181837.125 + * newname=SIP/101-0000002frawExisting:AsyncGoto/SIP/101-0000002f + * rawNewname:SIP/101-0000002frawUniquID:1351181837.125 Dump of LiveChannels, + * cause:RenameEvent: (proxy=2) SIP/101-0000002F:1351181837.125 ChannelProxy: + * (proxy=1) SIP/110-0000002E:1351181832.123 ChannelProxy: (proxy=2) + * SIP/101-0000002F:1351181837.125 ChannelProxy: (proxy=3) + * SIP/101-0000002F:1351181832.124 dispatch=RenameEvent: existing channel: + * (proxy=3) SIP/101-0000002F:1351181832.124 + * newname=AsyncGoto/SIP/101-0000002frawExisting:SIP/101-0000002f + * rawNewname:AsyncGoto/SIP/101-0000002frawUniquID:1351181832.124 Dump + * of LiveChannels, cause:RenameEvent: (proxy=3) + * ASYNCGOTO/SIP/101-0000002F:1351181832.124 ChannelProxy: (proxy=1) + * SIP/110-0000002E:1351181832.123 ChannelProxy: (proxy=2) + * SIP/101-0000002F:1351181837.125 ChannelProxy: (proxy=3) + * ASYNCGOTO/SIP/101-0000002F:1351181832.124 dispatch=BridgeEvent: + * channel1:(proxy=1) SIP/110-0000002E:1351181832.123 channel2:(proxy=3) + * ASYNCGOTO/SIP/101-0000002F:1351181832.124 bridgeState:Unlink + * dispatch=HangupEvent: channel:(proxy=3) + * ASYNCGOTO/SIP/101-0000002F:1351181832.124 cause:Normal Clearing Dump + * of LiveChannels, cause:Removing: (proxy=3) + * ASYNCGOTO/SIP/101-0000002F:1351181832.124 ChannelProxy: (proxy=1) + * SIP/110-0000002E:1351181832.123 ChannelProxy: (proxy=2) + * SIP/101-0000002F:1351181837.125 dispatch=HangupEvent: channel:(proxy=1) + * SIP/110-0000002E:1351181832.123 cause:Normal Clearing Dump of LiveChannels, + * cause:Removing: (proxy=1) SIP/110-0000002E:1351181832.123 ChannelProxy: + * (proxy=2) SIP/101-0000002F:1351181837.125 The end result is that the original + * (new) channel ends up with the clones (pre-existing) channel name. The + * pre-existing proxy ends up holding the original channel with the pre-existing + * channel's initial name. The masquerade event then is about ripping the guts + * out of the clone (pre-existing channel) and swapping with the original (new) + * channel. At the end of the swap the original (new) channel is left active (as + * it has the clones guts) and the clone (pre-existing) is inactive so we can + * hangup the clone as it is no longer needed. + * + * @author bsutton + */ +public class MasqueradeEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + private final Channel _original; + + private final Channel _clone; + + private ChannelState cloneState; + + private ChannelState originalState; + + public MasqueradeEvent(final org.asteriskjava.manager.event.MasqueradeEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this._original = pbx.internalRegisterChannel(event.getOriginal(), ChannelImpl.UNKNOWN_UNIQUE_ID); + this._clone = pbx.internalRegisterChannel(event.getClone(), ChannelImpl.UNKNOWN_UNIQUE_ID); + this.originalState = ChannelState.valueOf(event.getOriginalStateDesc()); + this.cloneState = ChannelState.valueOf(event.getCloneStateDesc()); + } + + /** + * Returns the original channel + * + * @return + */ + public Channel getOriginal() { + return this._original; + } + + public Channel getClone() { + return this._clone; + } + + public ChannelState getCloneState() { + return this.cloneState; + } + + public ChannelState getOriginalState() { + return this.originalState; + } + + public String toString() { + // Even though it talks about the original channel + return "MasqueradeEvent: originalChannel(new):" + this._original + " cloned from (pre-existing):" + this._clone; //$NON-NLS-1$//$NON-NLS-2$ + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeJoinEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeJoinEvent.java new file mode 100644 index 000000000..54e5a1e71 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeJoinEvent.java @@ -0,0 +1,25 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.CallerID; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBX; +import org.asteriskjava.pbx.PBXFactory; + +public class MeetMeJoinEvent extends AbstractMeetMeEvent { + private static final long serialVersionUID = 1L; + + CallerID callerID; + + public MeetMeJoinEvent(final org.asteriskjava.manager.event.MeetMeJoinEvent event) throws InvalidChannelName { + super(event); + final PBX pbx = PBXFactory.getActivePBX(); + + pbx.buildCallerID(event.getCallerIdNum(), event.getCallerIdName()); + + } + + public CallerID getCallerID() { + return this.callerID; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeLeaveEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeLeaveEvent.java new file mode 100644 index 000000000..45cb81e22 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeLeaveEvent.java @@ -0,0 +1,31 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.CallerID; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBX; +import org.asteriskjava.pbx.PBXFactory; + +public class MeetMeLeaveEvent extends AbstractMeetMeEvent { + private static final long serialVersionUID = 1L; + + private final CallerID callerID; + private final Long duration; + + public MeetMeLeaveEvent(final org.asteriskjava.manager.event.MeetMeLeaveEvent event) throws InvalidChannelName { + super(event); + + final PBX pbx = PBXFactory.getActivePBX(); + + this.callerID = pbx.buildCallerID(event.getCallerIdNum(), event.getCallerIdName()); + this.duration = event.getDuration(); + } + + public CallerID getCallerID() { + return this.callerID; + } + + public Long getDuration() { + return this.duration; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewChannelEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewChannelEvent.java new file mode 100644 index 000000000..74df7d71a --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewChannelEvent.java @@ -0,0 +1,43 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +public class NewChannelEvent extends AbstractChannelStateEvent { + private static final long serialVersionUID = 1L; + + private final String accountCode; + private final String context; + private final String exten; + + public NewChannelEvent(final org.asteriskjava.manager.event.NewChannelEvent event) throws InvalidChannelName { + super(event); + this.accountCode = event.getAccountCode(); + this.context = event.getContext(); + this.exten = event.getExten(); + + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + pbx.internalRegisterChannel(event.getChannel(), event.getUniqueId()); + + } + + public String getAccountCode() { + return this.accountCode; + } + + public String getContext() { + return this.context; + } + + public String getExten() { + return this.exten; + } + + public String toString() { + return "NewChannelEvent: channel: " + this.getChannel() + " context=" + this.context + " exten=" + this.exten //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + " state=" + this.getChannelStateDesc(); //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewExtenEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewExtenEvent.java new file mode 100644 index 000000000..608f705c4 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewExtenEvent.java @@ -0,0 +1,55 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +public class NewExtenEvent extends ManagerEvent implements ChannelEvent { + private static final long serialVersionUID = 1L; + + private final String context; + private final String extension; + private final String application; + private final String appData; + private final Integer priority; + private final Channel channel; + + public NewExtenEvent(final org.asteriskjava.manager.event.NewExtenEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this.channel = pbx.internalRegisterChannel(event.getChannel(), event.getUniqueId()); + this.context = event.getContext(); + this.extension = event.getExtension(); + this.application = event.getApplication(); + this.appData = event.getAppData(); + this.priority = event.getPriority(); + } + + public String getContext() { + return this.context; + } + + public String getExtension() { + return this.extension; + } + + public String getApplication() { + return this.application; + } + + public String getAppData() { + return this.appData; + } + + public Integer getPriority() { + return this.priority; + } + + @Override + public Channel getChannel() { + return this.channel; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewStateEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewStateEvent.java new file mode 100644 index 000000000..e010919b4 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewStateEvent.java @@ -0,0 +1,22 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.internal.core.ChannelProxy; + +public class NewStateEvent extends AbstractChannelStateEvent { + private static final long serialVersionUID = 1L; + private ChannelProxy destChannel; + + public NewStateEvent(final org.asteriskjava.manager.event.NewStateEvent event) throws InvalidChannelName { + super(event); + } + + public Channel getDestination() { + return destChannel; + } + + public String toString() { + return "NewStateEvent: channel:" + this.getChannel() + " channelState:" + this.getChannelState(); //$NON-NLS-1$//$NON-NLS-2$ + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/OriginateResponseEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/OriginateResponseEvent.java new file mode 100644 index 000000000..ce056a3ab --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/OriginateResponseEvent.java @@ -0,0 +1,78 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.internal.core.ChannelImpl; + +public class OriginateResponseEvent extends ResponseEvent implements ChannelEvent { + + private static final long serialVersionUID = 1L; + + // reflects whether we have a iChannel or an iEndPoint. We can't have both. + private final boolean isChannel; + private final Channel channel; + private final EndPoint endPoint; + private final String response; + private final String context; + private final String exten; + private final Integer reason; + + public OriginateResponseEvent(final org.asteriskjava.manager.event.OriginateResponseEvent event) + throws InvalidChannelName { + super(event); + + PBX pbx = PBXFactory.getActivePBX(); + + // The doco says this should be a channel but under 1.4 it comes up as + // an endpoint. + this.isChannel = pbx.isChannel(event.getChannel()); + if (this.isChannel) { + this.channel = ChannelEventHelper.registerChannel(event.getChannel(), + (event.getUniqueId() == null ? ChannelImpl.UNKNOWN_UNIQUE_ID : event.getUniqueId()), + event.getCallerIdNum(), event.getCallerIdName()); + this.endPoint = null; + } else { + this.endPoint = pbx.buildEndPoint(TechType.SIP, event.getChannel()); + this.channel = null; + } + + this.response = event.getResponse(); + this.context = event.getContext(); + this.exten = event.getExten(); + this.reason = event.getReason(); + + } + + public String getResponse() { + return this.response; + } + + public String getContext() { + return this.context; + } + + public String getExten() { + return this.exten; + } + + public Integer getReason() { + return this.reason; + } + + public boolean isChannel() { + return this.isChannel; + } + + @Override + public Channel getChannel() { + return this.channel; + } + + public EndPoint getEndPoint() { + return this.endPoint; + } + + public boolean isSuccess() { + return "Success".equalsIgnoreCase(this.response); //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ParkedCallEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ParkedCallEvent.java new file mode 100644 index 000000000..5ebd2b5bc --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ParkedCallEvent.java @@ -0,0 +1,46 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.core.ChannelImpl; + +public class ParkedCallEvent extends ManagerEvent { + + private static final long serialVersionUID = 1L; + + private final Channel fromChannel; + private final Integer timeout; + private String exten; + + public ParkedCallEvent(final org.asteriskjava.manager.event.ParkedCallEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + if (event.getParkerDialString() != null) + this.fromChannel = pbx.internalRegisterChannel(event.getParkerDialString(), ChannelImpl.UNKNOWN_UNIQUE_ID); + else + this.fromChannel = null; + this.timeout = event.getTimeout(); + this.exten = event.getExten(); + } + + /** + * The channel that parked the call. In some circumstances this can be null. + * + * @return + */ + public Channel getFromChannel() { + return this.fromChannel; + } + + public Integer getTimeout() { + return this.timeout; + } + + public String getExten() { + return this.exten; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerEntryEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerEntryEvent.java new file mode 100644 index 000000000..4bab04390 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerEntryEvent.java @@ -0,0 +1,23 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.EndPoint; +import org.asteriskjava.pbx.PBX; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.TechType; + +public class PeerEntryEvent extends ResponseEvent { + private static final long serialVersionUID = 1L; + + private final EndPoint peer; + + public PeerEntryEvent(final org.asteriskjava.manager.event.PeerEntryEvent event) { + super(event); + + PBX pbx = PBXFactory.getActivePBX(); + this.peer = pbx.buildEndPoint(TechType.valueOf(event.getChannelType()), event.getObjectName()); + } + + public EndPoint getPeer() { + return this.peer; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerStatusEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerStatusEvent.java new file mode 100644 index 000000000..fbab23813 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerStatusEvent.java @@ -0,0 +1,24 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.EndPoint; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +public class PeerStatusEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + private final EndPoint peer; + + public PeerStatusEvent(final org.asteriskjava.manager.event.PeerStatusEvent event) { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this.peer = pbx.buildEndPoint(event.getPeer());// registerChannel(event.getPeer(), + // Channel.UNKNOWN_UNIQUE_ID); + } + + public EndPoint getPeer() { + return this.peer; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerlistCompleteEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerlistCompleteEvent.java new file mode 100644 index 000000000..e9f7f998c --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerlistCompleteEvent.java @@ -0,0 +1,9 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class PeerlistCompleteEvent extends ResponseEvent { + private static final long serialVersionUID = 1L; + + public PeerlistCompleteEvent(final org.asteriskjava.manager.event.PeerlistCompleteEvent event) { + super(event); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/QueueCallerLeaveEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/QueueCallerLeaveEvent.java new file mode 100644 index 000000000..10230480f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/QueueCallerLeaveEvent.java @@ -0,0 +1,20 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.InvalidChannelName; + +public class QueueCallerLeaveEvent extends ChannelEventHelper { + private static final long serialVersionUID = 1L; + + private String queue; + + public QueueCallerLeaveEvent(final org.asteriskjava.manager.event.QueueCallerLeaveEvent event) throws InvalidChannelName { + super(event.getChannel(), event.getUniqueId(), event.getCallerIdNum(), event.getCallerIdName()); + + queue = event.getQueue(); + } + + public String getQueueName() { + return queue; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ReloadEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ReloadEvent.java new file mode 100644 index 000000000..702bfb817 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ReloadEvent.java @@ -0,0 +1,10 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class ReloadEvent extends ManagerEvent { + + private static final long serialVersionUID = 1L; + + public ReloadEvent(final org.asteriskjava.manager.event.ReloadEvent event) { + super(event); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/RenameEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/RenameEvent.java new file mode 100644 index 000000000..95f9fa13c --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/RenameEvent.java @@ -0,0 +1,66 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.core.ChannelProxy; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class RenameEvent extends ManagerEvent implements ChannelEvent { + private static final long serialVersionUID = 1L; + + private static final Log logger = LogFactory.getLog(RenameEvent.class); + + /** + * The existing channel which is about to be renamed. + */ + private final Channel _channel; + + /** + * New name of the channel after renaming occurred. + */ + private final String _newName; + + private String uniqueId; + + public RenameEvent(final org.asteriskjava.manager.event.RenameEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this._channel = pbx.internalRegisterChannel(event.getChannel(), event.getUniqueId()); + this._newName = event.getNewname(); + + String uniqueId = ((ChannelProxy) this._channel).getRealChannel().getUniqueId(); + logger.debug("Renaming :" + uniqueId + " " + event.getUniqueId()); + + this.uniqueId = event.getUniqueId(); + + assert uniqueId.equalsIgnoreCase("-1") + || uniqueId.compareToIgnoreCase(event.getUniqueId()) == 0 : "Rename registered against incorrect channel"; //$NON-NLS-1$ + + } + + @Override + public final Channel getChannel() { + return this._channel; + } + + public final String getNewName() { + return this._newName; + } + + public final String getUniqueId() { + return uniqueId; + } + + @Override + public String toString() { + org.asteriskjava.manager.event.RenameEvent rawEvent = (org.asteriskjava.manager.event.RenameEvent) getSource(); + return "RenameEvent: existing channel: " + this._channel + " newname=" + this._newName //$NON-NLS-1$ //$NON-NLS-2$ + + "rawExisting:" + rawEvent.getChannel() + " rawNewname:" + rawEvent.getNewname() //$NON-NLS-1$ //$NON-NLS-2$ + + "rawUniquID:" + rawEvent.getUniqueId(); //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvent.java new file mode 100644 index 000000000..bd29067e4 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvent.java @@ -0,0 +1,23 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class ResponseEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + private final String actionId; + private final String internalActionId; + + public ResponseEvent(final org.asteriskjava.manager.event.ResponseEvent event) { + super(event); + this.actionId = event.getActionId(); + this.internalActionId = event.getInternalActionId(); + } + + public String getActionId() { + return this.actionId; + } + + public String getInternalActionId() { + return this.internalActionId; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvents.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvents.java new file mode 100644 index 000000000..8a095bfdd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvents.java @@ -0,0 +1,24 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import java.util.ArrayList; +import java.util.Collection; + +public class ResponseEvents { + + ArrayList events = new ArrayList<>(); + + /** + * Returns a Collection of ManagerEvents that have been received including + * the last one that indicates completion. + * + * @return a Collection of ManagerEvents received. + */ + public Collection getEvents() { + return this.events; + } + + public void add(ResponseEvent event) { + this.events.add(event); + + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusCompleteEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusCompleteEvent.java new file mode 100644 index 000000000..a4c6907a1 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusCompleteEvent.java @@ -0,0 +1,9 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +public class StatusCompleteEvent extends ResponseEvent { + private static final long serialVersionUID = 1L; + + public StatusCompleteEvent(final org.asteriskjava.manager.event.StatusCompleteEvent event) { + super(event); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusEvent.java new file mode 100644 index 000000000..1446400ba --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusEvent.java @@ -0,0 +1,93 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +import java.util.Map; + +public class StatusEvent extends ResponseEvent implements ChannelEvent { + private static final long serialVersionUID = 1L; + + private final Channel channel; + private final CallerID callerId; + private final String accountCode; + private final ChannelState channelState; + private final String channelStateDesc; + private final String context; + private final DialPlanExtension extension; + private final Integer priority; + private final Integer seconds; + private final Channel bridgedChannel; + private final Map variables; + private final String uniqueId; + + public StatusEvent(final org.asteriskjava.manager.event.StatusEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this.channel = pbx.internalRegisterChannel(event.getChannel(), event.getUniqueId()); + this.callerId = pbx.buildCallerID(event.getCallerIdNum(), event.getCallerIdName()); + this.accountCode = event.getAccountCode(); + this.channelState = ChannelState.valueOfDesc(event.getChannelStateDesc()); + this.channelStateDesc = event.getChannelStateDesc(); + this.context = event.getContext(); + this.extension = pbx.buildDialPlanExtension(event.getExtension()); + this.priority = event.getPriority(); + this.seconds = event.getSeconds(); + if (event.getBridgedChannel() != null) + this.bridgedChannel = pbx.internalRegisterChannel(event.getBridgedChannel(), event.getBridgedUniqueId()); + else + this.bridgedChannel = null; + this.variables = event.getVariables(); + this.uniqueId = event.getUniqueId(); + } + + @Override + public final Channel getChannel() { + return this.channel; + } + + public final CallerID getCallerId() { + return this.callerId; + } + + public final String getAccountCode() { + return this.accountCode; + } + + public final ChannelState getState() { + return this.channelState; + } + + public final String getChannelStateDesc() { + return this.channelStateDesc; + } + + public final String getContext() { + return this.context; + } + + public final DialPlanExtension getExtension() { + return this.extension; + } + + public final Integer getPriority() { + return this.priority; + } + + public final Integer getSeconds() { + return this.seconds; + } + + public final Channel getBridgedChannel() { + return this.bridgedChannel; + } + + public final Map getVariables() { + return this.variables; + } + + public String getUniqueId() { + return this.uniqueId; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnlinkEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnlinkEvent.java new file mode 100644 index 000000000..3389983bd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnlinkEvent.java @@ -0,0 +1,12 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.InvalidChannelName; + +public class UnlinkEvent extends BridgeEvent { + private static final long serialVersionUID = 1L; + + @SuppressWarnings("deprecation") + public UnlinkEvent(final org.asteriskjava.manager.event.UnlinkEvent event) throws InvalidChannelName { + super(event); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnparkedCallEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnparkedCallEvent.java new file mode 100644 index 000000000..1f71857ca --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnparkedCallEvent.java @@ -0,0 +1,25 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.core.ChannelImpl; + +public class UnparkedCallEvent extends AbstractParkedCallEvent { + private static final long serialVersionUID = 1L; + + private final Channel fromChannel; + + public UnparkedCallEvent(final org.asteriskjava.manager.event.UnparkedCallEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this.fromChannel = pbx.internalRegisterChannel(event.getParkerDialString(), ChannelImpl.UNKNOWN_UNIQUE_ID); + } + + public Channel getFromChannel() { + return this.fromChannel; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/VarSetEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/VarSetEvent.java new file mode 100644 index 000000000..5df6731d6 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/VarSetEvent.java @@ -0,0 +1,41 @@ +package org.asteriskjava.pbx.asterisk.wrap.events; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +public class VarSetEvent extends ManagerEvent implements ChannelEvent { + private static final long serialVersionUID = 1L; + + /** + * The name of the channel. + */ + private final Channel _channel; + + private String _variableName; + + private String _variableValue; + + public VarSetEvent(final org.asteriskjava.manager.event.VarSetEvent event) throws InvalidChannelName { + super(event); + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + this._channel = pbx.internalRegisterChannel(event.getChannel(), event.getUniqueId()); + this._variableName = event.getVariable(); + this._variableValue = event.getValue(); + } + + @Override + public Channel getChannel() { + return this._channel; + } + + public String getVariableName() { + return this._variableName; + } + + public String getVariableValue() { + return this._variableValue; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/CommandResponse.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/CommandResponse.java new file mode 100644 index 000000000..135e76138 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/CommandResponse.java @@ -0,0 +1,29 @@ +package org.asteriskjava.pbx.asterisk.wrap.response; + +import java.util.Collections; +import java.util.List; + +public class CommandResponse extends ManagerResponse { + + private List result; + private boolean error; + + public CommandResponse(org.asteriskjava.manager.response.ManagerResponse response) { + super(response); + + if (response instanceof org.asteriskjava.manager.response.CommandResponse) { + result = ((org.asteriskjava.manager.response.CommandResponse) response).getResult(); + } else if (response instanceof org.asteriskjava.manager.response.ManagerError) { + error = true; + result = Collections.singletonList(response.getOutput()); + } + } + + public List getResult() { + return this.result; + } + + public boolean isError() { + return error; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerError.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerError.java new file mode 100644 index 000000000..68479b634 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerError.java @@ -0,0 +1,9 @@ +package org.asteriskjava.pbx.asterisk.wrap.response; + +public class ManagerError extends CommandResponse { + + public ManagerError(org.asteriskjava.manager.response.ManagerResponse error) { + super(error); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerResponse.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerResponse.java new file mode 100644 index 000000000..bd5715997 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerResponse.java @@ -0,0 +1,81 @@ +package org.asteriskjava.pbx.asterisk.wrap.response; + +import org.asteriskjava.manager.response.ManagerError; + +import java.util.Date; +import java.util.Locale; +import java.util.Map; + +public class ManagerResponse { + + private Date _dateReceived; + private String _actionId; + + /** + * The server from which this response has been received (only used with + * AstManProxy). + */ + final private String _server; + final private String _response; + final private String _eventList; + final private String message; + final private String _uniqueId; + final private Map _attributes; + + public ManagerResponse(org.asteriskjava.manager.response.ManagerResponse response) { + this._dateReceived = response.getDateReceived(); + this._actionId = response.getActionId(); + this._server = response.getServer(); + this._response = response.getResponse(); + this._eventList = response.getEventList(); + this._uniqueId = response.getUniqueId(); + this._attributes = response.getAttributes(); + + if (response instanceof ManagerError) { + this.message = response.getOutput(); + } else { + this.message = response.getMessage(); + } + } + + public Date getDateReceived() { + return this._dateReceived; + } + + public String getActionId() { + return this._actionId; + } + + public String getServer() { + return this._server; + } + + public String getResponse() { + return this._response; + } + + public String getEventList() { + return this._eventList; + } + + public String getMessage() { + return this.message; + } + + public String getUniqueId() { + return this._uniqueId; + } + + public Map getAttributes() { + return this._attributes; + } + + public String getAttribute(String key) { + return (String) this._attributes.get(key.toLowerCase(Locale.ENGLISH)); + } + + public boolean isSuccess() { + return this._response.compareToIgnoreCase("Success") == 0; //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/userEvents/UserEvent.java b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/userEvents/UserEvent.java new file mode 100644 index 000000000..d9dada2b9 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/userEvents/UserEvent.java @@ -0,0 +1,29 @@ +package org.asteriskjava.pbx.asterisk.wrap.userEvents; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; + +public class UserEvent extends ManagerEvent { + private static final long serialVersionUID = 1L; + + private Channel channel; + + public UserEvent(org.asteriskjava.manager.event.UserEvent source, Channel channel) { + super(source); + this.channel = channel; + } + + public UserEvent(org.asteriskjava.manager.event.UserEvent event) throws InvalidChannelName { + super(event); + + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + this.channel = pbx.internalRegisterChannel(event.getChannel(), event.getUniqueId()); + } + + public Channel getChannel() { + return this.channel; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/ActivityHelper.java b/src/main/java/org/asteriskjava/pbx/internal/activity/ActivityHelper.java new file mode 100644 index 000000000..fb490819d --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/ActivityHelper.java @@ -0,0 +1,170 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.lock.Lockable; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.asterisk.wrap.actions.SetVarAction; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.managerAPI.EventListenerBaseClass; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.Set; + +public abstract class ActivityHelper extends Lockable implements Runnable, Activity { + private static final Log logger = LogFactory.getLog(ActivityHelper.class); + + /** + * If the activity fails due to an exception then lastException will contain + * the final exception that was thrown. + */ + private PBXException lastException; + + /** + * Set to true once the activity succeeds. + */ + private volatile boolean _success = false; + + private final ActivityCallback callback; + + private final String activityName; + + private boolean _sendEvents; + + Exception callSite = new Exception("Invoked from here"); + + public ActivityHelper(final String activityName, final ActivityCallback callback) { + + this.callback = callback; + this.activityName = activityName; + } + + private AutoCloseable getManagerListener() { + if (!_sendEvents) { + return new AutoCloseable() { + + @Override + public void close() throws Exception { + // do nothing, we never started anything + } + }; + } + EventListenerBaseClass listener = new EventListenerBaseClass(activityName, PBXFactory.getActivePBX()) { + + @Override + public Set> requiredEvents() { + return ActivityHelper.this.requiredEvents(); + } + + @Override + public void onManagerEvent(ManagerEvent event) { + ActivityHelper.this.onManagerEvent(event); + + } + + @Override + public ListenerPriority getPriority() { + return ActivityHelper.this.getPriority(); + } + }; + listener.startListener(); + return listener; + + } + + @SuppressWarnings("unchecked") + public void startActivity(final boolean sendEvents) { + this._sendEvents = sendEvents; + if (this.callback != null) { + this.callback.progress((T) this, ActivityStatusEnum.START, ActivityStatusEnum.START.getDefaultMessage()); + } + + final Thread thread = new Thread(this, this.activityName); + thread.setDaemon(true); + thread.start(); + + } + + @Override + @SuppressWarnings("unchecked") + public void run() { + try (AutoCloseable closer = getManagerListener()) { + this._success = this.doActivity(); + } catch (final PBXException e) { + this.lastException = e; + ActivityHelper.logger.error(e, e); + logger.error(callSite, callSite); + } catch (final Throwable e) { + this.lastException = new PBXException(e); + ActivityHelper.logger.error(callSite, callSite); + logger.error(e, e); + } finally { + if (this.callback != null) { + if (this._success) { + this.callback.progress((T) this, ActivityStatusEnum.SUCCESS, + ActivityStatusEnum.SUCCESS.getDefaultMessage()); + } else { + // This went badly so make certain we hang everything up + this.callback.progress((T) this, ActivityStatusEnum.FAILURE, + ActivityStatusEnum.FAILURE.getDefaultMessage()); + } + } + } + + } + + abstract protected boolean doActivity() throws PBXException; + + /* + * Attempt to set a variable on the channel to see if it's up. + * @param channel the channel which is to be tested. + */ + public boolean validateChannel(final Channel channel) { + + boolean ret = false; + final SetVarAction var = new SetVarAction(channel, "testState", "1"); + + ManagerResponse response = null; + try { + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + response = pbx.sendAction(var, 500); + } catch (final Exception e) { + ActivityHelper.logger.debug(e, e); + ActivityHelper.logger.error("getVariable: " + e); + } + if ((response != null) && (response.getAttribute("Response").compareToIgnoreCase("success") == 0)) { + ret = true; + } + + return ret; + + } + + @Override + public boolean isSuccess() { + return this._success; + } + + protected void setLastException(final PBXException e) { + this.lastException = e; + } + + @Override + public Throwable getLastException() { + return this.lastException; + } + + public void progess(final T activity, final String message) { + this.callback.progress(activity, ActivityStatusEnum.PROGRESS, message); + + } + + abstract HashSet> requiredEvents(); + + abstract void onManagerEvent(final ManagerEvent event); + + abstract public ListenerPriority getPriority(); + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/BlindTransferActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/BlindTransferActivityImpl.java new file mode 100644 index 000000000..73f63ae9a --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/BlindTransferActivityImpl.java @@ -0,0 +1,280 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.Call.OperandChannel; +import org.asteriskjava.pbx.activities.BlindTransferActivity; +import org.asteriskjava.pbx.agi.AgiChannelActivityBlindTransfer; +import org.asteriskjava.pbx.agi.BlindTransferResultListener; +import org.asteriskjava.pbx.asterisk.wrap.events.*; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.Objects; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * The BlindTransferActivity is used by the AsteriksPBX to transfer a live + * channel to an endpoint that may need to be dialed. + * + * @author bsutton + */ +public class BlindTransferActivityImpl extends ActivityHelper implements BlindTransferActivity { + private static final Log logger = LogFactory.getLog(BlindTransferActivityImpl.class); + + private final Call _call; + + private Call.OperandChannel _channelToTransfer; + + private EndPoint _transferTarget; + + private CallerID _toCallerID; + + private boolean _autoAnswer; + + private CountDownLatch _latch; + + private CompletionCause _completionCause; + + private long _timeout; + + /** + * The new channel that was originated for the transferTarget endpoint. + */ + private Channel _transferTargetChannel; + + private CallImpl _newCall; + + private Channel dialedChannel; + + final Channel actualChannelToTransfer; + + private String dialOptions; + + /** + * Blind transfers a live channel to a given endpoint which may need to be + * dialed. When we dial the endpoint we display the 'toCallerID'. + * + * @param channelToTransfer The channel which is being transfered + * @param transferTarget The target to transfer (connect) the channel to. + * @param toCallerID The caller id to display on the target endpoint. + * @param timeout The time to wait (in seconds) for the activity to + * complete. + * @param listener + */ + public BlindTransferActivityImpl(Call call, final Call.OperandChannel channelToTransfer, final EndPoint transferTarget, + final CallerID toCallerID, boolean autoAnswer, long timeout, + final ActivityCallback listener, String dialOptions) { + super("BlindTransferActivity", listener); + + this._call = Objects.requireNonNull(call); + this._channelToTransfer = channelToTransfer; + this._transferTarget = transferTarget; + this._toCallerID = toCallerID; + this._autoAnswer = autoAnswer; + this._timeout = timeout; + this.dialOptions = dialOptions; + + actualChannelToTransfer = _call.getOperandChannel(this._channelToTransfer); + + this.startActivity(true); + } + + public BlindTransferActivityImpl(Channel agentChannel, EndPoint transferTarget, CallerID toCallerID, boolean autoAnswer, + int timeout, ActivityCallback iCallback, String dialOptions) throws PBXException { + super("BlindTransferActivity", iCallback); + + this._transferTarget = transferTarget; + this._toCallerID = toCallerID; + this._autoAnswer = autoAnswer; + this._timeout = timeout; + actualChannelToTransfer = agentChannel; + this.dialOptions = dialOptions; + _channelToTransfer = OperandChannel.ORIGINATING_PARTY; + this._call = new CallImpl(agentChannel, CallDirection.OUTBOUND); + this.startActivity(true); + + } + + @Override + public boolean doActivity() throws PBXException { + + boolean success = false; + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + /* + * initiate a blind transfer of the call , to the specified destination. + * when a link event occurs this call will be removed from the active + * call list. + */ + try { + + logger.debug("*******************************************************************************"); + logger.info("*********** begin blind transfer ****************"); + logger.info("*********** " + this._channelToTransfer + " ****************"); + logger.debug("*********** " + this._transferTarget + " ****************"); + logger.debug("*********** " + this._toCallerID + " ****************"); + logger.debug("*******************************************************************************"); + + if (!pbx.moveChannelToAgi(actualChannelToTransfer)) { + throw new PBXException("Channel: " + this._channelToTransfer + " couldn't be moved to agi"); + } + + if (!pbx.waitForChannelToQuiescent(actualChannelToTransfer, 3000)) + throw new PBXException( + "Channel: " + this._channelToTransfer + " cannot be transfered as it is still in transition."); + + // Set or clear the auto answer header. + // Clearing is important as it may have been set during the + // initial answer sequence. If we don't clear it then then transfer + // target will be auto-answered, which is fun but bad. + String sipHeader = null; + if (this._autoAnswer) { + sipHeader = PBXFactory.getActiveProfile().getAutoAnswer(); + } + + this._latch = new CountDownLatch(1); + + BlindTransferResultListener listener = new BlindTransferResultListener() { + + @Override + public void result(String status, boolean success) { + if (_completionCause == null) { + _completionCause = CompletionCause.FAILED; + } + _latch.countDown(); + + } + }; + actualChannelToTransfer.setCurrentActivityAction( + new AgiChannelActivityBlindTransfer(this._transferTarget.getFullyQualifiedName(), sipHeader, + _toCallerID.getNumber(), dialOptions, listener)); + + // TODO: At one point we were adding the /n option to the end of the + // channel to get around + // secondary transfer options. Need to review if this is still + // required. + // TODO control the caller id. + + success = this._latch.await(this._timeout, TimeUnit.SECONDS); + if (!success) { + this._completionCause = CompletionCause.TIMEOUT; + } else if (_completionCause == CompletionCause.CANCELLED) { + logger.warn("Cancelled, hanging up dialed channel"); + pbx.hangup(dialedChannel); + } else { + Call call = ((CallImpl) _call).split(actualChannelToTransfer); + Call rhsCall = new CallImpl(_transferTargetChannel, CallDirection.OUTBOUND); + try { + _newCall = ((CallImpl) call).join(OperandChannel.ORIGINATING_PARTY, rhsCall, + OperandChannel.ORIGINATING_PARTY, CallDirection.OUTBOUND); + } catch (Exception e) { + logger.error("New call doesn't seem to exist!?"); + } + } + } catch (final Exception e) { + logger.error("error occurred in blindtransfer", e); + this.setLastException(new PBXException(e)); + } + + return this._completionCause == CompletionCause.BRIDGED; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + required.add(BridgeEvent.class); + required.add(LinkEvent.class); + required.add(UnlinkEvent.class); + required.add(HangupEvent.class); + required.add(DialEvent.class); + return required; + } + + @Override + public void onManagerEvent(final ManagerEvent event) { + try (LockCloser closer = this.withLock()) { + if (event instanceof BridgeEvent) { + BridgeEvent bridge = (BridgeEvent) event; + if (bridge.isLink()) { + if (bridge.getChannel1().isSame(_call.getOperandChannel(this._channelToTransfer))) { + this._completionCause = CompletionCause.BRIDGED; + this._transferTargetChannel = bridge.getChannel2(); + this._latch.countDown(); + } else if (bridge.getChannel2().isSame(_call.getOperandChannel(this._channelToTransfer))) { + this._completionCause = CompletionCause.BRIDGED; + this._transferTargetChannel = bridge.getChannel1(); + this._latch.countDown(); + } + } + } else if (event instanceof HangupEvent) { + HangupEvent hangup = (HangupEvent) event; + if (hangup.getChannel().isSame(_call.getOperandChannel(this._channelToTransfer))) { + this._completionCause = CompletionCause.HANGUP; + this._latch.countDown(); + } + if (hangup.getChannel().isSame(dialedChannel)) { + this._completionCause = CompletionCause.HANGUP; + this._latch.countDown(); + } + } else if (event instanceof DialEvent) { + DialEvent dialEvent = (DialEvent) event; + if (dialEvent.getChannel() != null) { + Channel operandChannel = _call.getOperandChannel(_channelToTransfer); + if (dialEvent.getChannel().isSame(operandChannel)) { + DialEvent de = (DialEvent) event; + dialedChannel = de.getDestination(); + } + } + } + } + + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + @Override + public CompletionCause getCompletionCause() { + return this._completionCause; + } + + /** + * cancels the BlindTransfer. + */ + @Override + public void cancel() { + this._completionCause = CompletionCause.CANCELLED; + this._latch.countDown(); + } + + @Override + public Channel getChannelToTransfer() { + return _call.getOperandChannel(this._channelToTransfer); + } + + @Override + public CallerID getTransferTargetCallerID() { + return this._toCallerID; + } + + @Override + public EndPoint getTransferTarget() { + return this._transferTarget; + } + + @Override + public Channel getTransferTargetChannel() { + return this._transferTargetChannel; + } + + @Override + public Call getNewCall() throws PBXException { + return _newCall; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/BridgeActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/BridgeActivityImpl.java new file mode 100644 index 000000000..0229b3499 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/BridgeActivityImpl.java @@ -0,0 +1,109 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.activities.BridgeActivity; +import org.asteriskjava.pbx.agi.AgiChannelActivityBridge; +import org.asteriskjava.pbx.agi.AgiChannelActivityHoldForBridge; +import org.asteriskjava.pbx.asterisk.wrap.events.*; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class BridgeActivityImpl extends ActivityHelper implements BridgeActivity { + private static final Log logger = LogFactory.getLog(BridgeActivityImpl.class); + private final Channel _lhsChannel; + private final Channel _rhsChannel; + + private CountDownLatch _bridgeLatch; + + public BridgeActivityImpl(final Channel lhsChannel, final Channel rhsChannel, + final ActivityCallback callback) { + super("Bridge", callback); + + this._lhsChannel = lhsChannel; + this._rhsChannel = rhsChannel; + this.startActivity(true); + } + + @Override + public boolean doActivity() throws PBXException { + boolean success = false; + + BridgeActivityImpl.logger.debug("*******************************************************************************"); + BridgeActivityImpl.logger.info("*********** begin Bridge ****************"); + BridgeActivityImpl.logger.info("*********** lhs:" + this._lhsChannel + " ****************"); + BridgeActivityImpl.logger.debug("*********** rhs:" + this._rhsChannel + " ****************"); + BridgeActivityImpl.logger.debug("*******************************************************************************"); + try { + + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + if (!pbx.moveChannelToAgi(_lhsChannel)) { + throw new PBXException("Channel: " + _lhsChannel + " couldn't be moved to agi"); + } + if (!pbx.moveChannelToAgi(_rhsChannel)) { + throw new PBXException("Channel: " + _rhsChannel + " couldn't be moved to agi"); + } + + List channels = new LinkedList<>(); + channels.add(this._lhsChannel); + channels.add(_rhsChannel); + if (!pbx.waitForChannelsToQuiescent(channels, 3000)) + throw new PBXException("Channel: " + this._lhsChannel + " cannot be held as it is still in transition."); + try { + if (pbx.isBridgeSupported()) { + + this._bridgeLatch = new CountDownLatch(1); + final AgiChannelActivityBridge action = new AgiChannelActivityBridge(_lhsChannel); + _lhsChannel.setCurrentActivityAction(new AgiChannelActivityHoldForBridge(action)); + _rhsChannel.setCurrentActivityAction(action); + + // now wait for the bridge event to arrive. + success = this._bridgeLatch.await(3, TimeUnit.SECONDS); + + } + } catch (IllegalArgumentException | IllegalStateException | InterruptedException e) { + throw new PBXException(e); + } + + } catch (IllegalArgumentException | IllegalStateException e) { + BridgeActivityImpl.logger.error(e, e); + BridgeActivityImpl.logger.error(e, e); + throw new PBXException(e); + } + return success; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + required.add(StatusCompleteEvent.class); + required.add(StatusEvent.class); + required.add(BridgeEvent.class); + required.add(LinkEvent.class); + return required; + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + @Override + public void onManagerEvent(ManagerEvent event) { + + if (event instanceof BridgeEvent) { + BridgeEvent bridge = (BridgeEvent) event; + if (bridge.isLink() + && (bridge.getChannel1().isSame(this._lhsChannel) || bridge.getChannel1().isSame(this._rhsChannel)) + && (bridge.getChannel2().isSame(this._lhsChannel) || bridge.getChannel2().isSame(this._rhsChannel))) + this._bridgeLatch.countDown(); + } + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/DialActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/DialActivityImpl.java new file mode 100644 index 000000000..106fc4762 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/DialActivityImpl.java @@ -0,0 +1,223 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.activities.DialActivity; +import org.asteriskjava.pbx.asterisk.wrap.actions.SetVarAction; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.managerAPI.Dial; +import org.asteriskjava.pbx.internal.managerAPI.OriginateResult; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.Map; + +public class DialActivityImpl extends ActivityHelper implements DialActivity, NewChannelListener { + private static final Log logger = LogFactory.getLog(DialActivityImpl.class); + + private final boolean hideToCallerId; + + private boolean cancelledByOperator; + + private final EndPoint _originating; + + /** + * Once the 'from' channel has been brought up this is set. + */ + private Channel originatingChannel; + + private final EndPoint _accepting; + + private final CallerID toCallerID; + + /** + * Once the 'to' channel has been brought up this is set. + */ + private Channel acceptingChannel; + + private CallImpl newCall; + + private Map channelVarsToSet; + + private String dialOptions; + + public DialActivityImpl(final EndPoint originating, final EndPoint accepting, final CallerID toCallerID, + final boolean hideToCallerID, final ActivityCallback listener, + Map channelVarsToSet, String dialOptions) { + super("Dial", listener); + this._originating = originating; + this._accepting = accepting; + this.toCallerID = toCallerID; + this.hideToCallerId = hideToCallerID; + this.cancelledByOperator = false; + this.channelVarsToSet = channelVarsToSet; + this.dialOptions = dialOptions; + + this.startActivity(false); + } + + @Override + public boolean doActivity() throws PBXException { + boolean success = false; + + try (Dial nr = new Dial(this.toCallerID.toString())) { + DialActivityImpl.logger.debug("*******************************************************************************"); + DialActivityImpl.logger.info("*********** begin dial out ****************"); + DialActivityImpl.logger.info("*********** " + this._accepting + " ****************"); + DialActivityImpl.logger.debug("*******************************************************************************"); + + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + + final OriginateResult[] resultChannels = nr.dial(this, this._originating, this._accepting, + profile.getManagementContext(), this.toCallerID, this.hideToCallerId, channelVarsToSet, dialOptions); + + if ((resultChannels[0] == null) || (resultChannels[1] == null)) { + // the dial failed + + // so notify the operator. + // Unless the operated cancelled the call + if (!this.cancelledByOperator) { + this.setLastException(new PBXException(("OperatorEndedCall"))); + DialActivityImpl.logger.error("dialout to " + this._accepting.getFullyQualifiedName() + " failed."); + } + } else { + // Dial succeeded. + + // - get new channel name from result + this.originatingChannel = resultChannels[0].getChannel(); + this.acceptingChannel = resultChannels[1].getChannel(); + + newCall = new CallImpl(originatingChannel, acceptingChannel, CallDirection.OUTBOUND); + + DialActivityImpl.logger.debug("dialout succeeded: dest channel is :" + this.acceptingChannel); + + if (!this.validateChannel(this.acceptingChannel)) { + this.setLastException(new PBXException(("dialed extension hungup unexpectedly"))); + DialActivityImpl.logger.error("dialed extension hungup unexpectedly"); + } else { + success = true; + } + } + } finally { + if (!success) { + this.hangup(); + } + } + return success; + } + + private void hangup() { + try { + final PBX pbx = PBXFactory.getActivePBX(); + if (this.acceptingChannel != null) { + logger.warn("Hanging up"); + pbx.hangup(this.acceptingChannel); + } + if (this.originatingChannel != null) { + logger.warn("Hanging up"); + pbx.hangup(this.originatingChannel); + } + } catch (final Exception e) { + DialActivityImpl.logger.error(e, e); + } + } + + /** + * Called to cancels the dial before it fully comes up. The caller must also + * hangup the associated channels. + */ + @Override + public void markCancelled() { + this.cancelledByOperator = true; + } + + @Override + public Channel getOriginatingChannel() { + return this.originatingChannel; + } + + @Override + public Channel getAcceptingChannel() { + return this.acceptingChannel; + } + + @Override + public EndPoint getOriginatingEndPoint() { + return this._originating; + } + + @Override + public EndPoint getAcceptingEndPoint() { + return this._accepting; + } + + @Override + public void channelUpdate(final Channel channel) { + if (channel.sameEndPoint(this._accepting)) { + this.acceptingChannel = channel; + } + + if (channel.sameEndPoint(this._originating)) { + this.originatingChannel = channel; + } + + super.progess(this, "Channel for " + channel.getEndPoint().getSIPSimpleName() + " is now up."); + + } + + /* + * Attempt to set a variable on the channel to see if it's up. + * @param channel the channel which is to be tested. + */ + @Override + public boolean validateChannel(final Channel channel) { + + boolean ret = false; + final SetVarAction var = new SetVarAction(channel, "testState", "1"); + + ManagerResponse response = null; + try { + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + response = pbx.sendAction(var, 500); + } catch (final Exception e) { + DialActivityImpl.logger.debug(e, e); + DialActivityImpl.logger.error("getVariable: " + e); + } + if ((response != null) && (response.getAttribute("Response").compareToIgnoreCase("success") == 0)) { + ret = true; + } + + return ret; + + } + + @Override + public boolean cancelledByOperator() { + return this.cancelledByOperator; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + // no required. + return required; + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + @Override + public void onManagerEvent(ManagerEvent event) { + // NOOP + } + + @Override + public Call getNewCall() { + return newCall; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/DialToAgiActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/DialToAgiActivityImpl.java new file mode 100644 index 000000000..7304e5565 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/DialToAgiActivityImpl.java @@ -0,0 +1,203 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.activities.DialToAgiActivity; +import org.asteriskjava.pbx.asterisk.wrap.actions.SetVarAction; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.managerAPI.DialToAgi; +import org.asteriskjava.pbx.internal.managerAPI.OriginateResult; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.Map; + +public class DialToAgiActivityImpl extends ActivityHelper implements DialToAgiActivity, NewChannelListener { + private static final Log logger = LogFactory.getLog(DialToAgiActivityImpl.class); + + private final boolean hideToCallerId; + + private boolean cancelledByOperator; + + private final EndPoint _originating; + + /** + * Once the 'from' channel has been brought up this is set. + */ + private Channel originatingChannel; + + private final CallerID toCallerID; + + private Map channelVarsToSet; + + private AgiChannelActivityAction action; + + private DialToAgi originator; + + private Integer timeout; + + public DialToAgiActivityImpl(final EndPoint originating, final CallerID toCallerID, Integer timeout, + final boolean hideToCallerID, final ActivityCallback listener, + Map channelVarsToSet, AgiChannelActivityAction action) { + super("Dial", listener); + this.timeout = timeout; + this.action = action; + this._originating = originating; + this.toCallerID = toCallerID; + this.hideToCallerId = hideToCallerID; + this.cancelledByOperator = false; + this.channelVarsToSet = channelVarsToSet; + + } + + public void dial() { + this.startActivity(false); + } + + @Override + public boolean doActivity() throws PBXException { + boolean success = false; + + try (DialToAgi nr = new DialToAgi(this.toCallerID.toString())) { + DialToAgiActivityImpl.logger.debug("**************************************************************************"); + DialToAgiActivityImpl.logger + .info("*********** begin dial out to agi " + _originating + " ***********"); + DialToAgiActivityImpl.logger.debug("**************************************************************************"); + + originator = nr; + + final OriginateResult[] resultChannels = nr.dial(this, this._originating, this.action, this.toCallerID, + this.timeout, this.hideToCallerId, channelVarsToSet); + + if (resultChannels[0] == null || !resultChannels[0].isSuccess()) { + // the dial failed + + // so notify the operator. + // Unless the operated cancelled the call + if (!this.cancelledByOperator) { + this.setLastException(new PBXException(("OperatorEndedCall"))); + logger.warn("dialout to " + _originating + " failed."); + } + } else { + // Dial succeeded. + + // - get new channel name from result + this.originatingChannel = resultChannels[0].getChannel(); + + DialToAgiActivityImpl.logger.debug("dialout succeeded"); + + success = true; + + } + } catch (InterruptedException e) { + logger.error(e); + } finally { + if (!success) { + this.hangup(); + } + } + return success; + } + + private void hangup() { + try { + final PBX pbx = PBXFactory.getActivePBX(); + + if (this.originatingChannel != null) { + logger.info("Hanging up"); + pbx.hangup(this.originatingChannel); + } + } catch (final Exception e) { + DialToAgiActivityImpl.logger.error(e, e); + } + } + + /** + * Called if the user cancels the call after starting it. The caller must + * also hangup the trc channel. + */ + @Override + public void markCancelled() { + this.cancelledByOperator = true; + } + + @Override + public Channel getOriginatingChannel() { + return this.originatingChannel; + } + + @Override + public EndPoint getOriginatingEndPoint() { + return this._originating; + } + + @Override + public void channelUpdate(final Channel channel) { + + if (channel.sameEndPoint(this._originating)) { + this.originatingChannel = channel; + } + + super.progess(this, "Channel for " + channel.getEndPoint().getSIPSimpleName() + " is now up."); + + } + + /* + * Attempt to set a variable on the channel to see if it's up. + * @param channel the channel which is to be tested. + */ + @Override + public boolean validateChannel(final Channel channel) { + + boolean ret = false; + final SetVarAction var = new SetVarAction(channel, "testState", "1"); + + ManagerResponse response = null; + try { + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + response = pbx.sendAction(var, 500); + } catch (final Exception e) { + DialToAgiActivityImpl.logger.debug(e, e); + DialToAgiActivityImpl.logger.error("getVariable: " + e); + } + if ((response != null) && (response.getAttribute("Response").compareToIgnoreCase("success") == 0)) { + ret = true; + } + + return ret; + + } + + @Override + public boolean cancelledByOperator() { + return this.cancelledByOperator; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + // no required. + return required; + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + @Override + public void onManagerEvent(ManagerEvent event) { + // NOOP + } + + public void abort() { + if (originator != null) { + originator.abort(); + } else { + logger.error("Call to abort, but it doesn't look like the Dial had started yet"); + } + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/HoldActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/HoldActivityImpl.java new file mode 100644 index 000000000..835cda768 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/HoldActivityImpl.java @@ -0,0 +1,73 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.activities.HoldActivity; +import org.asteriskjava.pbx.agi.AgiChannelActivityHold; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; + +public class HoldActivityImpl extends ActivityHelper implements HoldActivity { + private static final Log logger = LogFactory.getLog(HoldActivityImpl.class); + private final Channel _channel; + + public HoldActivityImpl(final Channel channel, final ActivityCallback callback) { + super("HoldCall", callback); + + this._channel = channel; + this.startActivity(false); + } + + @Override + public boolean doActivity() throws PBXException { + boolean success = false; + + HoldActivityImpl.logger.debug("*******************************************************************************"); + HoldActivityImpl.logger.info("*********** begin Hold Audio ****************"); + HoldActivityImpl.logger.info("*********** " + this._channel + " ****************"); + HoldActivityImpl.logger.debug("*******************************************************************************"); + try { + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + if (!pbx.moveChannelToAgi(_channel)) { + throw new PBXException("Channel: " + _channel + " couldn't be moved to agi"); + } + + _channel.setCurrentActivityAction(new AgiChannelActivityHold()); + success = true; + + } catch (IllegalArgumentException | IllegalStateException e) { + HoldActivityImpl.logger.error(e, e); + HoldActivityImpl.logger.error(e, e); + throw new PBXException(e); + } + return success; + } + + public Channel getChannel() { + return this._channel; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + // no events requried. + + return required; + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + @Override + public void onManagerEvent(ManagerEvent event) { + // NOOP + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/JoinActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/JoinActivityImpl.java new file mode 100644 index 000000000..fc0caacd8 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/JoinActivityImpl.java @@ -0,0 +1,150 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.Call.OperandChannel; +import org.asteriskjava.pbx.activities.JoinActivity; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +/** + * The JoinActivity is used by the AsteriksPBX implementation to Join two + * channels into a single call. The join activity expects two channels which are + * each a leg of a different call it will then join those two channels into a + * single call.iChannel hangupChannel, The channels that remain in the + * originating calls will be hungup implicitly. + * + * @author bsutton + */ +public class JoinActivityImpl extends ActivityHelper implements JoinActivity { + + private static final Log logger = LogFactory.getLog(JoinActivityImpl.class); + + private final Call _lhsCall; + private final OperandChannel _originatingOperand; + + private final Call _rhsCall; + private final OperandChannel _acceptingOperand; + private final CallDirection _direction; + + private Call _joined; + + private Exception callSite; + + /** + * Joins a specific channel from this call with a specific channel from + * another call which results in a new Call object being created. Channels + * that do not participate in the join are left in their original Call. + * + * @param lhsCall one of the calls we are joining + * @param originatingOperand the channel from lhsCall call that will + * participate in the join as the originating Channel + * @param rhsCall the other call we are joining. + * @param acceptingOperand the channel from the rhsCall that will + * participate in the join as the accepting channel. + * @return + * @throws PBXException + */ + public JoinActivityImpl(final Call lhsCall, OperandChannel originatingOperand, final Call rhsCall, + OperandChannel acceptingOperand, CallDirection direction, final ActivityCallback listener) { + super("JoinActivity", listener); + + callSite = new Exception("Call site"); + + this._lhsCall = lhsCall; + this._originatingOperand = originatingOperand; + this._rhsCall = rhsCall; + this._acceptingOperand = acceptingOperand; + this._direction = direction; + + if (this._lhsCall == null) { + throw new IllegalArgumentException("lhsCall may not be null"); + } + + if (this._originatingOperand == null) { + throw new IllegalArgumentException("lhsOperand may not be null"); + } + + if (this._rhsCall == null) { + throw new IllegalArgumentException("rhsCall may not be null"); + } + + if (this._acceptingOperand == null) { + throw new IllegalArgumentException("rhsOperand may not be null"); + } + + this.startActivity(true); + } + + @Override + public boolean doActivity() throws PBXException { + boolean success = false; + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + JoinActivityImpl.logger.debug("*******************************************************************************"); + JoinActivityImpl.logger.info("*********** begin join ****************"); + JoinActivityImpl.logger.info("*********** " + this._lhsCall + " ****************"); + JoinActivityImpl.logger.debug("*********** " + this._rhsCall + " ****************"); + JoinActivityImpl.logger.debug("*******************************************************************************"); + + try { + final Channel rhsChannel = this._rhsCall.getOperandChannel(this._acceptingOperand); + final Channel lhsChannel = this._lhsCall.getOperandChannel(this._originatingOperand); + + if (!pbx.moveChannelToAgi(rhsChannel)) { + throw new PBXException("Channel: " + rhsChannel + " couldn't be moved to agi"); + } + if (!pbx.moveChannelToAgi(lhsChannel)) { + throw new PBXException("Channel: " + lhsChannel + " couldn't be moved to agi"); + } + + List channels = new LinkedList<>(); + channels.add(lhsChannel); + channels.add(rhsChannel); + if (!pbx.waitForChannelsToQuiescent(channels, 3000)) { + logger.error(callSite, callSite); + throw new PBXException("Channel: " + rhsChannel + " cannot be joined as it is still in transition."); + } + // Now do the actual join on the pbx. + pbx.bridge(lhsChannel, rhsChannel); + this._joined = ((CallImpl) this._lhsCall).join(this._originatingOperand, this._rhsCall, this._acceptingOperand, + this._direction); + success = true; + + } catch (RuntimeException e) { + logger.error(e, e); + logger.error(callSite, callSite); + throw new PBXException(e); + + } + return success; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + return required; + } + + @Override + synchronized public void onManagerEvent(final ManagerEvent event) { + // NOOP + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + @Override + public Call getJoinedCall() { + return this._joined; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/ParkActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/ParkActivityImpl.java new file mode 100644 index 000000000..53000e297 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/ParkActivityImpl.java @@ -0,0 +1,166 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.manager.TimeoutException; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.activities.ParkActivity; +import org.asteriskjava.pbx.asterisk.wrap.actions.RedirectAction; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.ParkedCallEvent; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.io.IOException; +import java.util.HashSet; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * The ParkActivity is used by the AsteriksPBX implementation to park a channel. + * The park activity expects two channels which are two legs legs of the same + * call. The parkChannel will be redirect to the njr-park extension. The + * hangupChannel (the second leg of the call) will be hung up. The (obvious?) + * limitation is that we can't park something like a conference call as it has + * more than two channels. + * + * @author bsutton + */ +public class ParkActivityImpl extends ActivityHelper implements ParkActivity { + private static final Log logger = LogFactory.getLog(ParkActivityImpl.class); + + /** + * call - the call which is being packed. + */ + private final Call _call; + + /** + * parkChannel - the channel from the above call which is going to be + * parked. extension. + */ + private final Channel _parkChannel; + + private volatile EndPoint _parkingLot; + + private final CountDownLatch _latch = new CountDownLatch(1); + + /* + * @param call the that is being parked. + * @param parkChannel the channel from the call which is the one which will + * be parked. All other channels in the call will be hungup. + */ + public ParkActivityImpl(final Call call, final Channel parkChannel, final ActivityCallback listener) { + super("ParkActivity", listener); + + if (call == null) { + throw new IllegalArgumentException("call may not be null"); + } + if (parkChannel == null) { + throw new IllegalArgumentException("parkChannel may not be null"); + } + this._parkChannel = parkChannel; + this._call = call; + + if (!this._call.contains(parkChannel)) + throw new IllegalArgumentException("The parkChannel must be from the call."); + + this.startActivity(true); + } + + @Override + public boolean doActivity() throws PBXException { + boolean success = false; + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + ParkActivityImpl.logger.debug("*******************************************************************************"); + ParkActivityImpl.logger.info("*********** begin park ****************"); + ParkActivityImpl.logger.info("*********** " + this._parkChannel + " ****************"); + ParkActivityImpl.logger.debug("*******************************************************************************"); + + try { + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + + if (!pbx.waitForChannelToQuiescent(this._parkChannel, 3000)) + throw new PBXException("Channel: " + this._parkChannel + " cannot be parked as it is still in transition."); + + // The extension must be a non-qualified name as + // otherwise it would be of the form DIALPLAN/njr-park + final RedirectAction redirect = new RedirectAction(this._parkChannel, profile.getManagementContext(), + pbx.getExtensionPark(), 1); + + final ManagerResponse response = pbx.sendAction(redirect, 1000); + if ((response != null) && (response.getResponse().compareToIgnoreCase("success") == 0)) { + // Hangup the call as we have parked the other side of + // the call. + if (this._call.getDirection() == CallDirection.INBOUND) { + logger.warn("Hanging up"); + pbx.hangup(this._call.getAcceptingParty()); + } else { + logger.warn("Hanging up"); + pbx.hangup(this._call.getOriginatingParty()); + } + success = true; + } + + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { + ParkActivityImpl.logger.error(e, e); + throw new PBXException(e); + + } finally { + // we wait at most 2 seconds for the parking extension to + // arrive. + try { + if (success) { + if (!this._latch.await(2, TimeUnit.SECONDS)) { + logger.warn("Timeout, continuing"); + } + } + + if (this._parkingLot == null) { + success = false; + ParkActivityImpl.logger.warn("ParkCallEvent not recieved within 2 seconds of parking call."); + this.setLastException(new PBXException("ParkCallEvent not recieved within 2 seconds of parking call.")); + } + } catch (final InterruptedException e) { + ParkActivityImpl.logger.error(e, e); + + } + + } + return success; + } + + @Override + public EndPoint getParkingLot() { + return this._parkingLot; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + required.add(ParkedCallEvent.class); + + return required; + } + + @Override + public void onManagerEvent(final ManagerEvent event) { + try (LockCloser closer = this.withLock()) { + assert event instanceof ParkedCallEvent : "Unexpected event"; + + final ParkedCallEvent parkedEvent = (ParkedCallEvent) event; + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + this._parkingLot = pbx.buildEndPoint(TechType.LOCAL, parkedEvent.getExten()); + this._latch.countDown(); + } + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/RedirectToActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/RedirectToActivityImpl.java new file mode 100644 index 000000000..5c30dfa3a --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/RedirectToActivityImpl.java @@ -0,0 +1,174 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.activities.RedirectToActivity; +import org.asteriskjava.pbx.agi.AgiChannelActivityHold; +import org.asteriskjava.pbx.asterisk.wrap.actions.RedirectAction; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.core.ChannelProxy; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +/** + * The SplitActivity is used by the AsteriksPBX to split a call and place the + * component channels into the specialist Activity fastagi. The SplitActivity + * can only split a call with two channels. The (obvious?) limitation is that we + * can't split something in a conference call as it has more than two channels. + * + * @author bsutton + */ +public class RedirectToActivityImpl extends ActivityHelper implements RedirectToActivity { + private static final Log logger = LogFactory.getLog(RedirectToActivityImpl.class); + + private Channel channel1; + + private Call _lhsCall; + + /** + * Splits a call by moving each of its two channels into the Activity agi. + * The channels will sit in the agi (with no audio) until something is done + * with them. As such you should leave them split for too long. + * + * @param callToSplit The call to split + * @param listener + */ + public RedirectToActivityImpl(final Channel channel1, final ActivityCallback listener) { + super("SplitActivity", listener); + + this.channel1 = channel1; + + this.startActivity(true); + } + + @Override + public boolean doActivity() throws PBXException { + + RedirectToActivityImpl.logger.debug("***************************************************************************"); + RedirectToActivityImpl.logger.info("*********** begin redirect to activity ****************"); + RedirectToActivityImpl.logger.info("*********** " + this.channel1 + " ****************"); + RedirectToActivityImpl.logger.debug("***************************************************************************"); + + // Splits the originating and secondary channels by moving each of them + // into the associated + // target. + boolean success = false; + + if (this.channel1 != null) { + success = splitTwo(); + + // Now update the call to reflect the split + if (success) { + this._lhsCall = new CallImpl(channel1, CallDirection.OUTBOUND); + } + } + return success; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + // No events required. + return required; + } + + @Override + synchronized public void onManagerEvent(final ManagerEvent event) { + // NOOP + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + /** + * After a call has been split we get two new calls. One will hold the + * original remote party and the other will hold the original local party. + * + * @return the call which holds the original remote party. + */ + @Override + public Call getCall() { + return this._lhsCall; + } + + /** + * After a call has been split we get two new calls. One will hold the + * original remote party and the other will hold the original local party. + * + * @return the call which holds the original local party. + */ + + /** + * Splits two channels moving them to defined endpoints. + * + * @param lhs + * @param lhsTarget + * @param lhsTargetContext + * @param rhs + * @param rhsTarget + * @param rhsTargetContext + * @return + * @throws PBXException + */ + private boolean splitTwo() throws PBXException { + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + List channels = new LinkedList<>(); + channels.add(channel1); + if (!pbx.waitForChannelsToQuiescent(channels, 3000)) { + logger.error(callSite, callSite); + throw new PBXException("Channel: " + channel1 + " cannot be split as they are still in transition."); + } + + /* + * redirects the specified channels to the specified endpoints. Returns + * true or false reflecting success. + */ + + AgiChannelActivityHold agi1 = new AgiChannelActivityHold(); + + pbx.setVariable(channel1, "proxyId", "" + ((ChannelProxy) channel1).getIdentity()); + + channel1.setCurrentActivityAction(agi1); + + final String agiExten = profile.getAgiExtension(); + final String agiContext = profile.getManagementContext(); + logger.debug("redirect channel lhs:" + channel1 + " to " + agiExten + " in context " + agiContext); + + final EndPoint extensionAgi = pbx.getExtensionAgi(); + final RedirectAction redirect = new RedirectAction(channel1, agiContext, extensionAgi, 1); + // logger.error(redirect); + + boolean ret = false; + { + try { + + // final ManagerResponse response = + pbx.sendAction(redirect, 1000); + double ctr = 0; + while (!agi1.hasCallReachedAgi() && ctr < 10) { + Thread.sleep(100); + ctr += 100.0 / 1000.0; + if (!agi1.hasCallReachedAgi()) { + logger.warn("Waiting on (agi1) " + channel1); + } + + } + ret = agi1.hasCallReachedAgi(); + + } catch (final Exception e) { + logger.error(e, e); + } + } + return ret; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/SplitActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/SplitActivityImpl.java new file mode 100644 index 000000000..9fa432ca1 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/SplitActivityImpl.java @@ -0,0 +1,256 @@ +package org.asteriskjava.pbx.internal.activity; + +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.activities.SplitActivity; +import org.asteriskjava.pbx.agi.AgiChannelActivityBridge; +import org.asteriskjava.pbx.agi.AgiChannelActivityHold; +import org.asteriskjava.pbx.asterisk.wrap.actions.RedirectAction; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.RenameEvent; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.core.ChannelProxy; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +/** + * The SplitActivity is used by the AsteriksPBX to split a call and place the + * component channels into the specialist Activity fastagi. The SplitActivity + * can only split a call with two channels. The (obvious?) limitation is that we + * can't split something in a conference call as it has more than two channels. + * + * @author bsutton + */ +public class SplitActivityImpl extends ActivityHelper implements SplitActivity { + private static final Log logger = LogFactory.getLog(SplitActivityImpl.class); + + private Call _callToSplit; + + private Channel channel1; + + private Channel channel2; + + private Call _lhsCall; + + private Call _rhsCall; + + /** + * Splits a call by moving each of its two channels into the Activity agi. + * The channels will sit in the agi (with no audio) until something is done + * with them. As such you should leave them split for too long. + * + * @param callToSplit The call to split + * @param listener + */ + public SplitActivityImpl(final Call callToSplit, final ActivityCallback listener) { + super("SplitActivity", listener); + + renameEventReceived.set(new CountDownLatch(1)); + this._callToSplit = callToSplit; + + List tmp = callToSplit.getChannels(); + if (tmp.size() > 1) { + channel1 = tmp.get(0); + channel2 = tmp.get(1); + } + this.startActivity(true); + + } + + @Override + public boolean doActivity() throws PBXException { + + SplitActivityImpl.logger.debug("*******************************************************************************"); + SplitActivityImpl.logger.info("*********** begin split ****************"); + SplitActivityImpl.logger.info("*********** " + this.channel1 + " ****************"); + SplitActivityImpl.logger.debug("*********** " + this.channel2 + " ****************"); + SplitActivityImpl.logger.debug("*******************************************************************************"); + + // Splits the originating and secondary channels by moving each of them + // into the associated + // target. + boolean success = false; + + if (this.channel2 != null) { + success = splitTwo(); + + // Now update the call to reflect the split + if (success) { + this._lhsCall = ((CallImpl) this._callToSplit).split(channel1); + this._rhsCall = ((CallImpl) this._callToSplit).split(channel2); + } + } + return success; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + required.add(RenameEvent.class); + return required; + } + + final AtomicReference renameEventReceived = new AtomicReference<>(); + + @Override + public void onManagerEvent(final ManagerEvent event) { + try (LockCloser closer = this.withLock()) { + if (event instanceof RenameEvent) { + RenameEvent rename = (RenameEvent) event; + if (rename.getChannel().isSame(channel1) || rename.getChannel().isSame(channel2)) { + renameEventReceived.get().countDown(); + } + } + } + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + /** + * After a call has been split we get two new calls. One will hold the + * original remote party and the other will hold the original local party. + * + * @return the call which holds the original remote party. + */ + @Override + public Call getLHSCall() { + return this._lhsCall; + } + + /** + * After a call has been split we get two new calls. One will hold the + * original remote party and the other will hold the original local party. + * + * @return the call which holds the original local party. + */ + @Override + public Call getRHSCall() { + return this._rhsCall; + } + + /** + * Splits two channels moving them to defined endpoints. + * + * @param lhs + * @param lhsTarget + * @param lhsTargetContext + * @param rhs + * @param rhsTarget + * @param rhsTargetContext + * @return + * @throws PBXException + */ + private boolean splitTwo() throws PBXException { + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + if (channel1 == channel2) { + throw new PBXException("channel1 is the same as channel2. if I let this happen, asterisk will core dump :)"); + } + + List channels = new LinkedList<>(); + channels.add(channel1); + channels.add(channel2); + if (!pbx.waitForChannelsToQuiescent(channels, 3000)) { + logger.error(callSite, callSite); + throw new PBXException( + "Channel: " + channel1 + " or " + channel2 + " cannot be split as they are still in transition."); + } + + /* + * redirects the specified channels to the specified endpoints. Returns + * true or false reflecting success. + */ + + AgiChannelActivityHold agi1 = new AgiChannelActivityHold(); + AgiChannelActivityHold agi2 = new AgiChannelActivityHold(); + + pbx.setVariable(channel1, "proxyId", "" + ((ChannelProxy) channel1).getIdentity()); + pbx.setVariable(channel2, "proxyId", "" + ((ChannelProxy) channel2).getIdentity()); + + // AgiChannelAcitivyBridge has a latch which other activities may be + // sleeping on, so it's important + // to change the other channels activity first to avoid it waking and + // taking an undesired action + // when the AgiChannelActivityBridge channel has it's acitvity + // cancelled. + if (channel2.getCurrentActivityAction() instanceof AgiChannelActivityBridge) { + channel1.setCurrentActivityAction(agi1); + channel2.setCurrentActivityAction(agi2); + } else { + channel2.setCurrentActivityAction(agi2); + channel1.setCurrentActivityAction(agi1); + } + + final String agiExten = profile.getAgiExtension(); + final String agiContext = profile.getManagementContext(); + logger.debug("splitTwo channel lhs:" + channel1 + " to " + agiExten + " in context " + agiContext + " from " + + this._callToSplit); + + final EndPoint extensionAgi = pbx.getExtensionAgi(); + final RedirectAction redirect = new RedirectAction(channel1, agiContext, extensionAgi, 1); + redirect.setExtraChannel(channel2); + redirect.setExtraContext(agiContext); + redirect.setExtraExten(extensionAgi); + redirect.setExtraPriority(1); + // logger.error(redirect); + + boolean ret = false; + { + try { + + renameEventReceived.set(new CountDownLatch(1)); + // final ManagerResponse response = + pbx.sendAction(redirect, 1000); + if (pbx.expectRenameEvents()) { + + // wait for channels to unbridge + if (!renameEventReceived.get().await(2000, TimeUnit.MILLISECONDS)) { + logger.error("There was no rename event"); + } else { + logger.warn("Channels are renaming, now waiting for Quiescent"); + } + } + + channels.clear(); + + channels.add(channel1); + channels.add(channel2); + if (!pbx.waitForChannelsToQuiescent(channels, 3000)) { + logger.error(callSite, callSite); + throw new PBXException("Channel: " + channel1 + " or " + channel2 + + " cannot be split as they are still in transition."); + } + + double ctr = 0; + while ((!agi1.hasCallReachedAgi() || !agi2.hasCallReachedAgi()) && ctr < 10) { + Thread.sleep(100); + ctr += 100.0 / 1000.0; + if (!agi1.hasCallReachedAgi()) { + logger.info("Waiting on (agi1) " + channel1); + } + if (!agi2.hasCallReachedAgi()) { + logger.info("Waiting on (agi2) " + channel2); + } + } + ret = agi1.hasCallReachedAgi() && agi2.hasCallReachedAgi(); + + } catch (final Exception e) { + logger.error(e, e); + } + } + return ret; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/asterisk/CallerIDImpl.java b/src/main/java/org/asteriskjava/pbx/internal/asterisk/CallerIDImpl.java new file mode 100644 index 000000000..db7b773d2 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/CallerIDImpl.java @@ -0,0 +1,99 @@ +package org.asteriskjava.pbx.internal.asterisk; + +import org.asteriskjava.pbx.CallerID; +import org.asteriskjava.pbx.PBXFactory; + +public class CallerIDImpl implements CallerID { + private final String number; + private final String name; + private boolean hideCallerID = false; + + /** + * Creates a caller ID. + * + * @param number - if null then we store an empty string. + * @param name - if null then we store an empty string. + */ + public CallerIDImpl(final String number, final String name) { + this.number = (number == null ? "" : number.trim()); //$NON-NLS-1$ + this.name = (name == null ? "" : name.trim()); //$NON-NLS-1$ + } + + @Override + public String getNumber() { + return this.number; + } + + @Override + public String getName() { + return this.name; + } + + /** + * This is a little helper class which will buid the name component of a + * clid from the first and lastnames. If both firstname and lastname are + * null then the name component will be an empty string. + * + * @param firstname the person's firstname, may be null. + * @param lastname the person's lastname, may be null + * @param number the phone number. + * @return + */ + public static CallerID buildFromComponents(final String firstname, final String lastname, final String number) { + String name = ""; //$NON-NLS-1$ + if (firstname != null) { + name += firstname.trim(); + } + + if (lastname != null) { + if (name.length() > 0) { + name += " "; //$NON-NLS-1$ + } + name += lastname.trim(); + } + + return PBXFactory.getActivePBX().buildCallerID(number, name); + } + + /** + * Formats and returns the caller ID in an asterisk specific format suitable + * for passing to the likes of the originate action. The format is: name + * + * + * @return a formatted clid. + */ + public String formatted() { + String callerID = ""; //$NON-NLS-1$ + if (this.name != null) { + callerID += this.name; + } + if (this.number != null) { + if (callerID.length() > 1) { + callerID += " "; //$NON-NLS-1$ + } + callerID += "<" + this.number + ">"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return callerID; + } + + @Override + public void setHideCallerID(final boolean hide) { + this.hideCallerID = hide; + + } + + @Override + public boolean isHideCallerID() { + return this.hideCallerID; + } + + @Override + public String toString() { + return this.formatted(); + } + + @Override + public boolean isUnknown() { + return (this.number.length() == 0) || (this.number.compareToIgnoreCase("unknown") == 0); //$NON-NLS-1$ + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/asterisk/DurationRoomOwner.java b/src/main/java/org/asteriskjava/pbx/internal/asterisk/DurationRoomOwner.java new file mode 100644 index 000000000..64cb11102 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/DurationRoomOwner.java @@ -0,0 +1,23 @@ +package org.asteriskjava.pbx.internal.asterisk; + +import java.util.concurrent.TimeUnit; + +public class DurationRoomOwner implements RoomOwner { + + long end = System.currentTimeMillis(); + + public DurationRoomOwner(long duration, TimeUnit units) { + end = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(duration, units); + } + + @Override + public boolean isRoomStillRequired() { + return System.currentTimeMillis() < end; + } + + @Override + public void setRoom(MeetmeRoom meetmeRoom) { + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoom.java b/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoom.java new file mode 100644 index 000000000..f01856574 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoom.java @@ -0,0 +1,191 @@ +package org.asteriskjava.pbx.internal.asterisk; + +import org.asteriskjava.lock.Lockable; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.LinkedList; + +/* + * This class tracks the status, channel names and number of participants in + * a meetme room. The hangup function will hangup all known participants in + * this meetme room. + */ +public class MeetmeRoom extends Lockable { + /** + * The asterisk room number. This will be value offset from the Meetme Base. + * e.g. if the base is 3750 and this is the third allocated room, then the + * roomNumber will equal 3753. + */ + private final int roomNumber; + + private static final Log logger = LogFactory.getLog(MeetmeRoom.class); + + LinkedList channels = new LinkedList<>(); + + private int channelCount = 0; + + private boolean active = false; + + private boolean forceClose = false; + + private Long lastUpdated = null; + + private RoomOwner owner = null; + + public MeetmeRoom(final int number) { + this.roomNumber = number; + } + + /* + * returns true if the channel was added to the list of channels in this + * meetme. if the channel is already in the meetme, returns false + */ + public boolean addChannel(final Channel channel) { + try (LockCloser closer = this.withLock()) { + boolean newChannel = false; + if (!this.channels.contains(channel)) { + this.channels.add(channel); + this.channelCount++; + newChannel = true; + } else + MeetmeRoom.logger.error("rejecting " + channel + " already in meetme."); //$NON-NLS-1$ //$NON-NLS-2$ + return newChannel; + } + } + + public int getChannelCount() { + try (LockCloser closer = this.withLock()) { + return this.channelCount; + } + } + + public Channel[] getChannels() { + try (LockCloser closer = this.withLock()) { + final Channel list[] = new Channel[this.channels.size()]; + + int cnt = 0; + for (final Channel channel : this.channels) { + list[cnt++] = channel; + } + return list; + } + } + + public boolean getForceClose() { + return this.forceClose; + } + + public Long getLastUpdated() { + return this.lastUpdated; + } + + public String getRoomNumber() { + return ("" + this.roomNumber); //$NON-NLS-1$ + } + + /** + * returns true if the meetme room is active, false if it is available + * + * @return + */ + public boolean isActive() { + return this.active; + } + + public void removeChannel(final Channel channel) { + try (LockCloser closer = this.withLock()) { + final boolean channelCountInSync = this.channelCount == this.channels.size(); + final boolean removed = this.channels.remove(channel); + + if (!removed) { + MeetmeRoom.logger.warn("An attempt to remove an non-existing channel " + channel + " from Meetme Room " //$NON-NLS-1$ //$NON-NLS-2$ + + this.getRoomNumber()); + } + + if (channelCountInSync && removed) { + this.channelCount--; + } + + // If the channel count is not insync then we decrement the channel + // count even if the remove was for a non-existent channel. + // We do this as if the channel count is out of sync it means that + // we + // have polled asterisk (usually during startup) + // and our local count was out of sync with asterisk. Asterisk is + // the + // definitive source. If we then get a remove + // channel then its probably a channel that asterisk knows about but + // which we don't know about. + // In that case our channelCount will also have come from asterisk + // so + // decrementing it keeps us in sync with asterisk + // and eventually we will get back in sync (hopefully). + if (!channelCountInSync && removed) { + this.channelCount--; + } + + if ((this.channels.size() < 2) && (this.channels.size() > 0)) { + if (!this.channels.get(0).isLocal()) { + logger.warn("One channel left in the meet me room " + this.channels.get(0) + " room " + this.roomNumber); //$NON-NLS-1$ + } + } + } + + } + + public void setActive() { + this.active = true; + } + + public void setForceClose(final boolean canClose) { + this.forceClose = canClose; + } + + public void setInactive() { + this.active = false; + this.channels.clear(); + this.forceClose = false; + this.lastUpdated = null; + this.owner = null; + + } + + public void setLastUpdated() { + this.lastUpdated = System.currentTimeMillis(); + } + + /** + * This method should only be called if asterisk is reporting a channel + * count for this meetme room which does not match our local channel count. + * This could happen if it was restarted whilst a call was active. + * + * @param channelCount + */ + public void resetChannelCount(final int resetChannelCount) { + this.channelCount = resetChannelCount; + + } + + public RoomOwner getOwner() { + return owner; + } + + public void setOwner(RoomOwner newOwner) { + owner = newOwner; + owner.setRoom(this); + setActive(); + } + + public void removeOwner(RoomOwner toRemove) { + if (owner == toRemove || owner == null) { + owner = null; + } else { + logger.error( + "Tring to remove the owner, but it's not the current owner. Owner=" + owner + " caller=" + toRemove); + } + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoomControl.java b/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoomControl.java new file mode 100644 index 000000000..a6d7970a4 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoomControl.java @@ -0,0 +1,348 @@ +package org.asteriskjava.pbx.internal.asterisk; + +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.live.ManagerCommunicationException; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.asterisk.wrap.actions.CommandAction; +import org.asteriskjava.pbx.asterisk.wrap.actions.ConfbridgeListAction; +import org.asteriskjava.pbx.asterisk.wrap.events.*; +import org.asteriskjava.pbx.asterisk.wrap.response.CommandResponse; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.core.CoherentManagerEventListener; +import org.asteriskjava.pbx.internal.managerAPI.EventListenerBaseClass; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicReference; + +public class MeetmeRoomControl extends EventListenerBaseClass implements CoherentManagerEventListener { + /* + * listens for a channel entering or leaving meetme rooms. when there is + * only 1 channel left in a room it sets it as inactive .It will not set to + * inactive unless okToKill is set to true. It is set to false by + * default.Also manages the available room list. + */ + + private static final Log logger = LogFactory.getLog(MeetmeRoomControl.class); + + private Integer meetmeBaseAddress; + + private MeetmeRoom rooms[]; + + private int roomCount; + + private boolean meetmeInstalled = false; + + private final static AtomicReference self = new AtomicReference<>(); + + synchronized public static void init(PBX pbx, final int roomCount) throws NoMeetmeException { + if (MeetmeRoomControl.self.get() != null) { + logger.warn("The MeetmeRoomControl has already been initialised."); //$NON-NLS-1$ + } else { + MeetmeRoomControl.self.set(new MeetmeRoomControl(pbx, roomCount)); + } + } + + public static MeetmeRoomControl getInstance() { + if (MeetmeRoomControl.self.get() == null) { + throw new IllegalStateException( + "The MeetmeRoomControl has not been initialised. Please call MeetmeRoomControl.init()."); //$NON-NLS-1$ + } + + return MeetmeRoomControl.self.get(); + + } + + private MeetmeRoomControl(PBX pbx, final int roomCount) throws NoMeetmeException { + super("MeetmeRoomControl", pbx); //$NON-NLS-1$ + this.roomCount = roomCount; + final AsteriskSettings settings = PBXFactory.getActiveProfile(); + this.meetmeBaseAddress = settings.getMeetmeBaseAddress(); + this.rooms = new MeetmeRoom[roomCount]; + this.configure((AsteriskPBX) pbx); + + this.startListener(); + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + required.add(MeetMeJoinEvent.class); + required.add(MeetMeLeaveEvent.class); + + return required; + } + + /* + * returns the next available meetme room, or null if no rooms are + * available. + */ + public MeetmeRoom findAvailableRoom(RoomOwner newOwner) { + try (LockCloser closer = this.withLock()) { + int count = 0; + for (final MeetmeRoom room : this.rooms) { + if (MeetmeRoomControl.logger.isDebugEnabled()) { + MeetmeRoomControl.logger.debug("room " + room.getRoomNumber() + " count " + count); + } + if (room.getOwner() == null || !room.getOwner().isRoomStillRequired()) { + /* + * new code to attempt to recover uncleared meetme rooms + * safely + */ + try { + final Long lastUpdated = room.getLastUpdated(); + final long now = System.currentTimeMillis(); + if (lastUpdated != null) { + final long elapsedTime = now - lastUpdated; + MeetmeRoomControl.logger.error( + "room: " + room.getRoomNumber() + " count: " + count + " elapsed: " + elapsedTime); + if ((elapsedTime > 1800000) && (room.getChannelCount() < 2)) { + MeetmeRoomControl.logger.error("clearing room"); //$NON-NLS-1$ + room.setInactive(); + } + } + } catch (final Exception e) { + /* + * attempt to make this new change safe + */ + MeetmeRoomControl.logger.error(e, e); + } + + if (room.getChannelCount() == 0) { + room.setInactive(); + room.setOwner(newOwner); + MeetmeRoomControl.logger.info("Returning available room " + room.getRoomNumber()); + return room; + } + + } else { + logger.warn("Meetme " + room.getRoomNumber() + " is still in use by " + room.getOwner()); + } + count++; + } + MeetmeRoomControl.logger.error("no more available rooms"); + return null; + } + } + + /** + * Returns the MeetmeRoom for the given room number. The room number will be + * an integer value offset from the meetme base address. + * + * @param roomNumber the meetme room number + * @return + */ + private MeetmeRoom findMeetmeRoom(final String roomNumber) { + try (LockCloser closer = this.withLock()) { + MeetmeRoom foundRoom = null; + for (final MeetmeRoom room : this.rooms) { + if (room.getRoomNumber().compareToIgnoreCase(roomNumber) == 0) { + foundRoom = room; + break; + } + } + return foundRoom; + } + + } + + MeetmeRoom getRoom(final int room) { + try (LockCloser closer = this.withLock()) { + return this.rooms[room]; + } + } + + @Override + public void onManagerEvent(final ManagerEvent event) { + MeetmeRoom room; + if (event instanceof MeetMeJoinEvent) { + final MeetMeJoinEvent evt = (MeetMeJoinEvent) event; + room = this.findMeetmeRoom(evt.getMeetMe()); + final Channel channel = evt.getChannel(); + if (room != null) { + if (room.addChannel(channel)) { + MeetmeRoomControl.logger.debug(channel + " has joined the conference " //$NON-NLS-1$ + + room.getRoomNumber() + " channelCount " + (room.getChannelCount())); //$NON-NLS-1$ + room.setLastUpdated(); + } + } + } + if (event instanceof MeetMeLeaveEvent) { + final MeetMeLeaveEvent evt = (MeetMeLeaveEvent) event; + room = this.findMeetmeRoom(evt.getMeetMe()); + final Channel channel = evt.getChannel(); + if (room != null) { + // ignore local dummy channels// && + // !channel.toUpperCase().startsWith("LOCAL/")) { + + if (MeetmeRoomControl.logger.isDebugEnabled()) { + MeetmeRoomControl.logger.debug(channel + " has left the conference " //$NON-NLS-1$ + + room.getRoomNumber() + " channel count " + (room.getChannelCount())); //$NON-NLS-1$ + } + room.removeChannel(channel); + room.setLastUpdated(); + if (room.getChannelCount() < 2 && room.getForceClose()) { + this.hangupChannels(room); + room.setInactive(); + } + + if (room.getChannelCount() < 1) { + room.setInactive(); + } + } + } + } + + public void hangupChannels(final MeetmeRoom room) { + + final Channel Channels[] = room.getChannels(); + if (room.isActive()) { + PBX pbx = PBXFactory.getActivePBX(); + + for (final Channel channel : Channels) { + room.removeChannel(channel); + + try { + logger.warn("Hanging up"); + pbx.hangup(channel); + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { + logger.error(e, e); + + } + } + } + } + + private void configure(AsteriskPBX pbx) throws NoMeetmeException { + final int base = this.meetmeBaseAddress; + for (int r = 0; r < this.roomCount; r++) { + this.rooms[r] = new MeetmeRoom(r + base); + } + + try { + String command; + if (pbx.getVersion().isAtLeast(AsteriskVersion.ASTERISK_13)) { + command = "ConfBridge list"; //$NON-NLS-1$ + ConfbridgeListAction action = new ConfbridgeListAction(); + final ResponseEvents response = pbx.sendEventGeneratingAction(action, 3000); + Map roomChannelCount = new HashMap<>(); + for (ResponseEvent event : response.getEvents()) { + + ConfbridgeListEvent e = (ConfbridgeListEvent) event; + Integer current = roomChannelCount.get(e.getConference()); + if (current == null) { + roomChannelCount.put(e.getConference(), 1); + } else { + roomChannelCount.put(e.getConference(), current + 1); + } + } + for (Entry entry : roomChannelCount.entrySet()) { + setRoomCount(entry.getKey(), entry.getValue(), Integer.parseInt(entry.getKey())); + + } + this.meetmeInstalled = true; + + } else { + if (pbx.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) { + command = "meetme list"; //$NON-NLS-1$ + } else { + command = "meetme"; //$NON-NLS-1$ + } + final CommandAction commandAction = new CommandAction(command); + final ManagerResponse response = pbx.sendAction(commandAction, 3000); + if (!(response instanceof CommandResponse)) { + throw new ManagerCommunicationException(response.getMessage(), null); + } + + final CommandResponse commandResponse = (CommandResponse) response; + MeetmeRoomControl.logger.debug("parsing active meetme rooms"); //$NON-NLS-1$ + for (final String line : commandResponse.getResult()) { + this.parseMeetme(line); + this.meetmeInstalled = true; + MeetmeRoomControl.logger.debug(line); + } + } + } catch (final NoMeetmeException e) { + throw e; + } catch (final Exception e) { + MeetmeRoomControl.logger.error(e, e); + throw new NoMeetmeException(e.getLocalizedMessage()); + } + } + + private void parseMeetme(final String line) throws NoMeetmeException { + try (LockCloser closer = this.withLock()) { + if (line != null) { + if (line.toLowerCase().startsWith("no such command 'meetme'")) //$NON-NLS-1$ + { + throw new NoMeetmeException("Asterisk is not configured correctly! Please enable the MeetMe app"); //$NON-NLS-1$ + } + + if ((!line.toLowerCase().startsWith("no active meetme conferences.")) //$NON-NLS-1$ + && (!line.toLowerCase().startsWith("conf num")) //$NON-NLS-1$ + && (!line.toLowerCase().startsWith("* total number")) //$NON-NLS-1$ + && (!line.toLowerCase().startsWith("no such conference")) //$NON-NLS-1$ + && (!line.toLowerCase().startsWith("no such command 'meetme")) //$NON-NLS-1$ + ) { + // Update the stats on each meetme + final String roomNumber = line.substring(0, 10).trim(); + final String tmp = line.substring(11, 25).trim(); + final int channelCount = Integer.parseInt(tmp); + + final int roomNo = Integer.valueOf(roomNumber); + setRoomCount(roomNumber, channelCount, roomNo); + } + } + } + } + + private void setRoomCount(final String roomNumber, final int channelCount, final int roomNo) { + Integer base = this.meetmeBaseAddress; + // First check if its one of our rooms. + if ((roomNo >= base) && (roomNo < (base + this.roomCount))) { + final MeetmeRoom room = this.findMeetmeRoom(roomNumber); + if (room != null) { + if (room.getChannelCount() != channelCount) { + /* + * After a restart there may have been meetme rooms left up + * and running with live calls. We need to identify any + * active rooms so we don't accidentally re-use an active + * room which would result in a crossed channel. + */ + MeetmeRoomControl.logger.warn("Room number: " + room.getRoomNumber() //$NON-NLS-1$ + + " has a server side channel count = " + channelCount //$NON-NLS-1$ + + " when the channel count for that room is: " + room.getChannelCount() //$NON-NLS-1$ + + " the server side channel count will be reset."); //$NON-NLS-1$ + } + room.resetChannelCount(channelCount); + room.setActive(); + } + // else "Found roomNumber:" + roomNumber + " but it was not + // in the list of rooms managed by MeetmeRoomControl."); + // //$NON-NLS-1$ //$NON-NLS-2$ + + } + } + + public void stop() { + this.close(); + + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + public boolean isMeetmeInstalled() { + return this.meetmeInstalled; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/asterisk/NoMeetmeException.java b/src/main/java/org/asteriskjava/pbx/internal/asterisk/NoMeetmeException.java new file mode 100644 index 000000000..7b83e8b20 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/NoMeetmeException.java @@ -0,0 +1,10 @@ +package org.asteriskjava.pbx.internal.asterisk; + +public class NoMeetmeException extends Exception { + private static final long serialVersionUID = 1L; + + public NoMeetmeException(final String message) { + super(message); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/asterisk/RoomOwner.java b/src/main/java/org/asteriskjava/pbx/internal/asterisk/RoomOwner.java new file mode 100644 index 000000000..f1f614edb --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/RoomOwner.java @@ -0,0 +1,20 @@ +package org.asteriskjava.pbx.internal.asterisk; + +public interface RoomOwner { + /** + * implementations of this method should NOT take locks and should return + * quickly. This is used as an indication that the room (even though empty) + * is still required by the owner + * + * @return true if the meetme room is still required + */ + boolean isRoomStillRequired(); + + /** + * this can be usefull to null the reference to the Owner when the room is + * nolong owned + * + * @param meetmeRoom + */ + void setRoom(MeetmeRoom meetmeRoom); +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/ActiveCallListener.java b/src/main/java/org/asteriskjava/pbx/internal/core/ActiveCallListener.java new file mode 100644 index 000000000..639aa12bd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/ActiveCallListener.java @@ -0,0 +1,15 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.Call; + +/** + * Used to notify a listener that the status of a call has changed. For instance + * the call may have just been parked. + * + * @author bsutton + */ +public interface ActiveCallListener { + + void callStatusChanged(Call call, boolean isHidden); + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/AsteriskPBX.java b/src/main/java/org/asteriskjava/pbx/internal/core/AsteriskPBX.java new file mode 100644 index 000000000..9147f06e7 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/AsteriskPBX.java @@ -0,0 +1,842 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.manager.AuthenticationFailedException; +import org.asteriskjava.manager.EventTimeoutException; +import org.asteriskjava.manager.ManagerConnectionState; +import org.asteriskjava.manager.TimeoutException; +import org.asteriskjava.manager.event.AbstractChannelEvent; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.Call.OperandChannel; +import org.asteriskjava.pbx.activities.*; +import org.asteriskjava.pbx.agi.AgiChannelActivityHangup; +import org.asteriskjava.pbx.agi.AgiChannelActivityHold; +import org.asteriskjava.pbx.asterisk.wrap.actions.*; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.ResponseEvents; +import org.asteriskjava.pbx.asterisk.wrap.response.CommandResponse; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.pbx.internal.activity.*; +import org.asteriskjava.pbx.internal.asterisk.CallerIDImpl; +import org.asteriskjava.pbx.internal.asterisk.MeetmeRoom; +import org.asteriskjava.pbx.internal.asterisk.MeetmeRoomControl; +import org.asteriskjava.pbx.internal.asterisk.RoomOwner; +import org.asteriskjava.pbx.internal.managerAPI.RedirectCall; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +public enum AsteriskPBX implements PBX, ChannelHangupListener { + + SELF; + + public static final String ACTIVITY_AGI = "activityAgi"; + private final Log logger = LogFactory.getLog(getClass()); + private boolean muteSupported; + private boolean bridgeSupport; + private boolean expectRenameEvents; + + private static final int MAX_MEETME_ROOMS = 500; + + private LiveChannelManager liveChannels; + + AsteriskPBX() { + try { + CoherentManagerConnection.init(); + + this.muteSupported = CoherentManagerConnection.getInstance().isMuteAudioSupported(); + this.bridgeSupport = CoherentManagerConnection.getInstance().isBridgeSupported(); + expectRenameEvents = CoherentManagerConnection.getInstance().expectRenameEvents(); + liveChannels = new LiveChannelManager(); + + MeetmeRoomControl.init(this, AsteriskPBX.MAX_MEETME_ROOMS); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public void performPostCreationTasks() { + liveChannels.performPostCreationTasks(); + } + + /** + * Call this method when shutting down the PBX interface to allow it to + * cleanup. + */ + @Override + public void shutdown() { + MeetmeRoomControl.getInstance().stop(); + CoherentManagerConnection.getInstance().shutDown(); + } + + @Override + public boolean isBridgeSupported() { + return this.bridgeSupport; + } + + @Override + public BlindTransferActivity blindTransfer(Call call, Call.OperandChannel channelToTransfer, EndPoint transferTarget, + CallerID toCallerID, boolean autoAnswer, long timeout, String dialOptions) { + final CompletionAdaptor completion = new CompletionAdaptor<>(); + + final BlindTransferActivityImpl transfer = new BlindTransferActivityImpl(call, channelToTransfer, transferTarget, + toCallerID, autoAnswer, timeout, completion, dialOptions); + + completion.waitForCompletion(timeout + 2, TimeUnit.SECONDS); + + return transfer; + + } + + @Override + public void blindTransfer(Call call, Call.OperandChannel channelToTransfer, EndPoint transferTarget, CallerID toCallerID, + boolean autoAnswer, long timeout, ActivityCallback listener, String dialOptions) { + new BlindTransferActivityImpl(call, channelToTransfer, transferTarget, toCallerID, autoAnswer, timeout, listener, + dialOptions); + + } + + public BlindTransferActivity blindTransfer(Channel agentChannel, EndPoint transferTarget, CallerID toCallerID, + boolean autoAnswer, int timeout, ActivityCallback iCallback, String dialOptions) + throws PBXException { + return new BlindTransferActivityImpl(agentChannel, transferTarget, toCallerID, autoAnswer, timeout, iCallback, + dialOptions); + + } + + /** + * Utility method to bridge two channels + * + * @param lhsChannel + * @param rhsChannel + * @param direction + * @throws PBXException + */ + public BridgeActivity bridge(final Channel lhsChannel, final Channel rhsChannel) throws PBXException { + final CompletionAdaptor completion = new CompletionAdaptor<>(); + + final BridgeActivityImpl bridge = new BridgeActivityImpl(lhsChannel, rhsChannel, completion); + + completion.waitForCompletion(10, TimeUnit.SECONDS); + + return bridge; + + } + + @Override + public void split(final Call callToSplit) throws PBXException { + final CompletionAdaptor completion = new CompletionAdaptor<>(); + + new SplitActivityImpl(callToSplit, completion); + + completion.waitForCompletion(10, TimeUnit.SECONDS); + + } + + @Override + public SplitActivity split(final Call callToSplit, final ActivityCallback listener) { + + return new SplitActivityImpl(callToSplit, listener); + } + + @Override + public RedirectToActivity redirectToActivity(final Channel channel, final ActivityCallback listener) { + + return new RedirectToActivityImpl(channel, listener); + } + + /** + * Joins two calls not returning until the join completes. The join will + * complete almost immediately as it is a simple bridging of two active + * channels. Each call must only have one active channel + */ + @Override + public JoinActivity join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel acceptingOperand, + CallDirection direction) { + final CompletionAdaptor completion = new CompletionAdaptor<>(); + + final JoinActivityImpl join = new JoinActivityImpl(lhs, originatingOperand, rhs, acceptingOperand, direction, + completion); + + completion.waitForCompletion(10, TimeUnit.SECONDS); + + return join; + + } + + /** + * Joins two calls not returning until the join completes. The join will + * complete almost immediately as it is a simple bridging of two active + * channels. Each call must only have one active channel + */ + @Override + public void join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel acceptingOperand, + CallDirection direction, ActivityCallback listener) { + new JoinActivityImpl(lhs, originatingOperand, rhs, acceptingOperand, direction, listener); + + } + + @Override + public void conference(final Channel channelOne, final Channel channelTwo, final Channel channelThree) { + // TODO Auto-generated method stub + + } + + @Override + public void conference(final Channel channelOne, final Channel channelTwo, final Channel channelThree, + final ActivityCallback callback) { + // TODO Auto-generated method stub + + } + + @Override + public DialActivity dial(final EndPoint from, final CallerID fromCallerID, final EndPoint to, final CallerID toCallerID, + String dialOptions) { + final CompletionAdaptor completion = new CompletionAdaptor<>(); + + final DialActivityImpl dialer = new DialActivityImpl(from, to, toCallerID, false, completion, null, dialOptions); + + completion.waitForCompletion(3, TimeUnit.MINUTES); + + return dialer; + } + + public DialLocalToAgiActivity dialLocalToAgi(final EndPoint from, final CallerID fromCallerID, + ActivityCallback callback, Map channelVarsToSet) { + return new DialLocalToAgiActivity(from, fromCallerID, callback, channelVarsToSet); + } + + public DialActivity dial(final EndPoint from, final CallerID fromCallerID, final EndPoint to, final CallerID toCallerID, + final ActivityCallback callback, Map channelVarsToSet, String dialOptions) { + final DialActivityImpl dialer = new DialActivityImpl(from, to, toCallerID, false, callback, channelVarsToSet, + dialOptions); + return dialer; + } + + @Override + public void dial(final EndPoint from, final CallerID fromCallerID, final EndPoint to, final CallerID toCallerID, + final ActivityCallback callback, String dialOptions) { + new DialActivityImpl(from, to, toCallerID, false, callback, null, dialOptions); + + } + + /** + * Convenience method to hangup the call without having to extract the + * channel yourself. + */ + public void hangup(Call call) throws PBXException { + this.hangup(call.getOriginatingParty()); + } + + @Override + public void hangup(final Channel channel) throws PBXException { + if (channel.isLive()) { + logger.info("Sending hangup action for channel: " + channel); //$NON-NLS-1$ + + PBX pbx = PBXFactory.getActivePBX(); + if (!pbx.waitForChannelToQuiescent(channel, 3000)) + throw new PBXException("Channel: " + channel + " cannot be retrieved as it is still in transition."); + + final HangupAction hangup = new HangupAction(channel); + try { + channel.setCurrentActivityAction(new AgiChannelActivityHangup()); + CoherentManagerConnection.sendAction(hangup, 1000); + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { + logger.error(e, e); + throw new PBXException(e); + } + } else + logger.debug("Suppressed hangup for " + channel + " as it was already hungup"); //$NON-NLS-1$ //$NON-NLS-2$ + + } + + @Override + public void hangup(final Channel channel, final ActivityCallback callback) { + throw new UnsupportedOperationException("Not yet implemented."); //$NON-NLS-1$ + } + + @Override + public HoldActivity hold(final Channel channel) { + final CompletionAdaptor completion = new CompletionAdaptor<>(); + + HoldActivity activity = null; + try { + activity = new HoldActivityImpl(channel, completion); + completion.waitForCompletion(10, TimeUnit.SECONDS); + + } catch (final Exception e) { + logger.error(e, e); + + } + return activity; + } + + @Override + public boolean isMuteSupported() { + return this.muteSupported; + } + + @Override + public ParkActivity park(final Call call, final Channel parkChannel) { + final CompletionAdaptor completion = new CompletionAdaptor<>(); + + final ParkActivity activity = new ParkActivityImpl(call, parkChannel, completion); + parkChannel.setParked(true); + + completion.waitForCompletion(10, TimeUnit.SECONDS); + return activity; + } + + @Override + public void park(final Call call, final Channel parkChannel, final ActivityCallback callback) { + new ParkActivityImpl(call, parkChannel, callback); + + } + + @Override + public void sendDTMF(final Channel channel, final DTMFTone tone) throws PBXException { + try { + if (!waitForChannelToQuiescent(channel, 3000)) + throw new PBXException("Channel: " + channel + " cannot play dtmf as it is still in transition."); + + CoherentManagerConnection.sendAction(new PlayDtmfAction(channel, tone), 1000); + } catch (final Exception e) { + logger.error(e, e); + throw new PBXException(e); + } + } + + @Override + public void sendDTMF(final Channel channel, final DTMFTone tone, final ActivityCallback callback) { + // TODO Auto-generated method stub + + } + + @Override + public void transferToMusicOnHold(final Channel channel) throws PBXException { + final RedirectCall transfer = new RedirectCall(); + transfer.redirect(channel, new AgiChannelActivityHold()); + } + + public String getManagementContext() { + final AsteriskSettings settings = PBXFactory.getActiveProfile(); + return settings.getManagementContext(); + } + + @Override + public Channel getChannelByEndPoint(final EndPoint endPoint) { + return this.liveChannels.getChannelByEndPoint(endPoint); + } + + @Override + public void channelHangup(Channel channel, Integer cause, String causeText) { + this.liveChannels.remove((ChannelProxy) channel); + } + + public DialPlanExtension getExtensionPark() { + final AsteriskSettings settings = PBXFactory.getActiveProfile(); + return this.buildDialPlanExtension(settings.getExtensionPark()); + } + + @Override + public EndPoint getExtensionAgi() { + final AsteriskSettings settings = PBXFactory.getActiveProfile(); + return this.buildDialPlanExtension(settings.getAgiExtension()); + } + + /** + * Builds an end point from a fully qualified end point name. If the + * endpoint name doesn't have a tech then it is considered invalid and null + * is returned. + */ + + @Override + public EndPoint buildEndPoint(final String fullyQualifiedEndPoint) { + EndPoint endPoint = null; + try { + endPoint = new EndPointImpl(fullyQualifiedEndPoint); + } catch (final IllegalArgumentException e) { + logger.warn(e, e); + } + return endPoint; + } + + /** + * Builds an end point from an end point name. If the endpoint name doesn't + * have a tech specified then the defaultTech is used. + */ + @Override + public EndPoint buildEndPoint(final TechType defaultTech, final String endPointName) { + EndPoint endPoint = null; + try { + if (endPointName == null || endPointName.trim().length() == 0) + endPoint = new EndPointImpl(); + else + endPoint = new EndPointImpl(defaultTech, endPointName); + } catch (final IllegalArgumentException e) { + logger.error(e, e); + } + return endPoint; + + } + + @Override + public EndPoint buildEndPoint(final TechType defaultTech, final Trunk trunk, final String endPointName) { + return new EndPointImpl(defaultTech, trunk, endPointName); + + } + + /** + * Builds an end point from an end point name. If the endpoint name doesn't + * have a tech specified then the defaultTech is used. + */ + public DialPlanExtension buildDialPlanExtension(final String extension) { + DialPlanExtension dialPlan = null; + try { + dialPlan = new DialPlanExtension(extension); + } catch (final IllegalArgumentException e) { + logger.error(e, e); + } + return dialPlan; + + } + + @Override + public CallerID buildCallerID(final String number, final String name) { + return new CallerIDImpl(number, name); + } + + /** + * Convenience method to build a call id from an event. + * + * @param event + */ + public CallerID buildCallerID(final AbstractChannelEvent event) { + final String number = event.getCallerIdNum(); + final String name = event.getCallerIdName(); + return this.buildCallerID(number, name); + } + + public Channel registerChannel(final String channelName, final String uniqueIdParam) throws InvalidChannelName { + String uniqueID = uniqueIdParam; + if (uniqueIdParam == null || uniqueIdParam.length() == 0) { + uniqueID = ChannelImpl.UNKNOWN_UNIQUE_ID; + } + + if (channelName == null || channelName.trim().length() == 0) { + throw new IllegalArgumentException("Channel name must not be empty"); + } + + Channel proxy = findChannel(cleanChannelName(channelName), null); + if (proxy == null) { + logger.info("Couldn't find the channel " + channelName + ", creating it"); + proxy = internalRegisterChannel(channelName, uniqueID); + } else { + if (uniqueID != null && !uniqueID.equals(proxy.getUniqueId())) { + logger.info( + "Found the channel(" + proxy.getUniqueId() + "), but with a different uniqueId (" + uniqueID + ")"); + + } + } + liveChannels.sanityCheck(); + + return proxy; + } + + /** + * This method is not part of the public API.
      + *
      + * Use registerChannel instead calling this method with an incorrect or + * stale uniqueId will cause inconsistent behaviour. + * + * @param channelName + * @param uniqueID + * @return + * @throws InvalidChannelName + */ + public Channel internalRegisterChannel(final String channelName, final String uniqueID) throws InvalidChannelName { + ChannelProxy proxy = null; + try (LockCloser closer = this.liveChannels.withLock()) { + + String localUniqueID = (uniqueID == null ? ChannelImpl.UNKNOWN_UNIQUE_ID : uniqueID); + proxy = this.findChannel(cleanChannelName(channelName), localUniqueID); + if (proxy == null) { + proxy = new ChannelProxy(new ChannelImpl(channelName, localUniqueID)); + logger.debug("Creating new Channel Proxy " + proxy); + this.liveChannels.add(proxy); + proxy.addHangupListener(this); + } + } + return proxy; + } + + /** + * remove white space + * + * @param name + * @return + */ + private String cleanChannelName(final String name) { + String cleanedName = name.trim().toUpperCase(); + + return cleanedName; + } + + public Channel registerHangupChannel(String channel, String uniqueId) throws InvalidChannelName { + Channel newChannel = null; + try (LockCloser closer = this.liveChannels.withLock()) { + newChannel = this.findChannel(channel, uniqueId); + if (newChannel == null) { + // WE don't add this channel to the liveChannels as it is in the + // process + // of being hungup so we don't need to track it. + // If we tried to track it that would likely cause a problem + // as the livechannel manager would never be able to discard it + // as + // it relies on the hangup event which is being processed right + // now. + newChannel = new ChannelProxy(new ChannelImpl(channel, uniqueId)); + } + } + return newChannel; + } + + public ChannelProxy findChannel(final String channelName, final String uniqueID) { + return this.liveChannels.findChannel(channelName, uniqueID); + } + + public MeetmeRoom acquireMeetmeRoom(RoomOwner owner) { + return MeetmeRoomControl.getInstance().findAvailableRoom(owner); + } + + public void addListener(FilteredManagerListener listener) { + CoherentManagerConnection connection = CoherentManagerConnection.getInstance(); + connection.addListener(listener); + } + + public void removeListener(FilteredManagerListener listener) { + CoherentManagerConnection connection = CoherentManagerConnection.getInstance(); + connection.removeListener(listener); + } + + /** + * sends an action with a default timeout of 30 seconds. + * + * @param theAction + * @return + * @throws IllegalArgumentException + * @throws IllegalStateException + * @throws IOException + * @throws TimeoutException + */ + public ManagerResponse sendAction(ManagerAction theAction) + throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { + return CoherentManagerConnection.sendAction(theAction, 30000); + } + + public ManagerResponse sendAction(ManagerAction theAction, int timeout) + throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { + return CoherentManagerConnection.sendAction(theAction, timeout); + } + + public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) + throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException { + ResponseEvents events = CoherentManagerConnection.sendEventGeneratingAction(action); + return events; + + } + + public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, int timeout) + throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException { + return CoherentManagerConnection.sendEventGeneratingAction(action, timeout); + + } + + public void setVariable(Channel channel, String name, String value) throws PBXException { + CoherentManagerConnection.getInstance().setVariable(channel, name, value); + + } + + public void sendActionNoWait(final ManagerAction action) { + CoherentManagerConnection.sendActionNoWait(action); + + } + + public String getVariable(Channel channel, String name) { + return CoherentManagerConnection.getInstance().getVariable(channel, name); + } + + public AsteriskVersion getVersion() { + return CoherentManagerConnection.getInstance().getVersion(); + } + + public boolean isConnected() { + return ((CoherentManagerConnection.managerConnection != null) + && (CoherentManagerConnection.managerConnection.getState() == ManagerConnectionState.CONNECTED)); + } + + public boolean isMeetmeInstalled() { + return MeetmeRoomControl.getInstance().isMeetmeInstalled(); + } + + @Override + public boolean isChannel(String channelName) { + boolean isChannel = false; + try { + internalRegisterChannel(channelName, ChannelImpl.UNKNOWN_UNIQUE_ID); + isChannel = true; + } catch (InvalidChannelName e) { + // if we get here then its not avalid channel name. + } + return isChannel; + } + + static public String getSIPADDHeader(final boolean inherit, final boolean targetIsSIP) { + String sipHeader = "SIPADDHEADER"; //$NON-NLS-1$ + if (!targetIsSIP || inherit) { + sipHeader = "__" + sipHeader; //$NON-NLS-1$ + } + return sipHeader; + } + + /** + * Waits for a channel to become quiescent. A Quiescent channel is one that + * is not in the middle of a name change (e.g. masquerade) + * + * @param channel + * @param timeout the time to wait (in milliseconds) for the channel to + * become quiescent. + */ + @Override + public boolean waitForChannelsToQuiescent(List channels, long timeout) { + long elapsed = 0; + while (elapsed < timeout && !channelsAreQuiesent(channels)) { + try { + Thread.sleep(200); + } catch (InterruptedException e) { + logger.error(e, e); + } + logger.info("Waiting for channesl to Quiescent"); + elapsed += 200; + } + + if (elapsed > timeout / 2) { + logger.warn("Took " + elapsed + "ms for channels to Quiescent"); + } + if (elapsed >= timeout) { + logger.error("Channels didn't Quiescent"); + for (Channel channel : channels) { + logger.error(channel); + } + + } + return timeout > elapsed; + } + + private boolean channelsAreQuiesent(List channels) { + boolean ret = true; + for (Channel channel : channels) { + ret &= channel.isQuiescent(); + } + return ret; + } + + public boolean moveChannelToAgi(Channel channel) throws PBXException { + if (!waitForChannelToQuiescent(channel, 3000)) + throw new PBXException("Channel: " + channel + " cannot be transfered as it is still in transition."); + + boolean isInAgi = channel.isInAgi(); + if (!isInAgi) { + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + + channel.setCurrentActivityAction(new AgiChannelActivityHold()); + final RedirectAction redirect = new RedirectAction(channel, profile.getManagementContext(), getExtensionAgi(), + 1); + + logger.error("Issuing redirect on channel " + channel + " to move it to the agi"); + + try { + final ManagerResponse response = sendAction(redirect, 1000); + if ((response != null) && (response.getResponse().compareToIgnoreCase("success") == 0))//$NON-NLS-1$ + { + int limit = 50; + while (!channel.isInAgi() && limit-- > 0) { + Thread.sleep(100); + } + isInAgi = channel.isInAgi(); + if (!isInAgi) { + logger.error("Failed to move channel"); + } + } + + } catch (final Exception e) { + logger.error(e, e); + } + + } + return isInAgi; + + } + + public void moveChannelTo(Channel channel, String context, String exten, int prio) { + + DialPlanExtension ext = this.buildDialPlanExtension(exten); + + channel.setCurrentActivityAction(new AgiChannelActivityHold()); + final RedirectAction redirect = new RedirectAction(channel, context, ext, prio); + + try { + sendAction(redirect, 1000); + + } catch (final Exception e) { + logger.error(e, e); + } + + } + + @Override + public boolean waitForChannelToQuiescent(Channel channel, int timeout) { + List channels = new LinkedList<>(); + channels.add(channel); + return waitForChannelsToQuiescent(channels, timeout); + } + + public ChannelProxy getProxyById(String id) { + return liveChannels.findProxyById(id); + } + + public DialToAgiActivityImpl dialToAgi(EndPoint endPoint, CallerID callerID, AgiChannelActivityAction action, + ActivityCallback iCallback, Map channelVarsToSet) { + + final CompletionAdaptor completion = new CompletionAdaptor<>(); + + final DialToAgiActivityImpl dialer = new DialToAgiActivityImpl(endPoint, callerID, null, false, completion, + channelVarsToSet, action); + + dialer.startActivity(false); + + completion.waitForCompletion(3, TimeUnit.MINUTES); + + final ActivityStatusEnum status; + + if (dialer.isSuccess()) { + status = ActivityStatusEnum.SUCCESS; + } else { + status = ActivityStatusEnum.FAILURE; + } + + iCallback.progress(dialer, status, status.getDefaultMessage()); + + return dialer; + } + + public DialToAgiActivityImpl dialToAgiWithAbort(EndPoint endPoint, CallerID callerID, int timeout, + AgiChannelActivityAction action, ActivityCallback iCallback) { + + return new DialToAgiActivityImpl(endPoint, callerID, timeout, false, iCallback, null, action); + + } + + /** + * Creates the set of extensions required to test NJR during the + * installation. The context must already exist in the dialplan. + * + * @param profile + * @param dialContext + * @return success or failure + * @throws IllegalStateException + * @throws IOException + * @throws AuthenticationFailedException + * @throws TimeoutException + */ + public boolean createAgiEntryPoint() throws IOException, AuthenticationFailedException, TimeoutException { + + try { + + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + AsteriskSettings profile = PBXFactory.getActiveProfile(); + if (!checkDialplanExists(profile)) { + + String host = profile.getAgiHost(); + String agi = profile.getAgiExtension(); + pbx.addAsteriskExtension(agi, 1, + "AGI(agi://" + host + "/" + ACTIVITY_AGI + "), into " + profile.getManagementContext()); + pbx.addAsteriskExtension(agi, 2, "wait(0.5), into " + profile.getManagementContext()); + pbx.addAsteriskExtension(agi, 3, "goto(" + agi + ",1), into " + profile.getManagementContext()); + + return checkDialplanExists(profile); + } + return true; + } catch (Exception e) { + logger.error(e); + + return false; + } + + } + + public boolean checkDialplanExists(String dialPlan, String context) throws IOException, TimeoutException { + String command; + + if (getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) { + // TODO: Use ShowDialplanAction instead of CommandAction? + command = "dialplan show " + context; + } else { + command = "show dialplan " + context; + } + + CommandAction action = new CommandAction(command); + CommandResponse response = (CommandResponse) sendAction(action, 30000); + + return response.getResult().stream().anyMatch(line -> line.contains(dialPlan)); + } + + public boolean checkDialplanExists(AsteriskSettings profile) + throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { + return checkDialplanExists(ACTIVITY_AGI, profile.getManagementContext()); + + } + + public String addAsteriskExtension(String extNumber, int priority, String command) throws Exception { + String ext = "dialplan add extension " + extNumber + "," + priority + "," + command; + + CommandAction action = new CommandAction(ext); + CommandResponse response = (CommandResponse) sendAction(action, 30000); + + List line = response.getResult(); + String tmp = "Extension '" + extNumber + "," + priority + ","; + + if (line.stream().anyMatch(answer -> answer.substring(0, tmp.length()).compareToIgnoreCase(tmp) == 0)) { + return "OK"; + } + + throw new Exception("InitiateAction.AddExtentionFailed" + ext); + } + + @Override + public Trunk buildTrunk(final String trunk) { + return new Trunk() { + + @Override + public String getTrunkAsString() { + return trunk; + } + }; + } + + public List getChannelList() { + return liveChannels.getChannelList(); + } + + public boolean expectRenameEvents() { + return expectRenameEvents; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/CallEndedListener.java b/src/main/java/org/asteriskjava/pbx/internal/core/CallEndedListener.java new file mode 100644 index 000000000..7dfb9271a --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CallEndedListener.java @@ -0,0 +1,12 @@ +package org.asteriskjava.pbx.internal.core; + +/** + * Used to notify a listener that a Call (CallTracker) has ended. + *

      + * This generally means the last channel has hungup. + * + * @author bsutton + */ +public interface CallEndedListener { + void callEnded(CallTracker listener); +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/CallTracker.java b/src/main/java/org/asteriskjava/pbx/internal/core/CallTracker.java new file mode 100644 index 000000000..458b612c7 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CallTracker.java @@ -0,0 +1,176 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.lock.LockableList; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.ChannelHangupListener; +import org.asteriskjava.pbx.asterisk.wrap.events.ChannelState; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * This is a fairly simple class which is used by a Peer to track what calls are + * live for the given Peer. It should be noted that the Peer must keep track of + * all calls regardless of whether they are associated with NJR. The reason for + * this is that a Peer needs to track the status of the associated endpoint so + * that it can show if a handset is on a call. In this way the operator can tell + * if a person is busy even before they call them. Essentially all this calls + * does is track the set of channels associated with a call. + * + * @author bsutton + */ +public class CallTracker implements ChannelHangupListener { + private static final Log logger = LogFactory.getLog(CallTracker.class); + + /** + * The list of channels associated with this call. + */ + LockableList _associatedChannels = new LockableList<>(new ArrayList<>()); + + /** + * The state of this call. + */ + PeerState _state; + + private CallEndedListener listener; + + CallTracker(Peer peer, Channel initialChannel) { + this._associatedChannels.add(initialChannel); + initialChannel.addHangupListener(this); + this.listener = peer; + + } + + /** + * Used to merge two calls into a single call. This is required as during a + * masquerade a new channel is created an initially we will create a + * CallTracker for it. When the masquerade event finally turns up we will + * realise it belongs to an existing CallTracker and as such we need to + * merge the two CallTrackers. + * + * @param rhs + */ + void mergeCalls(CallTracker rhs) { + try (LockCloser closer = this._associatedChannels.withLock()) { + this._associatedChannels.addAll(rhs._associatedChannels); + // not certain this is necessary but lets just tidy up a bit. + rhs._associatedChannels.clear(); + } + } + + public PeerState getState() { + return this._state; + } + + /** + * @param s + */ + public void setState(final ChannelState channelState) { + this._state = PeerState.valueByChannelState(channelState); + } + + public int findChannel(Channel newChannel) { + int index = -1; + try (LockCloser closer = this._associatedChannels.withLock()) { + + for (int i = 0; i < this._associatedChannels.size(); i++) { + Channel channel = this._associatedChannels.get(i); + if (channel.isSame(newChannel)) { + index = i; + break; + } + } + } + + return index; + } + + /** + * Remove a channel from the call. + * + * @param channel + */ + public void remove(Channel channel) { + try (LockCloser closer = this._associatedChannels.withLock()) { + int index = findChannel(channel); + if (index != -1) { + if (logger.isDebugEnabled()) + logger.debug( + "CallTracker removing channel: " + this.toString() + " " + channel.getExtendedChannelName()); //$NON-NLS-1$ //$NON-NLS-2$ + + this._associatedChannels.remove(index); + } + } + + } + + public void startSweep() { + try (LockCloser closer = this._associatedChannels.withLock()) { + for (final Channel channel : this._associatedChannels) { + ((ChannelProxy) channel).getRealChannel().startSweep(); + } + } + } + + public void endSweep() { + final List toremove = new LinkedList<>(); + try (LockCloser closer = this._associatedChannels.withLock()) { + for (final Channel channel : this._associatedChannels) { + if (!((ChannelProxy) channel).getRealChannel().wasMarkedDuringSweep()) { + toremove.add(channel); + logger.warn("removing channel " + this.hashCode() + " " + channel.getChannelName());//$NON-NLS-1$ //$NON-NLS-2$ + } + } + + this._associatedChannels.removeAll(toremove); + } + + // Now tell each of the channels it has been hungup + for (final Channel channel : toremove) { + ((ChannelProxy) channel).getRealChannel().notifyHangupListeners(-1, + "Lingering channel probably due to missed hangup event"); + } + + } + + void dumpChannelList() { + if (logger.isDebugEnabled()) { + logger.debug("CallTracker: dump channellist:" + this); //$NON-NLS-1$ + try (LockCloser closer = this._associatedChannels.withLock()) { + for (final Channel channel : this._associatedChannels) { + logger.debug("--> " + channel.toString()); //$NON-NLS-1$ + } + } + } + } + + public boolean hasEnded() { + try (LockCloser closer = this._associatedChannels.withLock()) { + return this._associatedChannels.size() == 0; + } + } + + @Override + public void channelHangup(Channel channel, Integer cause, String causeText) { + remove(channel); + try (LockCloser closer = this._associatedChannels.withLock()) { + if (this._associatedChannels.size() == 0) { + this._state = PeerState.NOTSET; + notifyCallEndedListener(); + } + } + } + + private void notifyCallEndedListener() { + this.listener.callEnded(this); + } + + public String toString() { + return this.listener + " : " + this._state; //$NON-NLS-1$ + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/ChannelImpl.java b/src/main/java/org/asteriskjava/pbx/internal/core/ChannelImpl.java new file mode 100644 index 000000000..97a64a66b --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/ChannelImpl.java @@ -0,0 +1,786 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.concurrent.TimeUnit; + +/** + * TODO set the channel unique id when registering against an existing channel + * which doesn't have its unique id set.
      + *
      + * Create a single asterisk event source. All users of MyBaseEventCalls will + * become listeners to this class rather than talking to asterisk directly. Each + * listener will have events queued to it. It can process these events in a + * separate thread.
      + *
      + * Key feature is that one a 'rename' event arrives we must pause all of the + * queues wait for them to empty and for the queue clients to quiescent, then + * apply the rename before resuming pushing data in to the queues.
      + *
      + * Additionally we need to redo the asterisk events classes with our own classes + * that pass around an iChannel rather than a raw channel name. By doing this + * the rename affectively becomes global updating every instance of the channel + * (because they actually only have an instance handle). + * + * @author bsutton + */ +public class ChannelImpl implements Channel { + public static final String ZOMBIE = ""; //$NON-NLS-1$ + public static final String MASQ = ""; //$NON-NLS-1$ + + public static final String UNKNOWN_UNIQUE_ID = "-1"; //$NON-NLS-1$ + + private static final Log logger = LogFactory.getLog(ChannelImpl.class); + private static int logCounter = 100; + + /** + * The channel name including the tech and the channel sequence number but + * not the masquerade prefix and not the zombie suffix. Forced to upper case + * for comparisons. + */ + private String _channelName; + + /** + * A unique id created by Asterisk to uniquely identify this channel. Often + * a channel can be 're-created' on the fly. In this case the channels name + * will be the same but the unique id will change. + */ + private String _uniqueID; + /** + * This is an abbreviated form of the channel name obtained by removing + * everything after the '-' in the channel name. + */ + private EndPoint _endPoint; + + /** + * The caller id for this channel. If this is an inbound channel then it the + * callerid received from the remote end. If this is an outbound channel + * then this is the caller id we are to present to the remote end. + */ + private CallerID _callerID; + + /** + * A globally unique id assigned to each channel as it is created + */ + private long _channelId; + + private boolean _muted = false; + + private boolean _parked = false; + + private volatile boolean _isZombie = false; + + /** + * A channel is live if it has not been hungup. + */ + private boolean _isLive = true; + + /** + * Indicates that the channel is being masquerading by another channel. + * Masqueraded channels have an extra suffix after the sequence + * number e.g. SIP/100-000009823 + */ + private volatile boolean _isMasqueraded = false; + + /** + * Indicates that the channel is undergoing an action such as being parked. + * Action channels have an extra prefix before the tech e.g. + * Parked/SIP/100-000009823 + */ + private volatile boolean _isInAction = false; + + /** + * Indicates that the channel has been originated directly from the Asterisk + * console. We can generally ignore these cases. + */ + private boolean _isConsole = false; + + /** + * The prefix added to a channel during some type of action: e.g. + * Parked/SIP/100-0000032323 In this case the prefix is Parked. + */ + private String _actionPrefix = null; + + public static final String[] _actions = new String[]{"PARKED/", "ASYNCGOTO/", "BRIDGE/"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + /** + * There should be only one hangup listener which is the ChannelProxy that + * wraps this channel. + */ + private ChannelHangupListener hangupListener; + + /** + * When validating channels the start time is set in the _sweepStartTime. as + * a channel is validated the _mark field is set to true. if new channels + * are created as the sweep is in progress the _sweepStartTime will not be + * set so they won't be cleaned up. + */ + private Long _sweepStartTime = null; + private boolean _marked = false; + + /** + * Creates a channel from a channelName
      + *
      + * This constructor is package private for a reason, and is called from + * AsteriskPBX... If you need to add a channel to the PBX do it like + * this
      + *
      + * AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX();
      + * final Channel channel = pbx.registerChannel(channelName, uniqueId);
      + *
      + * Channel names are one of the following formats: + * [Action/]Tech/EndPointName-[][ ] + * DAHDI/i/[:]-
      + *
      + * Where: [Action/] is an action that is being performed on a channel. e.g. + * Parked Tech is the Tech used to reach the end point.
      + *
      + * The set of supported techs are defined by the enum Tech.
      + *
      + * EndPointName the name of the endpoint.
      + *
      + * '' the optional terminating '' which indicates the channel is + * now being masqueraded. A masqueraded channel is one that has been cloned. + * The original channel is marked as being masqueraded and will hangup + * shortly. It plays no further part in the Call.
      + *
      + * '' the optional terminating '' which indicates the + * channel is now a zombie. A zombie channel is one that has been hungup and + * is awaiting final cleanup. I believe the zombie channel is used by the + * hangup extension 'h' in the dialplan.
      + *
      + * The channel name is stripped of the Action, MASQ and ZOMBIE elements. + * + * @param asteriskStateName + * @throws InvalidChannelName + */ + ChannelImpl(final String channelName, final String uniqueID) throws InvalidChannelName { + if (uniqueID == null) + throw new IllegalArgumentException("The UniqueID may not be null."); //$NON-NLS-1$ + + if (channelName == null) + throw new IllegalArgumentException("The channelName may not be null."); //$NON-NLS-1$ + + if (uniqueID.compareToIgnoreCase("-1") == 0) { + logger.debug("uniqueID is -1"); + } + + this._uniqueID = uniqueID; + + this.setChannelName(channelName); + + } + + /** + * designed for use by the ChannelProxy when a channel is being cloned as a + * result of Asterisk undertaking an Masquerade. This is not intended to be + * a complete clone just the key elements that we generally track on our + * side rather than getting directly from asterisk. + */ + public void masquerade(Channel channel) { + // If the channel doesn't have a caller id + // preserve the existing one (as given this is a clone they should be + // identical). + // Asterisk doesn't always pass the caller ID on the channel hence this + // protects us from Asterisk accidentally clearing the caller id. + if (channel.hasCallerID()) { + this._callerID = channel.getCallerID(); + } else if (this._callerID != null && ((ChannelImpl) channel)._callerID != null) { + // Force the caller id back into the channel so it has one as well. + PBX pbx = PBXFactory.getActivePBX(); + if (this._callerID != null) { + ((ChannelImpl) channel)._callerID = pbx.buildCallerID(this._callerID.getNumber(), + this._callerID.getName()); + } + } + + this._muted = channel.isMute(); + + this._parked = channel.isParked(); + + // just in case the original channel is part way through a sweep by the + // PeerMonitor + // marking the sweep as true will stop the new clone being hungup as it + // may not have been around when the sweep started. + this._marked = true; + this._sweepStartTime = null; + } + + private void setChannelName(final String channelName) throws InvalidChannelName { + logger.debug("Renamed channel from " + this._channelName + " to " + channelName); + this._channelName = this.cleanChannelName(channelName); + this.validateChannelName(this._channelName); + + this._channelId = ChannelFactory.getNextChannelId(); + this._endPoint = new EndPointImpl(this.extractPeerName(this._channelName)); + + // After stripping everything from the channel name after the hypen + // we should have the endpoint name which shouldn't match the + // channel name + // unless its a channel caused by a console dial (Console/dsp) which + // we don't really care about. + // If the peer name still matches then we have a malformed channel + // name. + if ((this._channelName.compareTo(this.getEndPoint().getFullyQualifiedName()) == 0) && !this._isConsole) { + if (ChannelImpl.logCounter > 0) { + ChannelImpl.logger.warn("Invalid channel name " + this._channelName); //$NON-NLS-1$ + ChannelImpl.logCounter--; + } else if (ChannelImpl.logCounter == 0) { + ChannelImpl.logger.warn("Further Invalid channel name warnings suppressed"); //$NON-NLS-1$ + ChannelImpl.logCounter--; + } + } + } + + /** + * validates the channel name. Validate is to be called after the channel + * has been cleaned. + * + * @param channelName + * @throws InvalidChannelName + */ + private void validateChannelName(final String channelName) throws InvalidChannelName { + if (!this._isConsole) { + if (!TechType.hasValidTech(channelName)) { + throw new InvalidChannelName("Invalid channelName: " + channelName + ". Unknown tech."); //$NON-NLS-1$ //$NON-NLS-2$ + } + + // Check we have the expected hypen + final int hypen = channelName.indexOf("-"); //$NON-NLS-1$ + if (hypen == -1) { + throw new InvalidChannelName("Invalid channelName: " + channelName + ". Missing hypen."); //$NON-NLS-1$ //$NON-NLS-2$ + } + + // Check we have the expected slash + final int slash = channelName.indexOf("/"); //$NON-NLS-1$ + if (slash == -1) { + throw new InvalidChannelName("Invalid channelName: " + channelName + ". Missing slash."); //$NON-NLS-1$ //$NON-NLS-2$ + } + + // Check that the hypen is after the slash. + if (hypen < slash) { + throw new InvalidChannelName( + "Invalid channelName: " + channelName + ". Hypen must be after the slash."); //$NON-NLS-1$ //$NON-NLS-2$ + } + + // Check that there is at least one characters between the hypen and + // the + // slash + if ((hypen - slash) < 2) { + throw new InvalidChannelName("Invalid channelName: " + channelName //$NON-NLS-1$ + + ". Must be one character between the hypen and the slash."); //$NON-NLS-1$ + } + + // Check that the channel sequence number is at least 1 character + // long. + if ((channelName.length() - hypen) < 2) { + throw new InvalidChannelName("Invalid channelName: " + channelName //$NON-NLS-1$ + + ". The channel sequence number must be at least 1 character."); //$NON-NLS-1$ + } + } + + } + + /** + * Cleans up the channel name by applying the following: 1) trim any + * whitespace 2) convert to upper case for easy string comparisions 3) strip + * of the masquerade prefix if it exists and mark the channel as + * masquerading 4) strip the zombie suffix and mark it as being a zombie. + * + * @param name + * @return + */ + private String cleanChannelName(final String name) { + String cleanedName = name.trim().toUpperCase(); + + // If if the channel is the console + this._isConsole = false; + if (name.compareToIgnoreCase("Console/dsp") == 0) //$NON-NLS-1$ + { + this._isConsole = true; + } + + // Check if the channel is in an action + boolean wasInAction = this._isInAction; + this._isInAction = false; + for (final String prefix : ChannelImpl._actions) { + if (cleanedName.startsWith(prefix)) { + this._isInAction = true; + this._actionPrefix = cleanedName.substring(0, prefix.length() - 1); + cleanedName = cleanedName.substring(prefix.length()); + break; + } + } + if (wasInAction != this._isInAction) { + logger.debug( + "Channel " + this + " : inaction status changed from " + wasInAction + " to " + this._isInAction); + } + + // Channels can be marked as in a zombie state + // so we need to strip of the zombie suffix and just mark the channel + // as a + // zombie. + this._isZombie = false; + if (cleanedName.contains(ChannelImpl.ZOMBIE)) { + this._isZombie = true; + cleanedName = cleanedName.substring(0, cleanedName.indexOf(ChannelImpl.ZOMBIE)); + } + + // Channels can be marked as in a MASQ state + // This happens during transfers (and other times) when the channel is + // replaced + // by a new channel in the call. The old channel is renamed with the + // word + // added as a suffix. + this._isMasqueraded = false; + if (cleanedName.contains(ChannelImpl.MASQ)) { + this._isMasqueraded = true; + cleanedName = cleanedName.substring(0, cleanedName.indexOf(ChannelImpl.MASQ)); + } + + return cleanedName; + } + + @Override + public void rename(final String newName, String uniqueId) throws InvalidChannelName { + + String oldChannelName = getChannelName(); + logger.info("Changing " + oldChannelName + " to " + newName + " on " + oldChannelName + " " + _uniqueID); + this.setChannelName(newName); + + if (_uniqueID.equalsIgnoreCase("-1")) { + logger.info("Changing " + _uniqueID + " to " + uniqueId + " on " + oldChannelName + " " + _uniqueID); + _uniqueID = uniqueId; + } + + // the new replacement channel will go through a rename (without + // MASQ) and is ready to use. + + // the old channel will go through a rename (MASQ), then anther + // rename (ZOMBIE) and finally a hangup + + _isInAction = false; + + } + + @Override + public String getChannelName() { + return this._channelName; + } + + @Override + public EndPoint getEndPoint() { + return this._endPoint; + } + + /* + * Extracts the peer name from a full channel name. The channel name is + * created by asterisk and consists of the peer name a hypen and a unique + * sequence number. e.g. SIP/100-000000123 * For SIP channels the Peer name + * is of the form: SIP/100 For dahdi channels the channel name is of the + * form: DAHDI/i/[:]-0000000123 With the peer name + * of the form: DAHDI/i/[:] + */ + private final String extractPeerName(final String channelName) { + // Find the start of the sequence number + int channelNameEndPoint = channelName.lastIndexOf("-"); //$NON-NLS-1$ + if (channelNameEndPoint == -1) { + channelNameEndPoint = channelName.length(); + } + // return the peer name which is everything before the sequence number + // (and its hypen). + return channelName.substring(0, channelNameEndPoint); + } + + boolean wasMarkedDuringSweep() { + boolean ret = false; + if (this._sweepStartTime == null || this._marked) { + this._sweepStartTime = null; + ret = true; + } + return ret; + } + + @Override + public void setCallerId(final CallerID callerId) { + this._callerID = callerId; + } + + /** + * Used to start the Mark and Sweep process by setting the marked status to + * false. At the end of the sweep the marked flag should have been set to + * true. If not then this channel has been hungup. + */ + void startSweep() { + this._sweepStartTime = System.currentTimeMillis(); + this._marked = false; + } + + /** + * The channel was found to be active on asterisk so it is still alive. + */ + void markChannel() { + this._marked = true; + + } + + /** + * ************************************************************************* + * ************************** The remaining methods are bridging methods to + * the new abstract PBX classes. + * ************************************************************************* + * ************************** + */ + @Override + public boolean isSame(final Channel _rhs) { + boolean equals = false; + + if (_rhs == null) { + logger.warn("isSame called with null"); + return false; + } + ChannelImpl rhs; + if (_rhs instanceof ChannelImpl) { + rhs = (ChannelImpl) _rhs; + } else { + rhs = ((ChannelProxy) _rhs).getRealChannel(); + } + // If we have unique id's for both channels then we can compare the id's + // directly. + if ((this._uniqueID.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0) + && (rhs._uniqueID.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0)) { + if (this._uniqueID.compareToIgnoreCase(rhs._uniqueID) == 0) { + equals = true; + } + } else { + boolean ok = (this._channelName != null) && (rhs._channelName != null); + final boolean namesMatch = (ok && (this._channelName.compareToIgnoreCase(rhs._channelName) == 0)); + + if (namesMatch) { + // check if the actions match + if (this._isInAction != rhs._isInAction) { + ok = false; + } else if (this._isInAction) { + ok = this._actionPrefix.compareTo(rhs._actionPrefix) == 0; + } + } + + if (ok && namesMatch) { + // check if the zombie match + if (this._isZombie != rhs._isZombie) { + ok = false; + } + } + + if (ok && namesMatch) { + // check if the masquerade match + if (this._isMasqueraded != rhs._isMasqueraded) { + ok = false; + } + } + + equals = ok & namesMatch; + } + return equals; + } + + @Override + public boolean isSame(final String extendedChannelName, final String uniqueID) { + boolean equals = false; + if ((this._uniqueID.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0) + && (uniqueID.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0)) { + if (this._uniqueID.compareTo(uniqueID) == 0) { + equals = true; + } + } else { + equals = this.sameExtenededChannelName(extendedChannelName); + } + + return equals; + } + + @Override + public boolean sameExtenededChannelName(final String extendedChannelName) { + boolean ok = (this.getExtendedChannelName() != null) && (extendedChannelName != null); + + return ok && (this.getExtendedChannelName().compareToIgnoreCase(extendedChannelName) == 0); + } + + /** + * Try to match a channel based solely on its unique ID + * + * @param uniqueID + * @return + */ + public boolean sameUniqueID(String uniqueID) { + boolean equals = false; + if ((this._uniqueID.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0) + && (uniqueID.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0)) { + if (this._uniqueID.compareTo(uniqueID) == 0) { + equals = true; + } + } + + return equals; + } + + @Override + public boolean sameEndPoint(final Channel rhs) { + return this.sameEndPoint(rhs.getEndPoint()); + } + + @Override + public boolean sameEndPoint(final EndPoint rhs) { + boolean ok = (this._endPoint != null) && (rhs != null); + return ok && this._endPoint.isSame(rhs); + } + + @Override + public long getChannelId() { + return this._channelId; + } + + @Override + public boolean isLive() { + return this._isLive; + } + + @Override + public void addHangupListener(final ChannelHangupListener listener) { + if (this.hangupListener != null) + throw new IllegalStateException("This channel may only have ONE listener which should be its ChannelProxy"); //$NON-NLS-1$ + + this.hangupListener = listener; + } + + @Override + public void removeListener(final ChannelHangupListener listener) { + + if (this.hangupListener != listener) + throw new IllegalStateException("An invalid attempt was made to remove a non-existant listener."); //$NON-NLS-1$ + + this.hangupListener = null; + + } + + /** + * Called by Peer when we have been hungup. This can happen when Peer + * receives a HangupEvent or during a periodic sweep done by PeerMonitor to + * find the status of all channels. Notify any listeners that this channel + * has been hung up. + */ + @Override + public void notifyHangupListeners(Integer cause, String causeText) { + this._isLive = false; + if (this.hangupListener != null) { + this.hangupListener.channelHangup(this, cause, causeText); + } else { + logger.warn("Hangup listener is null"); + } + } + + @Override + public boolean isConnectedTo(final EndPoint endPoint) { + return this._endPoint.isSame(endPoint); + } + + @Override + public boolean isMute() { + return this._muted; + } + + @Override + public void setMute(final boolean mutedState) { + this._muted = mutedState; + } + + @Override + public void setParked(final boolean parked) { + this._parked = parked; + + } + + @Override + public boolean isParked() { + return this._parked; + } + + @Override + public String toString() { + return this.getExtendedChannelName() + ":" + this._uniqueID; //$NON-NLS-1$ + } + + /** + * Returns the full channel name including the masquerade prefix and the + * zombie suffix. + * + * @return + */ + + @Override + public String getExtendedChannelName() { + int state = getState(); + if (state != lastState || !_channelName.equals(lastChannelName)) { + final StringBuilder name = new StringBuilder(); + + if (this._isInAction) { + name.append(this._actionPrefix); + name.append("/"); //$NON-NLS-1$ + } + name.append(this._channelName); + + if (this._isMasqueraded) { + name.append(ChannelImpl.MASQ); + } + + if (this._isZombie) { + name.append(ChannelImpl.ZOMBIE); + } + lastState = state; + lastChannelName = _channelName; + cachedExtenedChannelName = name.toString(); + + } + return cachedExtenedChannelName; + + } + + String cachedExtenedChannelName = null; + int lastState = -1; + String lastChannelName = null; + + int getState() { + int state = 0; + if (_isInAction) { + state += 2; + } + if (_isZombie) { + state += 4; + } + if (_isMasqueraded) { + state += 8; + } + return state; + } + + @Override + public boolean isLocal() { + return this._endPoint.isLocal(); + } + + @Override + public boolean isZombie() { + return this._isZombie; + } + + @Override + public boolean isConsole() { + return this._isConsole; + } + + TechType getTech() { + return this._endPoint.getTech(); + } + + /** + * Returns the actionPrefix for the channel or an empty string if the + * channel is not doing an action. + * + * @return + */ + String getActionPrefix() { + return this._isInAction ? this._actionPrefix : ""; //$NON-NLS-1$ + } + + boolean isInAction() { + return this._isInAction; + } + + boolean isMasqueraded() { + return this._isMasqueraded; + } + + @Override + public boolean hasCallerID() { + return this._callerID != null && !this._callerID.isUnknown(); + } + + @Override + public CallerID getCallerID() { + if (this._callerID == null) { + final CoherentManagerConnection smc = CoherentManagerConnection.getInstance(); + final String number = smc.getVariable(this, "CALLERID(number)"); //$NON-NLS-1$ + final String name = smc.getVariable(this, "CALLERID(name)"); //$NON-NLS-1$ + final PBX pbx = PBXFactory.getActivePBX(); + this._callerID = pbx.buildCallerID(number, name); + } + + return this._callerID; + + } + + @Override + public String getUniqueId() { + return this._uniqueID; + } + + /* + * Returns true if this channel can detect hangups A SIP channel can always + * detect a hangup if its not channel then we need to check the profile to + * see if hangup detection is available. Hangup detection is important as we + * don't want to connect two channels both of which can't do hangup + * detection. If this happened then we would end up with a call which would + * never hangup. + */ + @Override + public boolean canDetectHangup() { + boolean canDetectHangup = true; + + AsteriskSettings profile = PBXFactory.getActiveProfile(); + final boolean detect = profile.getCanDetectHangup(); + if (!this.getEndPoint().isSIP() && !detect) { + canDetectHangup = false; + } + return canDetectHangup; + } + + /** + * Returns true if the channel is quiescent. A quescent channel is one that + * is current not going through a transition (name change) such as MASQ, + * ZOMBIE, ASYNC, PARK + * + * @return + */ + @Override + public boolean isQuiescent() { + return !(_isInAction || _isMasqueraded || _isZombie); + } + + @Override + public AgiChannelActivityAction getCurrentActivityAction() { + throw new RuntimeException("This method is only implemented in ChannelProxy"); + } + + @Override + public void setCurrentActivityAction(AgiChannelActivityAction action) { + throw new RuntimeException("This method is only implemented in ChannelProxy"); + } + + @Override + public void setIsInAgi(boolean b) { + throw new RuntimeException("This method is only implemented in ChannelProxy"); + } + + @Override + public boolean isInAgi() { + throw new RuntimeException("This method is only implemented in ChannelProxy"); + } + + @Override + public boolean waitForChannelToReachAgi(long timeout, TimeUnit timeunit) throws InterruptedException { + throw new RuntimeException("This method is only implemented in ChannelProxy"); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/ChannelProxy.java b/src/main/java/org/asteriskjava/pbx/internal/core/ChannelProxy.java new file mode 100644 index 000000000..40dd823b2 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/ChannelProxy.java @@ -0,0 +1,354 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.agi.AgiChannelActivityHold; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +/** + * The ChannelProxy exists to deal with the fact that Asterisk will often + * replace a channel during a call. This is referred to as Masquerading. When a + * channel is to be Masqueraded we get a Masquerade event. The ChannelProxy + * class acts as a level of indirection for an iChannel. Rather than holding an + * iChannel directly you can instead hold a ChannelProxy. If the underlying + * iChannel is replaced the ChannelProxy will be updated with the new iChannel. + * + * @author bsutton + */ +public class ChannelProxy implements Channel, ChannelHangupListener { + + private static final Log logger = LogFactory.getLog(ChannelProxy.class); + + /** + * We give each proxy a unique identity to help track them when debugging. + */ + private static final AtomicInteger _nextIdentity = new AtomicInteger(); + + private int _identity = _nextIdentity.incrementAndGet(); + + private ChannelImpl _channel; + + private final List listeners = new CopyOnWriteArrayList<>(); + + public ChannelProxy(ChannelImpl channel) { + this._channel = channel; + currentActivityAction.set(new AgiChannelActivityHold()); + + channel.addHangupListener(this); + + } + + /** + * returns the current channel + * + * @return + */ + public Channel getChannel() { + return this._channel; + } + + @Override + public boolean isSame(Channel rhs) { + return this._channel.isSame(rhs); + } + + @Override + public boolean isSame(String extendedChannelName, String uniqueID) { + return this._channel.isSame(extendedChannelName, uniqueID); + } + + public boolean sameUniqueID(String uniqueID) { + return this._channel.sameUniqueID(uniqueID); + } + + @Override + public boolean sameEndPoint(Channel rhs) { + return this._channel.sameEndPoint(rhs); + } + + @Override + public boolean sameEndPoint(EndPoint extensionRoaming) { + return this._channel.sameEndPoint(extensionRoaming); + } + + @Override + public boolean sameExtenededChannelName(String channelName) { + return this._channel.sameExtenededChannelName(channelName); + } + + @Override + public void setParked(boolean parked) { + this._channel.setParked(parked); + } + + @Override + public void setMute(boolean muteState) { + this._channel.setMute(muteState); + + } + + @Override + public long getChannelId() { + return this._channel.getChannelId(); + } + + @Override + public boolean isLive() { + return this._channel.isLive(); + } + + @Override + public void addHangupListener(ChannelHangupListener listener) { + if (!listeners.contains(listener)) { + this.listeners.add(listener); + } + + } + + @Override + public void removeListener(ChannelHangupListener listener) { + + this.listeners.remove(listener); + + } + + @Override + public boolean isConnectedTo(EndPoint endPoint) { + return this._channel.isConnectedTo(endPoint); + } + + @Override + public String getChannelName() { + return this._channel.getChannelName(); + } + + @Override + public EndPoint getEndPoint() { + return this._channel.getEndPoint(); + } + + @Override + public boolean isMute() { + return this._channel.isMute(); + } + + @Override + public boolean isLocal() { + return this._channel.isLocal(); + } + + @Override + public boolean isZombie() { + return this._channel.isZombie(); + } + + @Override + public boolean isConsole() { + return this._channel.isConsole(); + } + + @Override + public CallerID getCallerID() { + return this._channel.getCallerID(); + } + + @Override + public void rename(String newName, String uniqueId) throws InvalidChannelName { + this._channel.rename(newName, uniqueId); + } + + @Override + public boolean isParked() { + return this._channel.isParked(); + } + + /** + * Used to handle a MasqueradeEvent. We essentially swap the two underlying + * channels between the two proxies. + * + * @param cloneProxy + * @throws InvalidChannelName + */ + public void masquerade(ChannelProxy cloneProxy) throws InvalidChannelName { + ChannelImpl originalChannel = this._channel; + ChannelImpl cloneChannel = cloneProxy._channel; + + cloneChannel.masquerade(this._channel); + + // detach the hangup listeners + originalChannel.removeListener(this); + cloneChannel.removeListener(cloneProxy); + + // Now we swap the channels. + this._channel = cloneChannel; + cloneProxy._channel = originalChannel; + + // Now re-attach the hangup listeners + this._channel.addHangupListener(this); + cloneProxy._channel.addHangupListener(cloneProxy); + + logger.debug(originalChannel + " Channel proxy now points to " + this._channel); + } + + public ChannelImpl getRealChannel() { + return this._channel; + } + + @Override + public String getExtendedChannelName() { + return this._channel.getExtendedChannelName(); + } + + private volatile boolean hangupCalled = false; + + @Override + public void notifyHangupListeners(Integer cause, String causeText) { + for (ChannelHangupListener listener : this.listeners) { + listener.channelHangup(this, cause, causeText); + } + + if (hangupCalled) { + logger.error("Hangup was already called and the listeners removed - OH NO"); + } + // we will blow up if notify listeners is called again + hangupCalled = true; + listeners.clear(); + + } + + @Override + public String toString() { + return "(proxy=" + this._identity + ") " + this._channel.toString(); //$NON-NLS-1$ //$NON-NLS-2$ + } + + @Override + public void channelHangup(Channel channel, Integer cause, String causeText) { + // When the underlying channel hangs up we need to notify all of the + // proxy listeners. + if (channel == this._channel) + notifyHangupListeners(cause, causeText); + + } + + @Override + public boolean canDetectHangup() { + return this._channel.canDetectHangup(); + } + + @Override + public boolean isQuiescent() { + return this._channel.isQuiescent(); + } + + @Override + public boolean hasCallerID() { + return this._channel.hasCallerID(); + } + + /* + * (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + _identity; + return result; + } + + /* + * (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof ChannelProxy)) { + return false; + } + ChannelProxy other = (ChannelProxy) obj; + if (_identity != other._identity) { + return false; + } + return true; + } + + private AtomicReference currentActivityAction = new AtomicReference<>(); + volatile private boolean isInAgi; + + @Override + public AgiChannelActivityAction getCurrentActivityAction() { + return currentActivityAction.get(); + } + + @Override + public void setCurrentActivityAction(AgiChannelActivityAction action) { + AgiChannelActivityAction previousAction = currentActivityAction.get(); + + logger.debug("Setting action to " + action.getClass().getSimpleName() + " for " + this); + + // Exception e = new Exception("Setting action to " + + // action.getClass().getSimpleName() + " for " + this); + // logger.warn(e, e); + + currentActivityAction.set(action); + if (previousAction != null) { + // when we cancel the previous action, the new one will be invoked + previousAction.cancel(); + } + } + + @Override + public void setIsInAgi(boolean b) { + if (b) { + hasReachedAgi.countDown(); + } + isInAgi = b; + logger.info("Setting is in agi to " + b + " for channel " + this); + + } + + @Override + public boolean isInAgi() { + return isInAgi; + } + + final CountDownLatch hasReachedAgi = new CountDownLatch(1); + + @Override + public boolean waitForChannelToReachAgi(long timeout, TimeUnit timeunit) throws InterruptedException { + logger.info("Waiting for channel to reach agi " + this); + boolean tmp = hasReachedAgi.await(timeout, timeunit); + logger.info("Result of waiting for channel to reach agi " + this + " " + tmp); + return tmp; + } + + @Override + public String getUniqueId() { + return _channel.getUniqueId(); + } + + public int getIdentity() { + return _identity; + } + + @Override + public void setCallerId(CallerID callerId) { + _channel.setCallerId(callerId); + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/CoherentEventFactory.java b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentEventFactory.java new file mode 100644 index 000000000..454a2ff9d --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentEventFactory.java @@ -0,0 +1,174 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.asterisk.wrap.actions.ManagerAction; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.ResponseEvent; +import org.asteriskjava.pbx.asterisk.wrap.response.CommandResponse; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerError; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; +import org.asteriskjava.util.ReflectionUtil; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; +import java.util.Hashtable; +import java.util.Set; + +/** + * This class maps asterisk-java events to our internal events that use iChannel + * rather than raw channel names. + * + * @author bsutton + */ +@SuppressWarnings({"unchecked"}) +public class CoherentEventFactory { + private static final Log logger = LogFactory.getLog(CoherentEventFactory.class); + + // Events + static Hashtable, Class> mapEvents = new Hashtable<>(); + + // Response + static Hashtable, Class> mapResponses = new Hashtable<>(); + + // static initialiser + static { + + Set> knownClasses = ReflectionUtil.loadClasses("org.asteriskjava.pbx.asterisk.wrap.events", + ManagerEvent.class); + + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + for (Class known : knownClasses) { + Class clazz = null; + try { + clazz = classLoader.loadClass("org.asteriskjava.manager.event" + "." + known.getSimpleName()); + + if (!Modifier.isAbstract(clazz.getModifiers())) { + if (known.getConstructor(clazz) != null) { + if (ResponseEvent.class.isAssignableFrom(known)) { + CoherentEventFactory.mapResponses.put( + (Class) clazz, + (Class) known); + logger.info("Response Event Added " + clazz + " --> " + known); + + } else { + CoherentEventFactory.mapEvents.put((Class) clazz, + (Class) known); + logger.info("Manager Event Added " + clazz + " --> " + known); + } + } else { + logger.warn("Skipping class " + clazz + " it doesn't have a public constructor with one arg of type " + + known); + } + } else { + logger.info("Skipping abstract class " + clazz); + } + } catch (ClassNotFoundException e) { + logger.error(e, e); + throw new RuntimeException(e); + } catch (NoSuchMethodException e) { + logger.error(clazz.getCanonicalName() + " doesn't have an appropriate event constructor"); + } catch (SecurityException e) { + logger.error(e, e); + } + } + + CoherentEventFactory.mapResponses.put(org.asteriskjava.manager.event.ResponseEvent.class, ResponseEvent.class); + + } + + public static Class getShadowEvent(org.asteriskjava.manager.event.ManagerEvent event) { + Class result = CoherentEventFactory.mapEvents.get(event.getClass()); + if (result == null) { + Class response = CoherentEventFactory.mapResponses.get(event.getClass()); + result = response; + } + + return result; + + } + + public static ManagerEvent build(final org.asteriskjava.manager.event.ManagerEvent event) { + ManagerEvent iEvent = null; + + Class target = null; + + if (event instanceof org.asteriskjava.manager.event.ResponseEvent) + target = CoherentEventFactory.mapResponses.get(event.getClass()); + else + target = CoherentEventFactory.mapEvents.get(event.getClass()); + + if (target == null) { + logger.warn("The given event " + event.getClass().getName() + " is not supported "); //$NON-NLS-1$ //$NON-NLS-2$ + } else { + + try { + iEvent = target.getDeclaredConstructor(event.getClass()).newInstance(event); + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + CoherentEventFactory.logger.error(e, e); + + } + } + return iEvent; + } + + public static ResponseEvent build(org.asteriskjava.manager.event.ResponseEvent event) { + ResponseEvent response = null; + + final Class target = CoherentEventFactory.mapResponses.get(event.getClass()); + + if (target == null) { + logger.warn("The given event " + event.getClass().getName() + " is not supported "); //$NON-NLS-1$ //$NON-NLS-2$ + } else { + + try { + final Constructor declaredConstructor = target + .getDeclaredConstructor(event.getClass()); + response = declaredConstructor.newInstance(event); + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + CoherentEventFactory.logger.error(e, e); + + } + } + return response; + } + + public static ManagerResponse build(org.asteriskjava.manager.response.ManagerResponse response) { + ManagerResponse result; + if (response instanceof org.asteriskjava.manager.response.CommandResponse) { + result = new CommandResponse(response); + } else if (response instanceof org.asteriskjava.manager.response.ManagerError) { + result = new ManagerError(response); + } else { + result = new ManagerResponse(response); + } + return result; + + } + + public static org.asteriskjava.manager.action.ManagerAction build(ManagerAction action) { + org.asteriskjava.manager.action.ManagerAction result = null; + + // final Class + // target = CoherentEventFactory.mapActions.get(action.getClass()); + + if (logger.isDebugEnabled()) + logger.debug("Action " + action); //$NON-NLS-1$ + + // if (target == null) + // { + // logger.warn("The given action " + action.getClass().getName() + " is + // not supported "); //$NON-NLS-1$ //$NON-NLS-2$ + // } + // else + { + result = action.getAJAction(); + } + return result; + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java new file mode 100644 index 000000000..fd73f2fd8 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java @@ -0,0 +1,465 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.manager.*; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.asterisk.wrap.actions.*; +import org.asteriskjava.pbx.asterisk.wrap.events.ConnectEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.DisconnectEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.ResponseEvents; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.pbx.internal.managerAPI.Connector; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import javax.naming.OperationNotSupportedException; +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * This is a wrapper class for the asterisk manager.
      + *
      + * It handles the hot swap of an asterisk server and distributes events to event + * listeners.
      + *
      + * The CoherentManagerConnection should be used whenever manager events need to + * be received either for short or extended periods of time.
      + *
      + * The CoherentManagerConnection uses the ManagerEventQueue to queue events to + * each listener.
      + *
      + * The ManagerEventQueue dispatches the events to the set of listeners using a + * separate thread (shared by all of the listeners).
      + *
      + * This means that we are always responsive to asterisk when receiving events, + * if we are not responsive then asterisk will drop the connection.
      + *
      + * It should be noted that as all events are dispatch from a single thread and + * as such a single tardy listener can block all other listeners.
      + *
      + * If your listener is likely to be slow in handling events then you should wrap + * the listener in its own ManagerEventQueue.
      + *
      + * It is critical that you use the ManagerEventQueue as it forms an intrinsic + * part of this classes ability to ensure that channel/event processing is + * coherent (i.e events are processed in the correct order).
      + *
      + * For connections that generate large number of events you should use + * + * @see org.asteriskjava.pbx.internal.core.CoherentManagerEventQueue Note: + * events for any action are distributed to all listeners! + */ +class CoherentManagerConnection implements FilteredManagerListener { + + static private Log logger = LogFactory.getLog(CoherentManagerConnection.class); + + static Map eventStatistics = new HashMap<>(); + + /** + * Used to instantiate the manager connection including the initial login. + */ + static Connector connector = null; + + /** + * The actual manager connection. AJ actually maintains two socket + * connections one for reading events and the other writing events. + */ + static ManagerConnection managerConnection = null; + + /** + * We operate two separate event queues each of which dispatches events via + * its own thread. All ListenerPriority.REALTIME events are dispatch via the + * realtime queue. REALTIME events cannot rely on the LiveChannelManager as + * it will may have been updated (renames, masquerades) when the realtime + * listener processes its event. + */ + private CoherentManagerEventQueue eventQueue; + + private CoherentManagerEventQueue realtimeEventQueue; + + // private List> realtimeListeners = + // new CopyOnWriteArrayList<>(); + + // True if the AMI function 'Bridge' is available. + private boolean canBridge; + + // True if the AMI function 'MuteAudio' is available. + private boolean canMuteAudio; + + private static CoherentManagerConnection self = null; + + // latch used for reconnections. + // We create an initial latch incase we get connect before we are really + // ready to wait for one. + private CountDownLatch _reconnectLatch = new CountDownLatch(0); + + private boolean expectRenameEvents = true; + + public static synchronized void init() + throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException, InterruptedException { + if (self != null) + logger.warn("The CoherentManagerConnection has already been initialised"); + else { + self = new CoherentManagerConnection(); + boolean done = false; + while (!done) { + try { + + self.checkConnection(); + self.checkFeatures(); + done = true; + } catch (Exception e) { + logger.error(e, e); + try { + TimeUnit.MILLISECONDS.sleep(500); + } catch (InterruptedException e1) { + throw e1; + } + } + } + } + + self.checkConnection(); + } + + public static void reset() { + self = null; + } + + public static synchronized CoherentManagerConnection getInstance() { + if (self == null) + throw new IllegalStateException("The CoherentManagerConnection has not been initialised"); + + self.checkConnection(); + + return self; + } + + private CoherentManagerConnection() + throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException { + super(); + connector = new Connector(); + this.configureConnection(); + } + + public AsteriskVersion getVersion() throws IllegalStateException { + return CoherentManagerConnection.managerConnection.getVersion(); + } + + public void setVariable(final Channel channel, final String variableName, final String value) throws PBXException { + try { + /* + * Sets the specified variable on the specified channel to the + * specified value. + */ + final SetVarAction setVariable = new SetVarAction(channel, variableName, value); + ManagerResponse response; + + PBX pbx = PBXFactory.getActivePBX(); + if (!pbx.waitForChannelToQuiescent(channel, 3000)) + throw new PBXException("Channel: " + channel + " cannot be retrieved as it is still in transition."); + + response = sendAction(setVariable, 500); + if ((response != null) && (response.getResponse().compareToIgnoreCase("success") == 0)) { + // $NON-NLS-1$ + + CoherentManagerConnection.logger.debug("set variable " + variableName + " to " + value //$NON-NLS-2$ + + " on " + channel); + } else { + throw new PBXException("failed to set variable '" + variableName + "' on channel " + channel + " to '" //$NON-NLS-2$ //$NON-NLS-3$ + + value + "'" + (response != null ? " Error:" + response.getMessage() : "")); //$NON-NLS-2$ //$NON-NLS-3$ + } + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { + logger.error(e, e); + throw new PBXException(e); + + } + + } + + /** + * Retrieves and returns the value of a variable associated with a channel. + * If the variable is empty or null then an empty string is returned. + * + * @param channel + * @param variableName + * @return + */ + public String getVariable(final Channel channel, final String variableName) { + String value = ""; + final GetVarAction var = new GetVarAction(channel, variableName); + + try { + PBX pbx = PBXFactory.getActivePBX(); + if (!pbx.waitForChannelToQuiescent(channel, 3000)) + throw new PBXException("Channel: " + channel + " cannot be retrieved as it is still in transition."); + + ManagerResponse convertedResponse = sendAction(var, 500); + if (convertedResponse != null) { + value = convertedResponse.getAttribute("value"); + if (value == null) + value = ""; + CoherentManagerConnection.logger.debug("getVarAction returned name:" + variableName + " value:" + value); //$NON-NLS-2$ + } + } catch (final Exception e) { + CoherentManagerConnection.logger.debug(e, e); + CoherentManagerConnection.logger.error("getVariable: " + e); + } + return value; + } + + /** + * Allows the caller to send an action to asterisk without waiting for the + * response. You should only use this if you don't care whether the action + * actually succeeds. + * + * @param sa + */ + public static void sendActionNoWait(final ManagerAction action) { + final Thread background = new Thread() { + @Override + public void run() { + try { + CoherentManagerConnection.sendAction(action, 5000); + } catch (final Exception e) { + CoherentManagerConnection.logger.error(e, e); + } + } + }; + background.setName("sendActionNoWait"); + background.setDaemon(true); + background.start(); + } + + public static ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) + throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException { + org.asteriskjava.manager.ResponseEvents events = CoherentManagerConnection.managerConnection + .sendEventGeneratingAction(action.getAJEventGeneratingAction()); + + ResponseEvents convertedEvents = new ResponseEvents(); + for (org.asteriskjava.manager.event.ResponseEvent event : events.getEvents()) { + convertedEvents.add(CoherentEventFactory.build(event)); + } + return convertedEvents; + + } + + public static ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, int timeout) + throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException { + org.asteriskjava.manager.ResponseEvents events = CoherentManagerConnection.managerConnection + .sendEventGeneratingAction(action.getAJEventGeneratingAction(), timeout); + + ResponseEvents convertedEvents = new ResponseEvents(); + for (org.asteriskjava.manager.event.ResponseEvent event : events.getEvents()) { + convertedEvents.add(CoherentEventFactory.build(event)); + } + return convertedEvents; + + } + + /** + * Sends an Asterisk action and waits for a ManagerRespose. + * + * @param action + * @param timeout timeout in milliseconds + * @return + * @throws IllegalArgumentException + * @throws IllegalStateException + * @throws IOException + * @throws TimeoutException + * @throws OperationNotSupportedException + */ + public static ManagerResponse sendAction(final ManagerAction action, final int timeout) + throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { + if (logger.isDebugEnabled()) + CoherentManagerConnection.logger.debug("Sending Action: " + action.toString()); + + CoherentManagerConnection.getInstance(); + if ((CoherentManagerConnection.managerConnection != null) + && (CoherentManagerConnection.managerConnection.getState() == ManagerConnectionState.CONNECTED)) { + final org.asteriskjava.manager.action.ManagerAction ajAction = action.getAJAction(); + + org.asteriskjava.manager.response.ManagerResponse response = CoherentManagerConnection.managerConnection + .sendAction(ajAction, timeout); + ManagerResponse convertedResponse = null; + + // UserEventActions always return a null + if (response != null) + convertedResponse = CoherentEventFactory.build(response); + + if ((convertedResponse != null) && (convertedResponse.getResponse().compareToIgnoreCase("Error") == 0)) { + CoherentManagerConnection.logger.warn("Action '" + ajAction + "' failed, Response: " + + convertedResponse.getResponse() + " Message: " + convertedResponse.getMessage()); + } + return convertedResponse; + } + + throw new IllegalStateException("not connected."); + } + + private void checkConnection() { + int trys = 3; + + this._reconnectLatch = new CountDownLatch(1); + while ((trys > 0) && ((CoherentManagerConnection.managerConnection == null) + || (CoherentManagerConnection.managerConnection.getState() != ManagerConnectionState.CONNECTED))) { + if (trys == 3) { + CoherentManagerConnection.logger.warn("Awaiting Manager connection"); + } + try { + + this._reconnectLatch.await(300, TimeUnit.MILLISECONDS); + } catch (final InterruptedException e) { + CoherentManagerConnection.logger.error(e, e); + } + trys--; + } + } + + public ManagerConnectionState getState() { + return CoherentManagerConnection.managerConnection.getState(); + } + + private void configureConnection() + throws IOException, AuthenticationFailedException, TimeoutException, IllegalStateException { + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + CoherentManagerConnection.managerConnection = CoherentManagerConnection.connector.connect(profile); + + // After a reconnect we will have duplicate eventQueues and + // realtimeEventQueues but + // the original queues will be drained quite quickly (on the small + // chance + // that it hasn't already) + // and should have no duplicate events. Once drained the queue will be + // garbage collected. + CoherentManagerEventQueue newRealtime = new CoherentManagerEventQueue("Realtime", + CoherentManagerConnection.managerConnection); + if (this.realtimeEventQueue != null) { + this.realtimeEventQueue.stop(); + newRealtime.transferListeners(this.realtimeEventQueue); + } + this.realtimeEventQueue = newRealtime; + + CoherentManagerEventQueue newStandard = new CoherentManagerEventQueue("Standard", + CoherentManagerConnection.managerConnection); + if (this.eventQueue != null) { + this.eventQueue.stop(); + newStandard.transferListeners(this.eventQueue); + } + this.eventQueue = newStandard; + } + + private void checkFeatures() throws IOException, TimeoutException { + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + + // Determine if the Bridge and Mute events are available. + final ListCommandsAction lca = new ListCommandsAction(); + ManagerResponse convertedResponse = sendAction(lca, 500); + boolean bridgeFound = false; + boolean muteAudioFound = false; + for (final String command : convertedResponse.getAttributes().keySet()) { + if (command.toLowerCase().contains("bridge")) { + bridgeFound = true; + } + if (command.toLowerCase().contains("muteaudio")) { + muteAudioFound = true; + } + } + if (CoherentManagerConnection.managerConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_13)) { + // we are really checking for the use of PJ SIP + expectRenameEvents = false; + } + this.canMuteAudio = muteAudioFound; + if (profile.getDisableBridge()) { + this.canBridge = false; + } else { + this.canBridge = bridgeFound; + } + } + + public void shutDown() { + CoherentManagerConnection.managerConnection.removeEventListener(this.eventQueue); + this.eventQueue.stop(); + try { + CoherentManagerConnection.managerConnection.logoff(); + } catch (final Exception e) { + CoherentManagerConnection.logger.debug("Manager logging off"); + CoherentManagerConnection.logger.debug(e, e); + } + } + + public boolean isBridgeSupported() { + return this.canBridge; + } + + public boolean isMuteAudioSupported() { + return this.canMuteAudio; + } + + public void removeListener(FilteredManagerListener listener) { + if (listener.getPriority() == ListenerPriority.REALTIME) + this.realtimeEventQueue.removeListener(listener); + else + this.eventQueue.removeListener(listener); + + } + + public void addListener(FilteredManagerListener listener) { + if (listener.getPriority() == ListenerPriority.REALTIME) + this.realtimeEventQueue.addListener(listener); + else + this.eventQueue.addListener(listener); + + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + required.add(ConnectEvent.class); + required.add(DisconnectEvent.class); + return required; + } + + @Override + public String getName() { + return "CoherentManagerConnection"; + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.REALTIME; + } + + @Override + public void onManagerEvent(ManagerEvent event) { + // Special handler for the connect event in case we are + // wait()ing for + // the connection to complete. This wakes the code up in the shortest + // time possible + // by notifying it of the connection. + if (event instanceof ConnectEvent) { + logger.warn("****************** Asterisk manager connection acquired **************************"); + this._reconnectLatch.countDown(); + } else if (event instanceof DisconnectEvent) { + logger.warn("****************** Asterisk manager connection lost **************************"); + // new Thread(new Runnable() + // { + // public void run() + // { + // reconnect(); + // } + // }); + } + + } + + public boolean expectRenameEvents() { + return expectRenameEvents; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventListener.java b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventListener.java new file mode 100644 index 000000000..62776b976 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventListener.java @@ -0,0 +1,14 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; + +import java.util.EventListener; + +public interface CoherentManagerEventListener extends EventListener { + /** + * This method is called when an event is received. + * + * @param event the event that has been received + */ + void onManagerEvent(ManagerEvent event); +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventQueue.java b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventQueue.java new file mode 100644 index 000000000..213520fe6 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventQueue.java @@ -0,0 +1,306 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.lock.LockableSet; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.manager.ManagerConnection; +import org.asteriskjava.manager.ManagerEventListener; +import org.asteriskjava.pbx.asterisk.wrap.events.BridgeEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.LinkEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.UnlinkEvent; +import org.asteriskjava.pbx.internal.eventQueue.EventLifeMonitor; +import org.asteriskjava.pbx.util.LogTime; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.*; + +/** + * This class provides a method of accepting, queueing and delivering manager + * events. Asterisk is very sensitive to delays in receiving events. This class + * ensures that events are received and queued rapidly. A separate thread + * dequeues them and delivers them to the manager listener. Used this queue as + * follows: manager.addEventListener(new + * CoherentManagerEventQueue(originalListener)); This affectively daisy changes + * the originalListener via our queue. + * + * @author bsutton + */ +class CoherentManagerEventQueue implements ManagerEventListener, Runnable { + private static final Log logger = LogFactory.getLog(CoherentManagerEventQueue.class); + + private final ListenerManager listeners = new ListenerManager(); + + private volatile boolean _stop = false; + + private static final int QUEUE_SIZE = 1000; + private final BlockingQueue> _eventQueue = new LinkedBlockingQueue<>( + QUEUE_SIZE); + + long suppressQueueSizeErrorUntil = 0; + + private LockableSet> globalEvents = new LockableSet<>(new HashSet<>()); + + public CoherentManagerEventQueue(String name, ManagerConnection connection) { + + connection.addEventListener(this); + + Thread _th = new Thread(this); + _th.setName("EventQueue: " + name);//$NON-NLS-1$ + _th.setDaemon(true); + _th.start(); + } + + /** + * handles manager events passed to us in our role as a listener. We queue + * the event so that it can be read, by the run method of this class, and + * subsequently passed on to the original listener. + */ + @Override + public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event) { + + // logger.error(event); + boolean wanted = false; + /** + * Dump any events we arn't interested in ASAP to minimise the + * processing overhead of these events. + */ + // Only enqueue the events that are of interest to one of our listeners. + try (LockCloser closer = this.globalEvents.withLock()) { + Class shadowEvent = CoherentEventFactory.getShadowEvent(event); + if (this.globalEvents.contains(shadowEvent)) { + wanted = true; + } + } + + if (wanted) { + // We don't support all events. + this._eventQueue.add(new EventLifeMonitor<>(event)); + if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10 + && suppressQueueSizeErrorUntil < System.currentTimeMillis()) { + suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000; + logger.error("EventQueue more than 90% full"); + } + + } + } + + @Override + public void run() { + try { + while (!this._stop) { + try { + final EventLifeMonitor elm = this._eventQueue.poll(2, + TimeUnit.SECONDS); + if (elm != null) { + // A poison queue event means its time to shutdown. + if (elm.getEvent().getClass() == PoisonQueueEvent.class) { + logger.warn("Got Poison event"); + break; + } + + final ManagerEvent iEvent = CoherentEventFactory.build(elm.getEvent()); + if (iEvent != null) { + dispatchEvent(iEvent); + elm.assessAge(); + } + } + } catch (final Exception e) { + /** + * If an exception is thrown whilst we are shutting down + * then we don't care. If it is thrown when we aren't + * shutting down then we have a problem and we need to log + * it. + */ + if (!this._stop) { + CoherentManagerEventQueue.logger.error(e, e); + } + } + + } + } finally { + logger.warn("Shutting down!"); + } + + } + + class PoisonQueueEvent extends org.asteriskjava.manager.event.ManagerEvent { + private static final long serialVersionUID = 1L; + + public PoisonQueueEvent() { + super("PoisonQueueEvent"); //$NON-NLS-1$ + } + + } + + public void stop() { + this._stop = true; + try { + this._eventQueue.put(new EventLifeMonitor(new PoisonQueueEvent())); + } catch (InterruptedException e) { + logger.error(e, e); + + } + } + + // + private final ExecutorService executors = Executors.newCachedThreadPool(); + + /** + * Events are sent here from the CoherentManagerEventQueue after being + * converted from a ManagerEvent to an ManagerEvent. This method is called + * from a dedicated thread attached to the event queue which it uses for + * dispatching events. + */ + public void dispatchEvent(final ManagerEvent event) { + if (logger.isDebugEnabled()) { + logger.debug("dispatch=" + event.toString()); //$NON-NLS-1$ + } + + // take a copy of the listeners so they can be modified whilst we + // iterate over them + // The iteration may call some long running processes. + final List listenerCopy; + try (LockCloser closer = this.listeners.withLock()) { + listenerCopy = this.listeners.getCopyAsList(); + } + + try { + final LogTime totalTime = new LogTime(); + + CountDownLatch latch = new CountDownLatch(listenerCopy.size()); + + for (final FilteredManagerListenerWrapper filter : listenerCopy) { + if (filter.requiredEvents.contains(event.getClass())) { + dispatchEventOnThread(event, filter, latch); + } else { + // this listener didn't want the event, so just decrease the + // countdown + latch.countDown(); + } + } + + if (!latch.await(2, TimeUnit.SECONDS)) { + logger.error("Timeout waiting for event to be processed " + event); + } + + if (totalTime.timeTaken() > 100) { + logger.warn("Too long to process event " + event + " time taken: " + totalTime.timeTaken()); //$NON-NLS-1$ //$NON-NLS-2$ + } + } catch (InterruptedException e) { + Thread.interrupted(); + } + } + + private void dispatchEventOnThread(final ManagerEvent event, final FilteredManagerListenerWrapper filter, + final CountDownLatch latch) { + Runnable runner = new Runnable() { + @Override + public void run() { + try { + final LogTime time = new LogTime(); + + filter._listener.onManagerEvent(event); + if (time.timeTaken() > 500) { + logger.warn("ManagerListener :" + filter._listener.getName() //$NON-NLS-1$ + + " is taken too long to process event " + event + " time taken: " + time.timeTaken()); //$NON-NLS-1$ //$NON-NLS-2$ + } + } catch (Exception e) { + logger.error(e, e); + } finally { + latch.countDown(); + } + } + }; + + executors.execute(runner); + + } + + /** + * Adds a listener which will be sent all events that its filterEvent + * handler will accept. All events are dispatch by way of a shared queue + * which is read via a thread which is shared by all listeners. Whilst poor + * performance of you listener can affect other listeners you can't affect + * the read thread which takes events from asterisk and enqueues them. + * + * @param listener + */ + public void addListener(final FilteredManagerListener listener) { + try (LockCloser closer = this.listeners.withLock()) { + this.listeners.addListener(listener); + try (LockCloser closer2 = this.globalEvents.withLock()) { + Collection> expandEvents = expandEvents(listener.requiredEvents()); + this.globalEvents.addAll(expandEvents); + } + } + logger.debug("listener added " + listener); + } + + /** + * in order to get Bridge Events, we must subscribe to Link and Unlink + * events for asterisk 1.4, so we automatically add them if the Bridge Event + * is required + * + * @param events + * @return + */ + Collection> expandEvents(Collection> events) { + Collection> requiredEvents = new HashSet<>(); + for (Class event : events) { + requiredEvents.add(event); + if (event.equals(BridgeEvent.class)) { + requiredEvents.add(UnlinkEvent.class); + requiredEvents.add(LinkEvent.class); + } + } + + return requiredEvents; + } + + public void removeListener(final FilteredManagerListener melf) { + if (melf != null) { + try (LockCloser closer = this.listeners.withLock()) { + this.listeners.removeListener(melf); + + // When we remove a listener we must unfortunately + // completely + // recalculate the set of required events. + try (LockCloser closer2 = this.globalEvents.withLock()) { + this.globalEvents.clear(); + Iterator itr = this.listeners.iterator(); + while (itr.hasNext()) { + FilteredManagerListenerWrapper readdContainer = itr.next(); + this.globalEvents.addAll(expandEvents(readdContainer._listener.requiredEvents())); + } + } + + } + + } + + } + + /** + * transfers the listeners from one queue to another. + * + * @param eventQueue + */ + public void transferListeners(CoherentManagerEventQueue eventQueue) { + try (LockCloser closer = this.listeners.withLock()) { + try (LockCloser closer2 = eventQueue.listeners.withLock()) { + Iterator itr = eventQueue.listeners.iterator(); + while (itr.hasNext()) { + FilteredManagerListenerWrapper listener = itr.next(); + + this.addListener(listener._listener); + } + eventQueue.listeners.clear(); + } + } + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/DialLocalToAgiActivity.java b/src/main/java/org/asteriskjava/pbx/internal/core/DialLocalToAgiActivity.java new file mode 100644 index 000000000..b399d795b --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/DialLocalToAgiActivity.java @@ -0,0 +1,133 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.agi.ActivityAgi; +import org.asteriskjava.pbx.agi.ActivityArrivalListener; +import org.asteriskjava.pbx.asterisk.wrap.actions.OriginateAction; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class DialLocalToAgiActivity implements Runnable, Activity { + + private EndPoint from; + private CallerID fromCallerID; + private Thread thread; + private final Log logger = LogFactory.getLog(this.getClass()); + + CountDownLatch latch = new CountDownLatch(1); + private List channels = new LinkedList<>(); + private ActivityCallback callback; + private Map channelVarsToSet; + + public DialLocalToAgiActivity(EndPoint from, CallerID fromCallerID, ActivityCallback callback, + Map channelVarsToSet) { + this.from = from; + this.fromCallerID = fromCallerID; + this.callback = callback; + this.channelVarsToSet = channelVarsToSet; + + thread = new Thread(this, "Dial " + from + " to AGI"); + thread.start(); + } + // Logger logger = LogManager.getLogger(); + + @Override + public void run() { + logger.debug("*******************************************************************************"); + logger.info("*********** begin dial local to AGI ****************"); + logger.debug("*********** ****************"); + logger.debug("*******************************************************************************"); + final AsteriskSettings settings = PBXFactory.getActiveProfile(); + + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + final OriginateAction originate = new OriginateAction(); + originate.setEndPoint(from); + originate.setContext(settings.getManagementContext()); + originate.setExten(pbx.getExtensionAgi()); + originate.setPriority(1); + originate.setCallerId(fromCallerID); + originate.setTimeout(30000); + + Map myVars = new HashMap<>(); + + if (channelVarsToSet != null) { + myVars.putAll(channelVarsToSet); + } + + originate.setVariables(myVars); + + ActivityArrivalListener listener = new ActivityArrivalListener() { + + @Override + public void channelArrived(Channel channel) { + channels.add(channel); + if (isSuccess()) { + latch.countDown(); + } + } + }; + try (AutoCloseable closeable = ActivityAgi.addArrivalListener(originate, listener);) { + + ManagerResponse response = pbx.sendAction(originate, 5000); + if (response.getResponse().compareToIgnoreCase("Success") != 0) { + callback.progress(this, ActivityStatusEnum.FAILURE, ActivityStatusEnum.FAILURE.getDefaultMessage()); + } else { + if (latch.await(5, TimeUnit.SECONDS)) { + callback.progress(this, ActivityStatusEnum.SUCCESS, ActivityStatusEnum.SUCCESS.getDefaultMessage()); + } else { + callback.progress(this, ActivityStatusEnum.FAILURE, ActivityStatusEnum.FAILURE.getDefaultMessage()); + } + } + } catch (Exception e) { + logger.error(e, e); + callback.progress(this, ActivityStatusEnum.FAILURE, ActivityStatusEnum.FAILURE.getDefaultMessage()); + + } + + } + + public void abort(final String reason) { + logger.warn("Aborting originate "); + + for (Channel channel : channels) { + PBX pbx = PBXFactory.getActivePBX(); + try { + pbx.hangup(channel); + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { + logger.error(e, e); + + } + } + latch.countDown(); + + } + + @Override + public Throwable getLastException() { + return null; + } + + @Override + public boolean isSuccess() { + return channels.size() == 2; + } + + public Channel getChannel1() { + return channels.get(0); + + } + + public Channel getChannel2() { + return channels.get(1); + + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/EndPointImpl.java b/src/main/java/org/asteriskjava/pbx/internal/core/EndPointImpl.java new file mode 100644 index 000000000..c8f09dece --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/EndPointImpl.java @@ -0,0 +1,233 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.EndPoint; +import org.asteriskjava.pbx.TechType; +import org.asteriskjava.pbx.Trunk; + +public class EndPointImpl implements EndPoint { + private static final String DELIMITER = "/"; //$NON-NLS-1$ + + final private TechType _tech; + + final private String _endPointName; + + final private String _fullyQualifiedName; + + // If true then this is an empty end point e.g. blank name and unknown tech. + final private boolean _empty; + + private Trunk _trunk; + + /** + * Creates a EndPoint from a fully qualified peer name of the form: SIP/NNN + * LOCAL/NNN TODO: the tech encoding should probably be specific to a + * particular pbx Implementation. + * + * @param fullyQualifiedPeerName + */ + public EndPointImpl(final String fullyQualifiedEndPoint) { + if (fullyQualifiedEndPoint == null) { + throw new IllegalArgumentException("The fullyQualifiedEndPoint may not be null"); //$NON-NLS-1$ + } + + final String cleaned = this.clean(fullyQualifiedEndPoint); + this._tech = TechType.getTech(cleaned); + this._endPointName = cleaned.substring(this._tech.name().length() + 1); + + if (this._tech == TechType.DIALPLAN) { + this._fullyQualifiedName = this._endPointName; + } else { + this._fullyQualifiedName = this._tech.name() + EndPointImpl.DELIMITER + this._endPointName; + } + this._empty = false; + } + + /** + * Creates a empty end point. + */ + public EndPointImpl() { + this._empty = true; + this._tech = TechType.UNKNOWN; + this._endPointName = ""; + this._fullyQualifiedName = ""; + } + + /** + * Creates an EndPoint from from a simple endpoint name and a tech. + * + * @param _tech + * @param peerName + */ + // EndPoint(String endPointName, String tech) + // { + // if (endPointName == null) + // throw new IllegalArgumentException("The endPoint Name may not be null"); + // + // if (tech == null) + // throw new IllegalArgumentException("The endPoint Tehc may not be null"); + // + // String cleaned = clean(endPointName); + // // Tech must be upper case to match the enum but + // // the simple name must be lower case to matcht the context extension + // // names. + // this.tech = Tech.valueOf(tech.toUpperCase()); + // this.endPointName = cleaned; + // } + public EndPointImpl(final TechType defaultTech, final String endPointName) { + if (endPointName == null) { + throw new IllegalArgumentException("The endPointName may not be null"); //$NON-NLS-1$ + } + + final String cleaned = this.clean(endPointName); + + if (cleaned.length() == 0) { + throw new IllegalArgumentException("The endPointName may not be empty"); //$NON-NLS-1$ + } + + // If tech is unknown then attempt to extract the tech from the + // endPointName. + if (TechType.hasTech(cleaned)) { + this._tech = TechType.getTech(cleaned); + this._endPointName = cleaned.substring(this._tech.name().length() + 1); + + } else { + this._tech = defaultTech; + this._endPointName = cleaned; + } + + if (this._tech == TechType.DIALPLAN) { + this._fullyQualifiedName = this._endPointName; + } else { + this._fullyQualifiedName = this._tech.name() + EndPointImpl.DELIMITER + this._endPointName; + } + this._empty = false; + } + + public EndPointImpl(TechType defaultTech, Trunk trunk, String endPointName) { + if (endPointName == null) { + throw new IllegalArgumentException("The endPointName may not be null"); //$NON-NLS-1$ + } + + final String cleaned = this.clean(endPointName); + + if (cleaned.length() == 0) { + throw new IllegalArgumentException("The endPointName may not be empty"); //$NON-NLS-1$ + } + + // If tech is unknown then attempt to extract the tech from the + // endPointName. + if (TechType.hasTech(cleaned)) { + throw new IllegalArgumentException("endPointName may not contain a Tech"); + + } + + this._tech = defaultTech; + this._endPointName = cleaned; + this._trunk = trunk; + + if (this._tech == TechType.DIALPLAN || this._tech == TechType.CONSOLE || this._tech == TechType.LOCAL) { + throw new IllegalArgumentException("defaultTech may not be DIALPLAN, LOCAL or CONSOLE"); + } + + this._fullyQualifiedName = this._tech.name() + EndPointImpl.DELIMITER + trunk.getTrunkAsString() + + EndPointImpl.DELIMITER + this._endPointName; + + this._empty = false; + + } + + /** + * Returns the fully qualified endPoint. + */ + @Override + public String getFullyQualifiedName() { + return this._fullyQualifiedName; + } + + public Trunk getTrunk() { + return _trunk; + } + + @Override + public boolean isSame(final EndPoint rhs) { + return this.compareTo(rhs) == 0; + } + + @Override + public int compareTo(EndPoint rhs) { + return this.getFullyQualifiedName().compareTo(rhs.getFullyQualifiedName()); + } + + @Override + public boolean isLocal() { + return this._tech == TechType.LOCAL; + } + + /** + * For the purposes of asterisk IAX and SIP are both considered SIP. + */ + @Override + public boolean isSIP() { + return this._tech == TechType.SIP || this._tech == TechType.IAX || this._tech == TechType.IAX2; + } + + public boolean isDAHDI() { + return this._tech == TechType.DAHDI; + } + + @Override + public String getSimpleName() { + return this._endPointName; + } + + @Override + public boolean isUnknown() { + return this._tech == TechType.UNKNOWN; + } + + /** + * Cleans up an endpoint name by removing all whitespace (including internal + * whitespace) as well as making the string lower case. + * + * @param _endPointName + * @return + */ + private String clean(final String _endPointName) { + String localTo = _endPointName.trim(); + + // strip all white space from within the name as some source + // pass in a formatted phone number (e.g. 03 8320 8100) + int tmp = localTo.indexOf(" "); //$NON-NLS-1$ + while (tmp != -1) { + localTo = localTo.substring(0, tmp) + localTo.substring(tmp + 1, localTo.length()); + tmp = localTo.indexOf(" "); //$NON-NLS-1$ + } + return localTo.toLowerCase(); + } + + @Override + public TechType getTech() { + return this._tech; + } + + @Override + public String toString() { + return this.getFullyQualifiedName(); + } + + @Override + public String getSIPSimpleName() { + String name; + + if (isSIP()) + name = getSimpleName(); + else + name = getFullyQualifiedName(); + return name; + } + + public boolean isEmpty() { + return this._empty; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListener.java b/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListener.java new file mode 100644 index 000000000..103ca0e61 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListener.java @@ -0,0 +1,44 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.ListenerPriority; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; + +import java.util.Set; + +/** + * Allows a object to receive Manager event notification which are pre-filtered. + * + * @author bsutton + */ +public interface FilteredManagerListener { + /** + * Provides a unique name for the listener. + * + * @return a unique name for the listener. + */ + String getName(); + + /** + * Called whenever the listener is first added and any time any listener is + * removed to refresh the list of required events. + * + * @return list of required events. + */ + Set> requiredEvents(); + + /** + * Called for each manager event that the connection receives for which the + * filterEvent returned true. + * + * @param event + */ + void onManagerEvent(T event); + + /** + * Set the listeners priority. Higher priority listeners have events + * dispatched to them before lower priority listeners. + * + * @return + */ + ListenerPriority getPriority(); +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListenerWrapper.java b/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListenerWrapper.java new file mode 100644 index 000000000..eba0c8178 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListenerWrapper.java @@ -0,0 +1,43 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.asterisk.wrap.events.BridgeEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.LinkEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.UnlinkEvent; + +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +public class FilteredManagerListenerWrapper { + FilteredManagerListener _listener; + Set> requiredEvents; + + private final static AtomicInteger seed = new AtomicInteger(); + Integer equalityBuster = seed.incrementAndGet(); + + public FilteredManagerListenerWrapper(FilteredManagerListener listener) { + this._listener = listener; + this.requiredEvents = listener.requiredEvents(); + + if (requiredEvents.contains(BridgeEvent.class)) { + // add LinkEvent and UnlinkEvent, as BridgeEvent only will + // miss some events + requiredEvents.add(LinkEvent.class); + requiredEvents.add(UnlinkEvent.class); + } + + for (Class event : requiredEvents) { + if (!CoherentEventFactory.mapEvents.values().contains(event) + && !CoherentEventFactory.mapResponses.values().contains(event)) { + throw new RuntimeException( + "The requested event type of " + event + "+isn't known by " + CoherentEventFactory.class); + } + } + } + + @Override + public String toString() { + return this._listener.getName(); + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/ListenerManager.java b/src/main/java/org/asteriskjava/pbx/internal/core/ListenerManager.java new file mode 100644 index 000000000..fb922097f --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/ListenerManager.java @@ -0,0 +1,69 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.lock.Lockable; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.*; + +public class ListenerManager extends Lockable { + private final TreeSet listeners = new TreeSet<>(new ListenerPriorityComparator()); + + Log logger = LogFactory.getLog(ListenerManager.class); + + final class ListenerPriorityComparator implements Comparator { + @Override + public int compare(FilteredManagerListenerWrapper lhs, FilteredManagerListenerWrapper rhs) { + + int result = lhs._listener.getPriority().compare(rhs._listener.getPriority()); + + if (result == 0) + result = lhs.equalityBuster.compareTo(rhs.equalityBuster); + + return result; + } + } + + public void clear() { + listeners.clear(); + } + + public int size() { + return listeners.size(); + } + + public Iterator iterator() { + return listeners.iterator(); + } + + public void addListener(FilteredManagerListener listener) { + listeners.add(new FilteredManagerListenerWrapper(listener)); + } + + List getCopyAsList() { + List list = new LinkedList<>(); + for (FilteredManagerListenerWrapper listener : listeners) { + list.add(listener); + } + + return list; + } + + boolean removeListener(FilteredManagerListener toRemove) { + boolean removed = false; + Iterator itr = listeners.iterator(); + while (itr.hasNext()) { + FilteredManagerListenerWrapper container = itr.next(); + // logger.error("Checking " + container._listener + " " + toRemove); + if (container._listener == toRemove) { + logger.debug("Removing listener " + toRemove); + itr.remove(); + removed = true; + break; + } + } + return removed; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/LiveChannelManager.java b/src/main/java/org/asteriskjava/pbx/internal/core/LiveChannelManager.java new file mode 100644 index 000000000..46a1778bd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/LiveChannelManager.java @@ -0,0 +1,352 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.lock.Lockable; +import org.asteriskjava.lock.LockableList; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.manager.TimeoutException; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.EndPoint; +import org.asteriskjava.pbx.InvalidChannelName; +import org.asteriskjava.pbx.ListenerPriority; +import org.asteriskjava.pbx.asterisk.wrap.actions.StatusAction; +import org.asteriskjava.pbx.asterisk.wrap.events.*; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.io.IOException; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * The LiveChannelManager keeps a list of all of the live channels present on an + * asterisk system. For this to work it needs to control the stream of asterisk + * events consumed by others. This need is caused by the fact that Asterisk can + * rename a channel many times after its comes up. When a channel is renamed + * Asterisk sends a rename event. After the rename event all future asterisk + * events will refer to the channel by its new name. Masquerade events pose + * further issues in that a channel can be replaced mid way through a call. The + * LiveChannelManager works with the ChannelProxy to manage this process. The + * issue is that if multiple classes are accessing the LiveChannelManager and + * those classes are consuming asterisk events form their own direct source then + * they may be behind or ahead of the LiveChannelManager in processing events. + * The result is that when attempting to access a channel by name from the + * LiveChannelManager the channel name may not match as the LiveChannelManager + * may have processed a rename event whilst the consumer may still be processing + * older events which are still referring to the channel via its old name. The + * first part of the solution is to wrap the asterisk-java events with our own + * events which pass an iChannel interface rather than a raw channel name. + * Because the iChannel interface is a handle to a channel managed via the + * LiveChannelManager then the name will be updated during the rename. To ensure + * that events are processed in an orderly fashion you MUST only obtain an event + * listener via AsteriskPBX.addListener(); The second part of the solution is + * the ChannelProxy. The ChannelProxy handles masquerading of channels where in + * a live channel is replaced with a new channel part way through a call. This + * can happen when transfering a call, parking a call or other similar actions. + * The ChannelProxy implements the iChannel interface and is affectively hidden + * from consumers of iChannels. The LiveChannelManager uses the proxy to replace + * a live channel during a masqurade event. A consumer holding an iChannel + * handle will not even be aware (and does not need to be) that the underlying + * channel has been replaced. + * + * @author bsutton + */ +public class LiveChannelManager extends Lockable implements FilteredManagerListener { + private static final Log logger = LogFactory.getLog(LiveChannelManager.class); + + /** + * A collection of all of the live proxies in the system. We monitor the + * channels and remove them as they hangup. The hash is keyed by the + * channel's name. e.g. SIP/100-000000100 + */ + private final LockableList _liveChannels = new LockableList<>(new CopyOnWriteArrayList<>()); + + public LiveChannelManager() { + CoherentManagerConnection.getInstance().addListener(this); + + } + + /** + * Find all the channels that came into existence before startup. This can't + * be done during the Constructor call, because it requires calls back to + * AsteriskPBX which isn't finished constructing until after the Constructor + * returns. + */ + void performPostCreationTasks() { + StatusAction statusAction = new StatusAction(); + try { + ResponseEvents events = CoherentManagerConnection.sendEventGeneratingAction(statusAction, 1000); + for (ResponseEvent event : events.getEvents()) { + if (event instanceof StatusEvent) { + // do nothing. Creating the events will register the + // channels, which is after all what we are trying to do. + } + } + + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { + logger.error(e, e); + } + + } + + public ChannelProxy getChannelByEndPoint(EndPoint endPoint) { + ChannelProxy connectedChannel = null; + for (final ChannelProxy channel : _liveChannels) { + if (channel.isConnectedTo(endPoint)) { + connectedChannel = channel; + break; + } + + } + return connectedChannel; + } + + public void add(ChannelProxy proxy) { + try (LockCloser closer = _liveChannels.withLock()) { + ChannelProxy index = findProxy(proxy); + if (index == null) + this._liveChannels.add(proxy); + } + logger.debug("Adding liveChannel " + proxy); + + dumpProxies(proxy, "Add"); + sanityCheck(); + + } + + private void dumpProxies(ChannelProxy proxy, String cause) { + if (logger.isDebugEnabled()) { + logger.debug("Dump of LiveChannels, cause:" + cause + ": " + proxy); //$NON-NLS-2$ + for (ChannelProxy aProxy : _liveChannels) { + logger.debug("ChannelProxy: " + aProxy); + } + } + } + + public void remove(ChannelProxy proxy) { + + ChannelProxy index = findProxy(proxy); + if (index != null) { + logger.info("Removing liveChannel " + proxy); + this._liveChannels.remove(index); + } + dumpProxies(proxy, "Removing"); + + } + + public ChannelProxy findChannel(String extendedChannelName, String uniqueID) { + ChannelProxy proxy = null; + logger.debug("Trying to find channel " + extendedChannelName + " " + uniqueID); + + String localUniqueId = uniqueID; + if (localUniqueId == null) + localUniqueId = ChannelImpl.UNKNOWN_UNIQUE_ID; + + // In order to get the 'best' match we first match each by unique id. + // Sometimes we can have two channels with the same name but + // different + + if (localUniqueId.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0) { + + for (ChannelProxy aChannel : _liveChannels) { + if (aChannel.sameUniqueID(localUniqueId)) { + proxy = aChannel; + break; + } + } + } + + // If we don't have a match from the first pass and the new uniqueID + // is unknown + // then do a search matching by name. + if (proxy == null) { + for (ChannelProxy aChannel : _liveChannels) { + + if (aChannel.isSame(extendedChannelName, localUniqueId)) { + proxy = aChannel; + break; + } + } + } + + if (proxy == null) { + logger.debug("Failed to match channel to any of..."); + for (ChannelProxy aChannel : _liveChannels) { + logger.debug(aChannel); + } + + } + + return proxy; + } + + private ChannelProxy findProxy(Channel original) { + for (ChannelProxy aChannel : _liveChannels) { + if (aChannel.isSame(original)) { + return aChannel; + } + } + return null; + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + required.add(MasqueradeEvent.class); + required.add(RenameEvent.class); + required.add(HangupEvent.class); + + // add NewChannelEvent so all channels are added to the + // LiveChannelManager + required.add(NewChannelEvent.class); + + return required; + } + + ChannelProxy findProxyById(String id) { + for (ChannelProxy aChannel : _liveChannels) { + if (("" + aChannel.getIdentity()).equals(id)) { + return aChannel; + } + } + return null; + } + + @Override + public void onManagerEvent(ManagerEvent event) { + if (event instanceof MasqueradeEvent) { + MasqueradeEvent masq = (MasqueradeEvent) event; + ChannelProxy originalIndex = findProxy(masq.getOriginal()); + ChannelProxy cloneIndex = findProxy(masq.getClone()); + if (originalIndex != null && cloneIndex != null) { + ChannelProxy originalProxy = (ChannelProxy) masq.getOriginal(); + ChannelProxy cloneProxy = (ChannelProxy) masq.getClone(); + try { + // After the masquerade the two underlying channels will + // have been switched + // between the two proxies. + // At this point the cloneProxy will be owned by a Peer + // (as they process NewChannelEvents) + // as such we cannot just discard the cloneProxy. The + // simplest solution then + // is to put the clone channel into the existing + // channel, as this is the core reason we have a proxy, + // and then put the original channel into the + // cloneProxy. At the end of this manuvour + // the Peer will still have two proxy which point to the + // two different channels. + // This is fine for the Peer as it doesn't attach any + // special meaning to any channel + // it just needs a list of all channels associated with + // the Peer. + // The original channel will shortly receive a hangup in + // which case the Peer will + // remove it from its list of channels and the Peer will + // be back to having + // one channel which will be the clone channel which is + // now the active channel + // and everyone will be happy. + originalProxy.masquerade(cloneProxy); + dumpProxies(cloneProxy, "Masquerade"); + sanityCheck(); + } catch (InvalidChannelName e) { + logger.error(e, e); + + } + + } else + logger.error("Either the clone or original channelProxy was missing during a masquerade: cloneIndex=" + + cloneIndex + " originalIndex=" + originalIndex); + + } + if (event instanceof RenameEvent) { + RenameEvent rename = (RenameEvent) event; + + ChannelProxy oldChannel = findProxy(rename.getChannel()); + if (oldChannel != null) { + try { + oldChannel.rename(rename.getNewName(), rename.getUniqueId()); + + dumpProxies(oldChannel, "RenameEvent"); + sanityCheck(); + } catch (InvalidChannelName e) { + logger.error(e, e); + } + } else { + String message = "Unable to rename channel -> Failed to find channel " + rename.getChannel(); + logger.warn(message); + dumpProxies(null, message); + } + } else if (event instanceof HangupEvent) { + // We need to process every hangup event that goes through the + // system + // as the LiveChannelManager has a Channel added for every channel + // that is created via Asterisk even if it has nothing to + // do with NJR. This is because channels are created + // whenever an event arrives before we actually can determine + // if we are interested in the event and its associated channels. + HangupEvent hangup = (HangupEvent) event; + // Yes I've seen a hangup where the channel was null, who knows + // why? + + if (hangup.getChannel() != null) { + + ChannelProxy proxy = findProxy(hangup.getChannel()); + if (proxy != null) { + logger.debug("Removing proxy " + proxy); + + this._liveChannels.remove(proxy); + logger.debug("Removing liveChannel " + proxy); + proxy.getChannel().notifyHangupListeners(hangup.getCause(), hangup.getCauseTxt()); + dumpProxies(proxy, "HangupEvent"); + } + + } else { + logger.error("Didn't remove hungup channel"); + } + } + } + + @Override + public String getName() { + return "LiveChannelManager"; + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.CRITICAL; + } + + public void sanityCheck() { + + if (logger.isDebugEnabled()) { + logger.error("Performing Sanity Check"); + Set channels = new HashSet<>(); + for (ChannelProxy channel : _liveChannels) { + if (!channels.add(channel.getChannel().getExtendedChannelName())) { + logger.error( + "Multiple channels by the name " + channel.getChannel().getExtendedChannelName() + " exist"); + for (ChannelProxy channel2 : _liveChannels) { + if (channel2.getChannel().getExtendedChannelName() + .equals(channel.getChannel().getExtendedChannelName())) { + logger.error(channel2); + } + } + Exception ex = new Exception("called from here"); + logger.error(ex, ex); + } + + } + } + } + + public List getChannelList() { + List channels = new LinkedList<>(); + channels.addAll(_liveChannels); + return channels; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/Peer.java b/src/main/java/org/asteriskjava/pbx/internal/core/Peer.java new file mode 100644 index 000000000..f06e87020 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/Peer.java @@ -0,0 +1,278 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.lock.LockableList; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.EndPoint; +import org.asteriskjava.pbx.asterisk.wrap.events.MasqueradeEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.NewChannelEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.NewStateEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.StatusEvent; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.LinkedList; + +/* + * this class tracks the status of a Peer on asterisk. T + * + * Peers are created by the PeerMonitor which also sends asterisk events to + * the peer. + * + */ + +public class Peer implements CallEndedListener { + private static final Log logger = LogFactory.getLog(Peer.class); + + private final EndPoint peerEndPoint; + + /** + * Used to track the list of channels associated with this peer. I think + * there would normally only be a single channel unless we are in the middle + * of a transfer or the phone has two calls up. + */ + private final LockableList callList = new LockableList<>(new LinkedList<>()); + + private PeerState _state = PeerState.NOTSET; + private boolean dnd = false; + + public Peer(final EndPoint endPoint) { + this.peerEndPoint = endPoint; + } + + public boolean isSame(final Peer rhs) { + return this.peerEndPoint.isSame(rhs.getEndPoint()); + } + + private CallTracker registerChannel(final Channel newChannel) { + CallTracker associatedCall = null; + boolean found = false; + try (LockCloser closer = this.callList.withLock()) { + for (final CallTracker call : this.callList) { + if (call.findChannel(newChannel) != -1) { + found = true; + associatedCall = call; + break; + } + } + if (!found) { + if (logger.isDebugEnabled()) + logger.debug("Peer adding Call: " + this.toString() + " " + newChannel.getExtendedChannelName()); //$NON-NLS-1$ //$NON-NLS-2$ + associatedCall = createCallTracker(newChannel); + this.dumpCallList(); + } + } + return associatedCall; + } + + private CallTracker createCallTracker(final Channel newChannel) { + CallTracker newCall; + try (LockCloser closer = this.callList.withLock()) { + newCall = new CallTracker(this, newChannel); + this.callList.add(newCall); + } + return newCall; + } + + public boolean getDND() { + return this.dnd; + } + + // public String getFullChannelName() + // { + // String channelName = null; + // try (LockCloser closer = Locker2.lock(this.callList) + // { + // if (this.callList.size() > 0) + // { + // channelName = this.callList.get(0).getChannelName(); + // } + // } + // + // return channelName; + // } + + public PeerState getState() { + return this._state; + } + + /** + * Determines if the given channel is connected to this peer. + * + * @param channel + * @return + */ + private boolean isConnectedToSelf(final Channel channel) { + return this.getEndPoint().isSame(channel.getEndPoint()); + } + + /** + * We handle the masqurade event is it contains channel state information. + * During a masquerade we will have two channels for the one peer, the + * original and the clone. As the clone is taking over from the original + * peer we now need to use that as true indicator of state. + * + * @param b + * @throws Exception + */ + public void handleEvent(final MasqueradeEvent b) { + if (this.isConnectedToSelf(b.getClone())) { + // At this point we will actually have two CallTrackers + // which we now need to merge into a single CallTracker. + CallTracker original = findCall(b.getOriginal()); + CallTracker clone = findCall(b.getClone()); + if (original != null && clone != null) { + clone.mergeCalls(original); + clone.setState(b.getCloneState()); + this.evaluateState(); + } else + logger.warn("When processing masquradeEvent we could not find the expected calls. event=" //$NON-NLS-1$ + + b.toString() + " original=" + original + " clone=" + clone); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + /** + * When a new channel comes up associated it with the peer. Be warned a peer + * can have multiple calls associated with it. + * + * @param b + * @throws Exception + */ + public void handleEvent(final NewChannelEvent b) { + // Very occasionally we get a null channel which we can't do anything + // with so just throw the event away. + // If we get a Console/dsp channel name it means that someone has + // dialled from the asterisk + // console. We just ignore these. + if ((b.getChannel() == null) || (b.getChannel().isConsole())) { + return; + } + + if (this.isConnectedToSelf(b.getChannel())) { + CallTracker call = this.registerChannel(b.getChannel()); + if (call != null) { + call.setState(b.getChannelState()); + this.evaluateState(); + } + } + } + + public void handleEvent(final NewStateEvent b) { + if (this.isConnectedToSelf(b.getChannel())) { + CallTracker call = this.registerChannel(b.getChannel()); + if (call != null) { + call.setState(b.getChannelState()); + this.evaluateState(); + } + } + } + + public void handleEvent(final StatusEvent b) { + final Channel channel = b.getChannel(); + if (this.isConnectedToSelf(channel)) { + ((ChannelProxy) channel).getRealChannel().markChannel(); + + CallTracker call = findCall(channel); + if (call != null) { + call.setState(b.getState()); + this.evaluateState(); + } + } + } + + private CallTracker findCall(Channel channel) { + CallTracker result = null; + try (LockCloser closer = this.callList.withLock()) { + for (CallTracker call : this.callList) { + if (call.findChannel(channel) != -1) { + result = call; + break; + } + } + + } + return result; + } + + public void setDND(final boolean on) { + this.dnd = on; + } + + public void startSweep() { + Peer.logger.debug("Starting sweep for " + this.peerEndPoint.getFullyQualifiedName());//$NON-NLS-1$ + try (LockCloser closer = this.callList.withLock()) { + for (final CallTracker call : this.callList) { + call.startSweep(); + } + } + } + + public void endSweep() { + Peer.logger.debug("Ending sweep for " + this.peerEndPoint.getFullyQualifiedName());//$NON-NLS-1$ + try (LockCloser closer = this.callList.withLock()) { + for (final CallTracker call : this.callList) { + call.endSweep(); + } + } + this.evaluateState(); + } + + /** + * Called each time the state of a call changes to determine the Peers + * overall state. + */ + private void evaluateState() { + try (LockCloser closer = this.callList.withLock()) { + // Get the highest prioirty state from the set of calls. + PeerState newState = PeerState.NOTSET; + for (CallTracker call : this.callList) { + if (call.getState().getPriority() > newState.getPriority()) + newState = call.getState(); + } + + this._state = newState; + } + } + + public EndPoint getEndPoint() { + return this.peerEndPoint; + } + + @Override + public String toString() { + return this.getEndPoint().toString(); + } + + private void dumpCallList() { + if (logger.isDebugEnabled()) { + Peer.logger.debug("Peer: dump CallList:" + this); //$NON-NLS-1$ + for (final CallTracker call : this.callList) { + call.dumpChannelList(); + } + } + } + + @Override + public void callEnded(CallTracker call) { + boolean found = false; + try (LockCloser closer = this.callList.withLock()) { + for (final CallTracker aCall : this.callList) { + if (call == aCall) { + found = true; + if (logger.isDebugEnabled()) + logger.debug("peer Removing call " + call); //$NON-NLS-1$ + this.callList.remove(call); + this.evaluateState(); + this.dumpCallList(); + break; + } + } + if (!found) { + logger.error("Error call not found removing call from peer: call=" + call + " peer=" + this); //$NON-NLS-1$ //$NON-NLS-2$ + this.dumpCallList(); + } + } + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/PeerMonitor.java b/src/main/java/org/asteriskjava/pbx/internal/core/PeerMonitor.java new file mode 100644 index 000000000..05d9c1a25 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/PeerMonitor.java @@ -0,0 +1,315 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.lock.LockableList; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.asterisk.wrap.actions.SipPeersAction; +import org.asteriskjava.pbx.asterisk.wrap.actions.StatusAction; +import org.asteriskjava.pbx.asterisk.wrap.events.*; +import org.asteriskjava.pbx.internal.managerAPI.EventListenerBaseClass; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +/* + * this class tracks the status of all peers on asterisk. + */ +public class PeerMonitor extends EventListenerBaseClass implements Runnable { + + private static final Log logger = LogFactory.getLog(PeerMonitor.class); + + LockableList peerList = new LockableList<>(new LinkedList<>()); + + boolean initSip = false; + + private final Thread markAndSweepThread; + + private static PeerMonitor self; + + private static NewExtensionListener listener; + + /** + * needs to notify PhoneBookDisplayController.getInstance().addExtensions(); + * + * @param _listener + */ + public synchronized static void init(final NewExtensionListener _listener) { + PeerMonitor.listener = _listener; + + if (PeerMonitor.self == null) { + PeerMonitor.self = new PeerMonitor(); + } else if (_listener != null) { + logger.error("Call to PeerMonitor.init, but it's already initialized. Listener will not be set"); + } + } + + public static synchronized PeerMonitor getInstance() { + if (PeerMonitor.self == null) { + throw new IllegalStateException("You must call PeerMonitor.init()"); //$NON-NLS-1$ + } + return PeerMonitor.self; + } + + private PeerMonitor() { + super("PeerMonitor", PBXFactory.getActivePBX()); //$NON-NLS-1$ + this.peerList = new LockableList<>(new LinkedList<>()); + this.startListener(); + this.addSipsToMonitor(); + try { + if (PeerMonitor.listener != null) { + PeerMonitor.listener.newExtension(); + } else { + logger.warn("Peer monitor listener is null"); + } + } catch (final Exception e) { + PeerMonitor.logger.error(e, e); + } + + this.markAndSweepThread = new Thread(this); + this.markAndSweepThread.setName("PeerMonitor-MarkAndSweep"); //$NON-NLS-1$ + this.markAndSweepThread.setDaemon(true); + this.markAndSweepThread.start(); + + } + + public void addSipsToMonitor() { + /* + * request asterisk to send a list of sip peers. The monitor will + * dynamically add the peers to its list + */ + this.initSip = false; + + final StatusAction sa = new StatusAction(); + final SipPeersAction t = new SipPeersAction(); + try { + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + pbx.sendAction(t, 5000); + pbx.sendAction(sa, 5000); + } catch (final Exception e) { + PeerMonitor.logger.error(e, e); + } + + } + + public Peer registerPeer(final Channel newChannel) { + final Peer peer = this.registerPeer(newChannel.getEndPoint()); + return peer; + } + + public Peer registerPeer(final EndPoint endPoint) { + if (endPoint.isLocal()) { + return null; + } + + try (LockCloser closer = peerList.withLock()) { + Peer peer = this.findPeer(endPoint); + if (peer == null) { + peer = new Peer(endPoint); + this.peerList.add(peer); + } + return peer; + } + + } + + public Peer findPeer(final EndPoint peerEndPoint) { + Peer found = null; + + try (LockCloser closer = peerList.withLock()) { + for (final Peer peer : this.peerList) { + if (peer.getEndPoint().isSame(peerEndPoint)) { + found = peer; + break; + } + } + } + return found; + } + + public Iterator getIterator() { + try (LockCloser closer = peerList.withLock()) { + final List clone = new LinkedList(this.peerList); + return clone.iterator(); + } + + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + required.add(NewChannelEvent.class); + required.add(PeerStatusEvent.class); + required.add(PeerEntryEvent.class); + required.add(PeerlistCompleteEvent.class); + required.add(NewStateEvent.class); + required.add(StatusEvent.class); + required.add(StatusCompleteEvent.class); + required.add(DndStateEvent.class); + + return required; + } + + @Override + public void onManagerEvent(final ManagerEvent event) { + /* + * This function is called from the base class. Here we process events + * we are interested in. + */ + + if (event instanceof PeerStatusEvent) { + this.handleEvent((PeerStatusEvent) event); + } else if (event instanceof PeerlistCompleteEvent) { + this.handleEvent((PeerlistCompleteEvent) event); + } else if (event instanceof PeerEntryEvent) { + this.handleEvent((PeerEntryEvent) event); + } else if (event instanceof NewChannelEvent) { + this.handleEvent((NewChannelEvent) event); + } else if (event instanceof MasqueradeEvent) { + this.handleEvent((MasqueradeEvent) event); + } else if (event instanceof StatusEvent) { + this.handleEvent((StatusEvent) event); + } else if (event instanceof StatusCompleteEvent) { + this.handleEvent((StatusCompleteEvent) event); + } else if (event instanceof NewStateEvent) { + this.handleEvent((NewStateEvent) event); + } + } + + private void handleEvent(NewStateEvent event) { + try (LockCloser closer = peerList.withLock()) { + for (Peer peer : this.peerList) { + peer.handleEvent(event); + } + } + } + + private void handleEvent(final NewChannelEvent event) { + try (LockCloser closer = peerList.withLock()) { + for (Peer peer : this.peerList) { + peer.handleEvent(event); + } + } + } + + private void handleEvent(final MasqueradeEvent event) { + try (LockCloser closer = peerList.withLock()) { + for (Peer peer : this.peerList) { + peer.handleEvent(event); + } + } + } + + private void handleEvent(final StatusEvent event) { + try (LockCloser closer = peerList.withLock()) { + for (Peer peer : this.peerList) { + peer.handleEvent(event); + } + } + } + + private void handleEvent(final PeerEntryEvent event) { + final EndPoint endPoint = event.getPeer(); + this.registerPeer(endPoint); + } + + private void handleEvent(final PeerlistCompleteEvent b) { + this.initSip = true; + } + + /** + * @param event + */ + private void handleEvent(final PeerStatusEvent event) { + this.registerPeer(event.getPeer()); + } + + /** + * We receive the StatusComplete event once the Mark and Sweep channel + * operation has completed. We now call endSweep which will remove any + * channels that were not marked during the operation. + * + * @param event + */ + private void handleEvent(final StatusCompleteEvent event) { + try (LockCloser closer = peerList.withLock()) { + for (final Peer peer : this.peerList) { + peer.endSweep(); + } + } + PeerMonitor.logger.debug("Channel Mark and Sweep complete"); //$NON-NLS-1$ + } + + boolean isInitialized() { + return this.initSip; + } + + public void stop() { + this.close(); + + } + + /************************************************************************************** + * Mark and Sweep logic follows + **************************************************************************************/ + + /** + * Runs the mark and sweep operation every 120 seconds on all channels to + * clean up any channels that have died and for which (for some reason) we + * missed the hangup event. + */ + @Override + public void run() { + while (true) { + try { + Thread.sleep(120000); + PeerMonitor.getInstance().startSweep(); + } catch (final InterruptedException e) { + PeerMonitor.logger.error(e, e); + + } + } + + } + + /** + * Check every channel to make certain they are still active. We do this in + * case we missed a hangup event along the way somewhere. This allows us to + * cleanup any old channels. We start by clearing the mark on all channels + * and then generates a Asterisk status message for every active channel. At + * the end of the process any channels which haven't been marked are then + * discarded. + */ + public void startSweep() { + PeerMonitor.logger.debug("Starting channel mark and sweep"); //$NON-NLS-1$ + + // Mark every channel as 'clearing' + try (LockCloser closer = peerList.withLock()) { + for (final Peer peer : this.peerList) { + peer.startSweep(); + } + } + + /** + * Request Asterisk to send us a status update for every channel. + */ + final StatusAction sa = new StatusAction(); + try { + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + pbx.sendAction(sa, 5000); + } catch (final Exception e) { + PeerMonitor.logger.error(e, e); + } + + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.HIGH; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/PeerState.java b/src/main/java/org/asteriskjava/pbx/internal/core/PeerState.java new file mode 100644 index 000000000..b7405a0df --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/core/PeerState.java @@ -0,0 +1,98 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.asterisk.wrap.events.ChannelState; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public enum PeerState { + DOWN(1, "Down", "OnHook", false), //$NON-NLS-1$ //$NON-NLS-2$ + UP(2, "Up", "OnPhone", true), //$NON-NLS-1$ //$NON-NLS-2$ + UNKNOWN(0, "Unknown", "Unknown", false), //$NON-NLS-1$ //$NON-NLS-2$ + NOTSET(0, "Not Set", "", false), //$NON-NLS-1$ //$NON-NLS-2$ + UNMONITORED(0, "Unmonitored", "Unmonitored", true), //$NON-NLS-1$ //$NON-NLS-2$ + DND(3, "DND", "DND", true), //$NON-NLS-1$ //$NON-NLS-2$ + RINGING(4, "Ringing", "Ringing", true), //$NON-NLS-1$ //$NON-NLS-2$ + OFF_LINE(1, "Off line", "Offline", true), //$NON-NLS-1$ //$NON-NLS-2$ + UNREGISTERED(0, "Unregistered", "Unregistered", true), //$NON-NLS-1$ //$NON-NLS-2$ + REGISTERED(0, "Registered", "Registered", false), //$NON-NLS-1$ //$NON-NLS-2$ + BUSY(2, "Busy", "Busy", true), //$NON-NLS-1$//$NON-NLS-2$ + RING(4, "Ring", "Dialing", true), //$NON-NLS-1$ //$NON-NLS-2$ + EXTERNAL(0, "External", "External", false);//$NON-NLS-1$ //$NON-NLS-2$ + + private static final Log logger = LogFactory.getLog(PeerState.class); + + final String _asteriskStateName; + + final String label; + + /** + * Controls whether the state should be displayed to the end user or just + * hidden. + */ + private boolean _visible; + + /** + * The priority ranks the PeerStates relative to each other. When a Peer has + * multiple active calls we need to display the call state from the call + * with the highest priority. e.g. If one call is UP and another is RINGING + * then we need to display the RINGING state as this is more interesting. + */ + private int _priority; + + public static PeerState valueByName(final String value) { + PeerState status = NOTSET; + + for (PeerState aState : PeerState.values()) { + + if (aState.getAsteriskStateName().compareToIgnoreCase(value) == 0) { + status = aState; + break; + } + } + return status; + } + + private String getAsteriskStateName() { + return this._asteriskStateName; + } + + public static PeerState valueByChannelState(final ChannelState state) { + PeerState status = NOTSET; + + for (PeerState aState : PeerState.values()) { + + if (aState.getAsteriskStateName().compareToIgnoreCase(state.name()) == 0) { + status = aState; + break; + } + } + + if (status == NOTSET) + logger.warn("Unknown channelState: " + state + " recieved", new Throwable("Unknown channelState")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + return status; + } + + PeerState(int priority, final String asteriskStateName, final String label, boolean visible) { + this._asteriskStateName = asteriskStateName; + this.label = label; + this._visible = visible; + this._priority = priority; + } + + public String getLabel() { + return this.label; + } + + @Override + public String toString() { + return this.label; + } + + public boolean isVisible() { + return this._visible; + } + + public int getPriority() { + return this._priority; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/eventQueue/EventLifeMonitor.java b/src/main/java/org/asteriskjava/pbx/internal/eventQueue/EventLifeMonitor.java new file mode 100644 index 000000000..b2d62d59c --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/eventQueue/EventLifeMonitor.java @@ -0,0 +1,34 @@ +package org.asteriskjava.pbx.internal.eventQueue; + +import org.asteriskjava.pbx.util.LogTime; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class EventLifeMonitor { + private static final Log logger = LogFactory.getLog(EventLifeMonitor.class); + + /* + * this class is used to hold an event while its in the queue and calculate + * how long it spent in the que before being processed. + */ + + private final T theEvent; + + private final LogTime age; + + public EventLifeMonitor(final T event) { + this.theEvent = event; + this.age = new LogTime(); + } + + public void assessAge() { + if (this.age.timeTaken() > 2000) { + EventLifeMonitor.logger.warn("event age : " + this.age.timeTaken()); //$NON-NLS-1$ + } + + } + + public T getEvent() { + return this.theEvent; + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Connector.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Connector.java new file mode 100644 index 000000000..80435bccd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Connector.java @@ -0,0 +1,91 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.manager.AuthenticationFailedException; +import org.asteriskjava.manager.ManagerConnection; +import org.asteriskjava.manager.ManagerConnectionFactory; +import org.asteriskjava.manager.TimeoutException; +import org.asteriskjava.pbx.AsteriskSettings; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.UnknownHostException; + +/* + * this class is a very thin wrapper around the manager connection class + */ +public class Connector { + private ManagerConnection managerConnection; + private static final Log logger = LogFactory.getLog(Connector.class); + + /** + * Establishes a Asterisk ManagerConnection as well as performing the + * 'login' required by Asterisk. + * + * @param asteriskSettings + * @return + * @throws IOException + * @throws AuthenticationFailedException + * @throws TimeoutException + * @throws IllegalStateException + */ + public ManagerConnection connect(final AsteriskSettings asteriskSettings) + throws IOException, AuthenticationFailedException, TimeoutException, IllegalStateException { + checkIfAsteriskRunning(asteriskSettings); + this.makeConnection(asteriskSettings); + return this.managerConnection; + } + + /** + * This method will try to make a simple tcp connection to the asterisk + * manager to establish it is up. We do this as the default makeConnection + * doesn't have a timeout and will sit trying to connect for a minute or so. + * By using method when the user realises they have a problem on start up + * they can go to the asterisk panel. Fix the problem and then we can retry + * with the new connection settings within a couple of seconds rather than + * waiting a minute for a timeout. + * + * @param asteriskSettings + * @throws UnknownHostException + * @throws IOException + */ + private void checkIfAsteriskRunning(AsteriskSettings asteriskSettings) throws UnknownHostException, IOException { + try (Socket socket = new Socket()) { + socket.setSoTimeout(2000); + + InetSocketAddress asteriskHost = new InetSocketAddress(asteriskSettings.getAsteriskIP(), + asteriskSettings.getManagerPortNo()); + socket.connect(asteriskHost, 2000); + } + + } + + /** + * @param socketReadTimeout + * @throws IOException + * @throws AuthenticationFailedException + * @throws TimeoutException + * @throws InsufficientPermissionsException + * @throws IllegalStateException + */ + private void makeConnection(final AsteriskSettings asteriskSettings) + throws IOException, AuthenticationFailedException, TimeoutException, IllegalStateException { + ManagerConnectionFactory factory = null; + if (asteriskSettings.getManagerPortNo() == -1) { + Connector.logger.debug("Using default port 5038."); //$NON-NLS-1$ + factory = new ManagerConnectionFactory(asteriskSettings.getAsteriskIP(), asteriskSettings.getManagerUsername(), + asteriskSettings.getManagerPassword()); + } else { + factory = new ManagerConnectionFactory(asteriskSettings.getAsteriskIP(), asteriskSettings.getManagerPortNo(), + asteriskSettings.getManagerUsername(), asteriskSettings.getManagerPassword()); + + } + + this.managerConnection = factory.createManagerConnection(); + // this.managerConnection.setSocketReadTimeout(socketReadTimeout); + // this.managerConnection.setSocketTimeout(socketReadTimeout); + this.managerConnection.login(); + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Dial.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Dial.java new file mode 100644 index 000000000..bf0f98162 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Dial.java @@ -0,0 +1,146 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.agi.AgiChannelActivityDial; +import org.asteriskjava.pbx.asterisk.wrap.events.*; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +public class Dial extends EventListenerBaseClass { + private static final Log logger = LogFactory.getLog(Dial.class); + + private final OriginateResult result[] = new OriginateResult[2]; + + private CountDownLatch _latch; + + public Dial(final String descriptiveName) { + super(descriptiveName, PBXFactory.getActivePBX()); + } + + /** + * Dials the targetEndPoint connecting the call to the localHandset. The + * dial is done in two parts as we need to set the auto answer header + * differently for each phone. For the localHandset we set auto answer on, + * whilst for the remote targetEndPoint we MUST not auto answer the phone. + * + * @param localHandset the users handset we are going to dial from (e.g. + * receptionist phone). + * @param targetEndPoint - the remote handset we are going to connect the + * localHandset to. + * @param dialContext - context we are going to dial from. + * @param hideCallerId + * @param channelVarsToSet + * @param callerId - the callerID to display on the targetEndPoint. + * @return + * @throws PBXException + */ + public OriginateResult[] dial(final NewChannelListener listener, final EndPoint localHandset, + final EndPoint targetEndPoint, final String dialContext, final CallerID callerID, final boolean hideCallerId, + Map channelVarsToSet, String dialOptions) throws PBXException { + final PBX pbx = PBXFactory.getActivePBX(); + + try (final OriginateToExtension originate = new OriginateToExtension(listener)) { + + this.startListener(); + + // First bring the operator's handset up and connect it to the + // 'njr-dial' extension where they can + // wait whilst we complete the second leg + final OriginateResult trcResult = originate.originate(localHandset, pbx.getExtensionAgi(), true, + ((AsteriskPBX) pbx).getManagementContext(), callerID, null, hideCallerId, channelVarsToSet); + + this.result[0] = trcResult; + if (trcResult.isSuccess()) { + + try { + if (targetEndPoint instanceof HoldAtAgi) { + if (trcResult.getChannel().waitForChannelToReachAgi(30, TimeUnit.SECONDS)) { + // call is now in agi + System.out.println("Call is in agi"); + } else { + // call never reached agi + System.out.println("Call never reached agi"); + } + } else { + + // The call is now up, so connect it to + // the + // destination. + this._latch = new CountDownLatch(1); + + trcResult.getChannel().setCurrentActivityAction( + new AgiChannelActivityDial(targetEndPoint.getFullyQualifiedName(), dialOptions)); + + if (!this._latch.await(30, TimeUnit.SECONDS)) { + logger.warn("Timeout waiting for channel. " + trcResult.getChannel()); + } + + } + } catch (final InterruptedException e) { + // noop + } + } + + return this.result; + } finally { + this.close(); + } + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + required.add(BridgeEvent.class); + // bridge event is a subclass of linkevent, so we need link & unlink in + // our list of events to support Asterisk 1.4 + required.add(LinkEvent.class); + required.add(UnlinkEvent.class); + required.add(HangupEvent.class); + + return required; + } + + @Override + public void onManagerEvent(final ManagerEvent event) { + if (event instanceof BridgeEvent) { + final BridgeEvent link = (BridgeEvent) event; + + if ((link.getChannel1() != null) && (this.result[0] != null) + && link.getChannel1().isSame(this.result[0].getChannel())) { + + Dial.logger.debug("Dial out bridged on " + link.getChannel1() + " to " + link.getChannel2()); //$NON-NLS-1$ //$NON-NLS-2$ + this.result[1] = new OriginateResult(); + + this.result[1].setChannelData(link.getChannel2()); + this._latch.countDown(); + } + } else if (event instanceof HangupEvent) { + final HangupEvent hangup = (HangupEvent) event; + final Channel hangupChannel = hangup.getChannel(); + + if (Dial.logger.isDebugEnabled()) { + Dial.logger.debug("hangup :" + hangupChannel); //$NON-NLS-1$ + Dial.logger.debug("channel 0:" + this.result[0]); //$NON-NLS-1$ + Dial.logger.debug("channel 1:" + this.result[1]); //$NON-NLS-1$ + } + if ((this.result[0] != null) && this.result[0].isSuccess() && hangupChannel.isSame(this.result[0].getChannel())) { + if (this._latch != null) { + this._latch.countDown(); + } + } + } + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/DialToAgi.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/DialToAgi.java new file mode 100644 index 000000000..51bf9a03e --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/DialToAgi.java @@ -0,0 +1,120 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.asterisk.wrap.events.HangupEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashSet; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +public class DialToAgi extends EventListenerBaseClass { + private static final Log logger = LogFactory.getLog(DialToAgi.class); + + private final OriginateResult result[] = new OriginateResult[2]; + + private volatile boolean hangupDetected = false; + + private OriginateToExtension originator; + + public DialToAgi(final String descriptiveName) { + super(descriptiveName, PBXFactory.getActivePBX()); + } + + /** + * Dials the targetEndPoint connecting the call to the localHandset. The + * dial is done in two parts as we need to set the auto answer header + * differently for each phone. For the localHandset we set auto answer on, + * whilst for the remote targetEndPoint we MUST not auto answer the phone. + * + * @param localHandset the users handset we are going to dial from (e.g. + * receptionist phone). + * @param targetEndPoint - the remote handset we are going to connect the + * localHandset to. + * @param dialContext - context we are going to dial from. + * @param hideCallerId + * @param channelVarsToSet + * @param callerId - the callerID to display on the targetEndPoint. + * @return + * @throws PBXException + */ + public OriginateResult[] dial(final NewChannelListener listener, final EndPoint localHandset, + final AgiChannelActivityAction action, final CallerID callerID, Integer timeout, final boolean hideCallerId, + Map channelVarsToSet) throws PBXException, InterruptedException { + final PBX pbx = PBXFactory.getActivePBX(); + + try (final OriginateToExtension originate = new OriginateToExtension(listener)) { + this.startListener(); + originator = originate; + + // First bring the operator's handset up and connect it to the + // 'njr-dial' extension where they can + // wait whilst we complete the second leg + final OriginateResult trcResult = originate.originate(localHandset, pbx.getExtensionAgi(), true, + ((AsteriskPBX) pbx).getManagementContext(), callerID, timeout, hideCallerId, channelVarsToSet); + + this.result[0] = trcResult; + if (trcResult.isSuccess()) { + if (trcResult.getChannel() != null) { + trcResult.getChannel().setCurrentActivityAction(action); + if (trcResult.getChannel().waitForChannelToReachAgi(30, TimeUnit.SECONDS)) { + logger.info("Call reached AGI"); + } else { + logger.error("Call never reached agi"); + } + } else { + logger.error("Call never reached agi"); + } + } else { + logger.warn("Originate failed: " + trcResult.getAbortReason()); + } + logger.info("Hangup status is " + hangupDetected); + + return this.result; + } finally { + this.close(); + } + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + required.add(HangupEvent.class); + + return required; + } + + @Override + public void onManagerEvent(final ManagerEvent event) { + if (event instanceof HangupEvent) { + final HangupEvent hangup = (HangupEvent) event; + final Channel hangupChannel = hangup.getChannel(); + + if (DialToAgi.logger.isDebugEnabled()) { + DialToAgi.logger.debug("hangup :" + hangupChannel); //$NON-NLS-1$ + DialToAgi.logger.debug("channel 0:" + this.result[0]); //$NON-NLS-1$ + DialToAgi.logger.debug("channel 1:" + this.result[1]); //$NON-NLS-1$ + } + if ((this.result[0] != null) && this.result[0].isSuccess() && hangupChannel.isSame(this.result[0].getChannel())) { + hangupDetected = true; + } + } + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + public void abort() { + if (originator != null) { + originator.abort("user abort"); + } else { + logger.error("Call to abort, but it doesn't look like the Dial had started yet"); + } + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/EventListenerBaseClass.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/EventListenerBaseClass.java new file mode 100644 index 000000000..2e2e0e8e4 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/EventListenerBaseClass.java @@ -0,0 +1,79 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.lock.Lockable; +import org.asteriskjava.pbx.PBX; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.pbx.internal.core.FilteredManagerListener; + +/* + * This is the basic abstract event listener class. It implements a thread + * and queue. + */ +public abstract class EventListenerBaseClass extends Lockable implements FilteredManagerListener, AutoCloseable { + + private final String name; + private final PBX pbx; + + protected EventListenerBaseClass(final String descriptiveName, PBX iPBX) { + this.name = descriptiveName; + this.pbx = iPBX; + } + + @Override + public String getName() { + return this.name; + } + + /** + * we have to take the pbx as an arg here as we sometimes this is called + * during the creation phase of for the pbx, and the factory can't give out + * the pbx at that point event though it is initialised. + */ + + public void startListener() { + + ((AsteriskPBX) pbx).addListener(this); + } + + /** + * Stops the listener. + */ + @Override + public void close() { + ((AsteriskPBX) pbx).removeListener(this); + } + + /** + * This class exists so we can start and stop the listener using the new + * try-with-resource of JRE7. Whilst the parent class is Autoclosable we + * can't always use it directly in a try block (e.g. it is the base class). + * In those cases you can use this class. + * + * @author bsutton + */ + public class AutoClose implements java.lang.AutoCloseable { + EventListenerBaseClass listener; + + public AutoClose(final EventListenerBaseClass listener) { + this(listener, true); + } + + public AutoClose(final EventListenerBaseClass listener, final boolean sendEvents) { + if (listener == null) { + throw new IllegalArgumentException("listener may not be null"); //$NON-NLS-1$ + } + + this.listener = listener; + if (sendEvents) { + listener.startListener(); + } + } + + @Override + public void close() { + this.listener.close(); + + } + } +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/HoldAtAgi.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/HoldAtAgi.java new file mode 100644 index 000000000..5a29a3a36 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/HoldAtAgi.java @@ -0,0 +1,59 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.pbx.EndPoint; +import org.asteriskjava.pbx.TechType; + +public class HoldAtAgi implements EndPoint { + + @Override + public int compareTo(EndPoint arg0) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean isSame(EndPoint rhs) { + return rhs instanceof HoldAtAgi; + } + + @Override + public boolean isLocal() { + return false; + } + + @Override + public boolean isSIP() { + return false; + } + + @Override + public String getFullyQualifiedName() { + return ""; + } + + @Override + public String getSimpleName() { + return ""; + } + + @Override + public String getSIPSimpleName() { + return ""; + } + + @Override + public boolean isUnknown() { + return false; + } + + @Override + public TechType getTech() { + return null; + } + + @Override + public boolean isEmpty() { + return true; + } + // Logger logger = LogManager.getLogger(); +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/MonitorCall.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/MonitorCall.java new file mode 100644 index 000000000..af751a4fd --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/MonitorCall.java @@ -0,0 +1,48 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.pbx.Call; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.asterisk.wrap.actions.MonitorAction; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.concurrent.atomic.AtomicLong; + +public class MonitorCall { + private static final Log logger = LogFactory.getLog(MonitorCall.class); + + private static final AtomicLong id = new AtomicLong(); + + private String file = null; + + public MonitorCall(final Call call) { + super(); + + try { + this.setFile(); + final MonitorAction monitorAction = new MonitorAction(call.getRemoteParty(), this.file, "gsm", true); + + AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + pbx.sendAction(monitorAction, 1000); + + } catch (final Exception e) { + MonitorCall.logger.error(e, e); + } + } + + public String getFilename() { + return this.file + ".gsm"; + } + + private void setFile() { + long no = System.currentTimeMillis(); + no = no / 1000; + final String unq = Long.toHexString(no); + + this.file = "njr" + unq + "-" + MonitorCall.id.incrementAndGet(); + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateBaseClass.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateBaseClass.java new file mode 100644 index 000000000..0ba6c5eaa --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateBaseClass.java @@ -0,0 +1,406 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.live.ManagerCommunicationException; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.asterisk.wrap.actions.OriginateAction; +import org.asteriskjava.pbx.asterisk.wrap.events.*; +import org.asteriskjava.pbx.asterisk.wrap.response.ManagerResponse; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +public abstract class OriginateBaseClass extends EventListenerBaseClass { + + /* + * this class generates and issues ActionEvents to asterisk through the + * manager. This is the asterisk coal face. + */ + protected static final Log logger = LogFactory.getLog(OriginateBaseClass.class); + + private volatile String originateID; + + volatile private boolean originateSuccess; + + private final Channel monitorChannel1; + + private boolean hungup = false; + + private Channel newChannel; + + private final Channel monitorChannel2; + + private final OriginateResult result; + + Exception ex = new Exception("Created here"); + + /** + * The following two variables together are used to determine if the + * originated channel has come up. This is to overcome the problem that the + * OriginateResponseEvent and the NewChannelEvent can occur in any order + * (although the NewChannelEvent will occur first in most circumstances). + * Note: we get many NewChannelEvents but we are only interested in a very + * specific one. + */ + // Used to track if the originate event has been seen. + private boolean originateSeen = false; + + // Used to track if the new (final) channel has been seen. + private boolean channelSeen = false; + + private final NewChannelListener listener; + + private final CountDownLatch originateLatch = new CountDownLatch(1); + + private final AsteriskPBX pbx; + + private String channelId; + + private final AtomicInteger managerEventsSeen = new AtomicInteger(); + + protected OriginateBaseClass(final NewChannelListener listener, final Channel monitor, final Channel monitor2) { + super("NewOrginateClass", PBXFactory.getActivePBX()); + pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + this.listener = listener; + this.monitorChannel1 = monitor; + this.monitorChannel2 = monitor2; + this.result = new OriginateResult(); + + } + + private static final AtomicLong originateSeed = new AtomicLong(); + + /** + * @param local + * @param target + * @param myVars + * @param callerId the caller id to set when initiating this call. + * @param hideCallerId + * @param context + * @return + */ + OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap myVars, + final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context) { + OriginateBaseClass.logger.info("originate called"); + this.originateSeen = false; + this.channelSeen = false; + + if (this.hungup) { + // the monitored channel already hungup so just return false and + // shutdown + return null; + } + + OriginateBaseClass.logger.info("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$ + + " vars " + myVars); + ManagerResponse response = null; + + final AsteriskSettings settings = PBXFactory.getActiveProfile(); + + final OriginateAction originate = new OriginateAction(); + this.originateID = originate.getActionId(); + + channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet(); + originate.setChannelId(channelId); + + Integer localTimeout = timeout; + + if (timeout == null) { + localTimeout = 30000; + try { + localTimeout = settings.getDialTimeout() * 1000; + } catch (final Exception e) { + OriginateBaseClass.logger.error("Invalid dial timeout value"); + } + } + + // Whilst the originate document says that it takes a channel it + // actually takes an + // end point. I haven't check but I'm skeptical that you can actually + // originate to + // a channel as the doco talks about 'dialing the channel'. I suspect + // this + // may be part of asterisk's sloppy terminology. + if (local.isLocal()) { + originate.setEndPoint(local); + originate.setOption("/n"); + } else { + originate.setEndPoint(local); + } + + originate.setContext(context); + originate.setExten(target); + originate.setPriority(1); + + // Set the caller id. + if (hideCallerId) { + // hide callerID + originate.setCallingPres(32); + } else { + originate.setCallerId(callerID); + } + + originate.setVariables(myVars); + originate.setAsync(true); + originate.setTimeout(localTimeout); + + try { + // Just add us as an asterisk event listener. + this.startListener(); + + response = pbx.sendAction(originate, localTimeout); + OriginateBaseClass.logger.info("Originate.sendAction completed"); + if (response.getResponse().compareToIgnoreCase("Success") != 0) { + OriginateBaseClass.logger + .error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$ + throw new ManagerCommunicationException(response.getMessage(), null); + } + + // wait the set timeout +1 second to allow for + // asterisk to start the originate + if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS)) { + logger.error("Originate Latch timed out"); + } + } catch (final InterruptedException e) { + OriginateBaseClass.logger.debug(e, e); + } catch (final Exception e) { + OriginateBaseClass.logger.error(e, e); + } finally { + this.close(); + } + + if (this.originateSuccess) { + this.result.setSuccess(true); + this.result.setChannelData(this.newChannel); + OriginateBaseClass.logger.info("new channel ok: " + this.newChannel); + } else { + OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$ + + if (this.newChannel != null) { + try { + logger.warn("Hanging up"); + pbx.hangup(this.newChannel); + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { + logger.error(e, e); + + } + } + } + + return this.result; + } + + void abort(final String reason) { + OriginateBaseClass.logger.warn("Aborting originate "); + this.originateSuccess = false; + this.result.setAbortReason(reason); + this.hungup = true; + if (this.newChannel != null) { + OriginateBaseClass.logger.warn("Aborted, Hangup up on the way out"); + this.result.setChannelHungup(true); + + PBX pbx = PBXFactory.getActivePBX(); + try { + pbx.hangup(this.newChannel); + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { + logger.error(e, e); + + } + } + originateLatch.countDown(); + + } + + @Override + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); + + required.add(OriginateResponseEvent.class); + required.add(BridgeEvent.class); + // bridge event is a subclass of linkevent, so we need link & unlink in + // our list of events to support Asterisk 1.4 + required.add(LinkEvent.class); + required.add(UnlinkEvent.class); + required.add(HangupEvent.class); + required.add(NewChannelEvent.class); + required.add(DialEndEvent.class); + required.add(DialBeginEvent.class); + + return required; + } + + /** + * It is important that this method is synchronised as there is some + * interaction between the events and we need to ensure we process one at a + * time. + */ + @Override + public void onManagerEvent(final ManagerEvent event) { + try (LockCloser closer = this.withLock()) { + managerEventsSeen.getAndIncrement(); + if (event instanceof HangupEvent) { + final HangupEvent hangupEvt = (HangupEvent) event; + final Channel hangupChannel = hangupEvt.getChannel(); + + if (channelId.equals(hangupEvt.getUniqueId())) { + this.originateSuccess = false; + OriginateBaseClass.logger.warn("Dest channel " + this.newChannel + " hungup"); + originateLatch.countDown(); + } + if ((this.monitorChannel1 != null) && (hangupChannel.isSame(this.monitorChannel1))) { + this.originateSuccess = false; + this.hungup = true; + if (this.newChannel != null) { + OriginateBaseClass.logger.warn("hanging up " + this.newChannel); + this.result.setChannelHungup(true); + + PBX pbx = PBXFactory.getActivePBX(); + try { + logger.warn("Hanging up"); + pbx.hangup(this.newChannel); + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { + logger.error(e, e); + + } + } + OriginateBaseClass.logger.warn("notify channel 1 hungup"); + originateLatch.countDown(); + } + if ((this.monitorChannel2 != null) && (hangupChannel.isSame(this.monitorChannel2))) { + this.originateSuccess = false; + this.hungup = true; + if (this.newChannel != null) { + OriginateBaseClass.logger.warn("Hanging up channel " + this.newChannel); + this.result.setChannelHungup(true); + + PBX pbx = PBXFactory.getActivePBX(); + try { + pbx.hangup(this.newChannel); + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { + logger.error(e, e); + + } + } + OriginateBaseClass.logger.warn("Notify channel 2 (" + this.monitorChannel2 + ") hungup");//$NON-NLS-2$ + originateLatch.countDown(); + } + + } + if (event instanceof OriginateResponseEvent) { + OriginateBaseClass.logger.debug("response : " + this.newChannel); + + final OriginateResponseEvent response = (OriginateResponseEvent) event; + OriginateBaseClass.logger.debug("OriginateResponseEvent: channel=" + + (response.isChannel() ? response.getChannel() : response.getEndPoint()) + " originateID:" + + this.originateID); + OriginateBaseClass.logger.debug("{" + response.getReason() + ":" + response.getResponse() + "}"); //$NON-NLS-2$ //$NON-NLS-3$ + if (this.originateID != null) { + if (this.originateID.compareToIgnoreCase(response.getActionId()) == 0) { + this.originateSuccess = response.isSuccess(); + OriginateBaseClass.logger.info("OriginateResponse: matched actionId, success=" + + this.originateSuccess + " channelSeen=" + this.channelSeen); + + this.originateSeen = true; + + if (originateSuccess) { + if (newChannel == null) { + this.newChannel = response.getChannel(); + } + channelSeen = newChannel != null; + + // if we have also seen the channel then we can + // notify + // the + // originate() method + // that the call is up. Otherwise we will rely on + // the + // NewChannelEvent doing the + // notify. + if (this.channelSeen) { + OriginateBaseClass.logger.info("notify originate response event " + this.originateSuccess); + originateLatch.countDown(); + } else { + logger.error("Originate Response didn't contain the channel"); + } + } + } + } else { + OriginateBaseClass.logger.warn("actionid is null"); + } + } + + if (event instanceof NewChannelEvent) { + final NewChannelEvent newState = (NewChannelEvent) event; + if (channelId.equalsIgnoreCase(newState.getChannel().getUniqueId())) { + final Channel channel = newState.getChannel(); + + OriginateBaseClass.logger.info("new channel event :" + channel + " context = " + newState.getContext() //$NON-NLS-2$ + + " state =" + newState.getChannelStateDesc() + " state =" + newState.getChannelState()); //$NON-NLS-2$ + + handleId(channel); + } + } + + if (event instanceof BridgeEvent) { + if (((BridgeEvent) event).isLink()) { + final BridgeEvent bridgeEvent = (BridgeEvent) event; + Channel channel = bridgeEvent.getChannel1(); + if (bridgeEvent.getChannel1().isLocal()) { + channel = bridgeEvent.getChannel2(); + } + if (channelId.equalsIgnoreCase(bridgeEvent.getChannel1().getUniqueId()) + || channelId.equalsIgnoreCase(bridgeEvent.getChannel2().getUniqueId())) { + + OriginateBaseClass.logger + .info("new bridge event :" + channel + " channel1 = " + bridgeEvent.getChannel1() //$NON-NLS-2$ + + " channel2 =" + bridgeEvent.getChannel2()); + + handleId(channel); + } + } + + } + + if (event instanceof DialEndEvent) { + if (channelId.equalsIgnoreCase(((DialEndEvent) event).getDestChannel().getUniqueId())) { + String forward = ((DialEndEvent) event).getForward(); + if (forward != null && forward.length() > 0) { + logger.warn("DialEndEvent"); + originateLatch.countDown(); + } + } + } + } + } + + private void handleId(Channel channel) { + + if ((this.newChannel == null) && !channel.isLocal()) { + this.newChannel = channel; + this.channelSeen = true; + + OriginateBaseClass.logger.info("new channel name " + channel); + if (this.listener != null) { + /* + * Update the phone channel to allow the call to be cancelled + * before it's answered. + */ + this.listener.channelUpdate(channel); + } + + if (this.originateSeen) { + OriginateBaseClass.logger.info("notifying success 362"); + originateLatch.countDown(); + } + } + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateResult.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateResult.java new file mode 100644 index 000000000..c2e544357 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateResult.java @@ -0,0 +1,53 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.pbx.Channel; + +public class OriginateResult { + + private boolean channelHungup = false; + + private boolean success = false; + + private Channel newChannel = null; + + private String abortReason; + + OriginateResult() { + // not used + } + + public String getAbortReason() { + return this.abortReason; + } + + void setAbortReason(final String reason) { + this.abortReason = reason; + + } + + public void setChannelData(final Channel channel) { + this.newChannel = channel; + } + + public Channel getChannel() { + + return this.newChannel; + } + + public boolean isSuccess() { + return this.success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public boolean isChannelHungup() { + return this.channelHungup; + } + + public void setChannelHungup(boolean channel1Hungup) { + this.channelHungup = channel1Hungup; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateToExtension.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateToExtension.java new file mode 100644 index 000000000..f82cd8841 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateToExtension.java @@ -0,0 +1,65 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.pbx.*; + +import java.util.HashMap; +import java.util.Map; + +public class OriginateToExtension extends OriginateBaseClass { + + /* + * this class generates and issues ActionEvents to asterisk through the + * manager. This is the asterisk coal face. + */ + + public OriginateToExtension(final NewChannelListener listener) { + super(listener, null, null); + + } + + public OriginateResult originate(final EndPoint localHandset, final EndPoint targetExtension, final boolean autoAnswer, + final CallerID callerID, final String context) { + /* + * A new call is originated on the nominated channel to the specified + * extension. + */ + OriginateBaseClass.logger.debug("originate connecting localHandset " + localHandset + " to Extension " //$NON-NLS-1$ //$NON-NLS-2$ + + targetExtension + " autoAnswer " + autoAnswer); //$NON-NLS-1$ + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + + final HashMap myVars = new HashMap<>(1); + if (autoAnswer) { + RedirectCall.setAutoAnswer(myVars, profile); + } + + return this.originate(localHandset, targetExtension, myVars, callerID, null, false, context); + } + + public OriginateResult originate(final EndPoint localHandset, final EndPoint targetExtension, final boolean autoAnswer, + final String context, final CallerID callerID, Integer timeout, final boolean hideCallerId, + Map channelVarsToSet) { + /* + * A new call is originated on the nominated channel to the specified + * extension. + */ + OriginateBaseClass.logger.debug("originate connection localHandset " + localHandset + " to Extension " //$NON-NLS-1$ //$NON-NLS-2$ + + targetExtension + " autoAnswer " + autoAnswer); //$NON-NLS-1$ + final AsteriskSettings profile = PBXFactory.getActiveProfile(); + + final HashMap myVars = new HashMap<>(1); + if (autoAnswer) { + RedirectCall.setAutoAnswer(myVars, profile); + } + if (channelVarsToSet != null) { + myVars.putAll(channelVarsToSet); + } + + return this.originate(localHandset, targetExtension, myVars, callerID, timeout, hideCallerId, context); + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectCall.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectCall.java new file mode 100644 index 000000000..522191485 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectCall.java @@ -0,0 +1,64 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.pbx.*; +import org.asteriskjava.pbx.agi.AgiChannelActivityDial; +import org.asteriskjava.pbx.agi.AgiChannelActivityVoicemail; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.util.HashMap; + +public class RedirectCall { + /* + * this class generates and issues ActionEvents to asterisk through the + * manager. This is the asterisk coal face. + */ + private static final Log logger = LogFactory.getLog(RedirectCall.class); + + static public void setAutoAnswer(final HashMap myVars, final AsteriskSettings settings) { + myVars.put(AsteriskPBX.getSIPADDHeader(false, true), settings.getAutoAnswer()); + RedirectCall.logger.debug("auto answer"); //$NON-NLS-1$ + } + + public boolean redirect(final Channel channel, final EndPoint targetEndPoint, final String context, + final boolean autoAnswer) throws PBXException { + // Set or clear the auto answer header. + // Clearing is important as it may have been set during the + // initial answer sequence. If we don't clear it then then transfer + // target will be auto-answered, which is fun but bad. + String sipHeader = ""; + if (autoAnswer) { + sipHeader = PBXFactory.getActiveProfile().getAutoAnswer(); + } + + /* + * redirects the specified channel to the specified extension. Returns + * true or false reflecting success. + */ + redirect(channel, new AgiChannelActivityDial(targetEndPoint.getFullyQualifiedName(), sipHeader)); + + RedirectCall.logger.debug("redirected " + channel + " to " + targetEndPoint); //$NON-NLS-1$ //$NON-NLS-2$ + return true; + } + + public boolean redirectToVoicemail(final Channel channel, final EndPoint mailbox) throws PBXException { + + redirect(channel, new AgiChannelActivityVoicemail(mailbox.getFullyQualifiedName())); + return true; + } + + public void redirect(Channel channel, AgiChannelActivityAction channelActivityHold) throws PBXException { + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + + if (!pbx.moveChannelToAgi(channel)) { + throw new PBXException("Channel: " + channel + " couldn't be moved to agi"); + } + if (!pbx.waitForChannelToQuiescent(channel, 3000)) + throw new PBXException("Channel: " + channel + " cannot be redirected as it is still in transition."); + + channel.setCurrentActivityAction(channelActivityHold); + + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectToMeetMe.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectToMeetMe.java new file mode 100644 index 000000000..548938ed1 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectToMeetMe.java @@ -0,0 +1,39 @@ +package org.asteriskjava.pbx.internal.managerAPI; + +import org.asteriskjava.pbx.Channel; +import org.asteriskjava.pbx.PBXException; +import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.agi.AgiChannelActivityMeetme; +import org.asteriskjava.pbx.internal.core.AsteriskPBX; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +public class RedirectToMeetMe { + private static final Log logger = LogFactory.getLog(RedirectToMeetMe.class); + + public RedirectToMeetMe() { + super(); + } + + public boolean redirectToMeetme(final Channel channel, final String room, String bridgeProfile, String userProfile) + throws PBXException { + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); + /* + * this procedure rediects the specified channel to the specified meetme + * room. This is achieved through the dial plan. q option - don't + * announce new members to meetme d option - dynamically create meetme x + * option - close the conference when last marked user exits A options - + * set marked user + */ + + RedirectToMeetMe.logger.info("redirect to Meetme channel " + channel + " room " + room); + + if (!pbx.moveChannelToAgi(channel)) { + throw new PBXException("Channel: " + channel + " couldn't be moved to agi"); + } + channel.setCurrentActivityAction(new AgiChannelActivityMeetme(room, bridgeProfile, userProfile)); + + return true; + } + +} diff --git a/src/main/java/org/asteriskjava/pbx/util/LogTime.java b/src/main/java/org/asteriskjava/pbx/util/LogTime.java new file mode 100644 index 000000000..2db86c5a1 --- /dev/null +++ b/src/main/java/org/asteriskjava/pbx/util/LogTime.java @@ -0,0 +1,19 @@ +/* + * Created on 2/03/2005 + * + */ +package org.asteriskjava.pbx.util; + +/** + * @author work shop + */ +public class LogTime { + private final Long dStartTime = System.currentTimeMillis(); + + /** + * @return time taken from construction until now in milliseconds + */ + public long timeTaken() { + return System.currentTimeMillis() - this.dStartTime; + } +} diff --git a/src/main/java/org/asteriskjava/tools/HtmlEventTracer.java b/src/main/java/org/asteriskjava/tools/HtmlEventTracer.java index 875411246..b60b0b0f9 100644 --- a/src/main/java/org/asteriskjava/tools/HtmlEventTracer.java +++ b/src/main/java/org/asteriskjava/tools/HtmlEventTracer.java @@ -7,8 +7,11 @@ import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; +import java.io.FileOutputStream; import java.io.IOException; +import java.io.OutputStreamWriter; import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -16,7 +19,8 @@ /** * A diagnostic tool that creates an HTML file showing the state changing events - * received from Asterisk on the Manager API.

      + * received from Asterisk on the Manager API. + *

      * The following events are shown: *

        *
      • NewChannel
      • @@ -30,19 +34,17 @@ * * @version $Id$ */ -public class HtmlEventTracer implements ManagerEventListener -{ +public class HtmlEventTracer implements ManagerEventListener { private String filename = "trace.html"; private PrintWriter writer; private final List uniqueIds; private final List events; private final Map, String> colors; - public HtmlEventTracer() - { - uniqueIds = new ArrayList(); - events = new ArrayList(); - colors = new HashMap, String>(); + public HtmlEventTracer() { + uniqueIds = new ArrayList<>(); + events = new ArrayList<>(); + colors = new HashMap<>(); colors.put(NewChannelEvent.class, "#7cd300"); // green colors.put(NewStateEvent.class, "#a4b6c8"); @@ -52,20 +54,15 @@ public HtmlEventTracer() colors.put(BridgeEvent.class, "#fff8ae"); // light yellow colors.put(HangupEvent.class, "#ff6c17"); // orange - try - { - writer = new PrintWriter(filename); - } - catch (IOException e) - { + try { + writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8)); + } catch (IOException e) { e.printStackTrace(); } } - public static void main(String[] args) throws Exception - { - if (args.length != 3) - { + public static void main(String[] args) throws Exception { + if (args.length != 3) { System.err.println("Usage: java org.asteriskjava.tools.HtmlEventTracer host username password"); System.exit(1); } @@ -80,44 +77,35 @@ public static void main(String[] args) throws Exception System.err.println("Event tracer successfully started. Press Ctrl-C to write trace file and exit."); - Runtime.getRuntime().addShutdownHook(new Thread() - { + Runtime.getRuntime().addShutdownHook(new Thread() { @Override - public void run() - { + public void run() { tracer.write(); server.shutdown(); } - } - ); + }); - while(true) - { + while (true) { Thread.sleep(1000); } } - public void onManagerEvent(ManagerEvent event) - { + public void onManagerEvent(ManagerEvent event) { events.add(event); System.out.println("> " + event); - for (String property : new String[]{"uniqueId", "uniqueId1", "uniqueId2", "srcUniqueId", "destUniqueId"}) - { + for (String property : new String[]{"uniqueId", "uniqueId1", "uniqueId2", "srcUniqueId", "destUniqueId"}) { String uniqueId; uniqueId = getProperty(event, property); - if (uniqueId != null && !uniqueIds.contains(uniqueId)) - { + if (uniqueId != null && !uniqueIds.contains(uniqueId)) { uniqueIds.add(uniqueId); } } } - public void write() - { + public void write() { writer.append(""); - for (String uniqueId : uniqueIds) - { + for (String uniqueId : uniqueIds) { writer.append(""); writer.println(""); - for (ManagerEvent event : events) - { + for (ManagerEvent event : events) { boolean print = false; StringBuilder line = new StringBuilder(); line.append(""); - for (String uniqueId : uniqueIds) - { + for (String uniqueId : uniqueIds) { String text; text = getText(uniqueId, event); - if (text == null) - { + if (text == null) { line.append(""); - } - else - { + } else { String color = getColor(event.getClass()); line.append(""); print = true; } } line.append(""); - if (print) - { + if (print) { writer.println(line.toString()); } } @@ -163,35 +145,27 @@ public void write() System.err.println("Trace file successfully written to " + filename + "."); } - private String getColor(Class clazz) - { - for (Map.Entry, String> entry : colors.entrySet()) - { - if (entry.getKey().isAssignableFrom(clazz)) - { + private String getColor(Class clazz) { + for (Map.Entry, String> entry : colors.entrySet()) { + if (entry.getKey().isAssignableFrom(clazz)) { return entry.getValue(); } } return "#ffffff"; } - protected String getProperty(Object obj, String property) - { - try - { + protected String getProperty(Object obj, String property) { + try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); - for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) - { - if (!propertyDescriptor.getName().equals(property)) - { + for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) { + if (!propertyDescriptor.getName().equals(property)) { continue; } - return propertyDescriptor.getReadMethod().invoke(obj).toString(); + final Object o = propertyDescriptor.getReadMethod().invoke(obj); + return o != null ? o.toString() : null; } - } - catch (Exception e) - { + } catch (Exception e) { System.err.println("Unable to read property '" + property + "' from object " + obj + ": " + e.getMessage()); return null; } @@ -199,101 +173,74 @@ protected String getProperty(Object obj, String property) return null; } - protected String getLocalName(Class c) - { - String s; - - s = c.getName(); - return s.substring(s.lastIndexOf(".") + 1, s.length()); - } - - protected String getText(String uniqueId, ManagerEvent event) - { + protected String getText(String uniqueId, ManagerEvent event) { String format = null; String[] properties = null; - if (uniqueId.equals(getProperty(event, "uniqueId"))) - { - if (event instanceof NewChannelEvent) - { + if (uniqueId.equals(getProperty(event, "uniqueId"))) { + if (event instanceof NewChannelEvent) { format = "%s
        %s"; properties = new String[]{"channel", "state"}; - } - else if (event instanceof NewStateEvent) - { + } else if (event instanceof NewStateEvent) { format = "%s
        %s"; properties = new String[]{"channel", "state"}; - } - else if (event instanceof NewExtenEvent) - { + } else if (event instanceof NewExtenEvent) { format = "%s,%s,%s
        %s(%s)"; properties = new String[]{"context", "extension", "priority", "application", "appData"}; - } - else if (event instanceof RenameEvent) - { + } else if (event instanceof RenameEvent) { format = "old: %s
        new: %s"; properties = new String[]{"oldname", "newname"}; - } - else if (event instanceof HoldEvent) - { + } else if (event instanceof HoldEvent) { format = "%s"; properties = new String[]{"status"}; - } - else if (event instanceof AbstractParkedCallEvent) - { + } else if (event instanceof AbstractParkedCallEvent) { format = "exten: %s
        from: %s"; properties = new String[]{"exten", "from"}; - } - else if (event instanceof HangupEvent) - { + } else if (event instanceof HangupEvent) { format = "%s
        %s (%s)"; properties = new String[]{"channel", "cause", "causeTxt"}; + } else if (event instanceof AntennaLevelEvent) { + format = "%s"; + properties = new String[]{"signal"}; + } else if (event instanceof PausedEvent) { + format = "(%s) %s"; + properties = new String[]{"header", "extension"}; + } else if (event instanceof UnpausedEvent) { + format = "(%s) %s"; + properties = new String[]{"header", "extension"}; } } - if (event instanceof BridgeEvent) - { - if (uniqueId.equals(getProperty(event, "uniqueId1"))) - { + if (event instanceof BridgeEvent) { + if (uniqueId.equals(getProperty(event, "uniqueId1"))) { format = "%s
        %s
        %s"; properties = new String[]{"uniqueId2", "channel2", "bridgeState"}; - } - else if (uniqueId.equals(getProperty(event, "uniqueId2"))) - { + } else if (uniqueId.equals(getProperty(event, "uniqueId2"))) { format = "%s
        %s
        %s"; properties = new String[]{"uniqueId1", "channel1", "bridgeState"}; } } - if (event instanceof DialEvent) - { - if (uniqueId.equals(getProperty(event, "srcUniqueId"))) - { + if (event instanceof DialEvent) { + if (uniqueId.equals(getProperty(event, "srcUniqueId"))) { format = "To: %s"; properties = new String[]{"destination"}; - } - else if (uniqueId.equals(getProperty(event, "destUniqueId"))) - { + } else if (uniqueId.equals(getProperty(event, "destUniqueId"))) { format = "From: %s"; properties = new String[]{"src"}; } } - if (format != null) - { + if (format != null && properties != null) { String[] args = new String[properties.length]; - for (int i = 0; i < properties.length; i++) - { + for (int i = 0; i < properties.length; i++) { String value; value = getProperty(event, properties[i]); - if (value == null) - { + if (value == null) { args[i] = ""; - } - else - { + } else { value = value.replace("<", "<"); value = value.replace(">", ">"); args[i] = value; diff --git a/src/main/java/org/asteriskjava/tools/package.html b/src/main/java/org/asteriskjava/tools/package.html index 82bfc804c..ed5aa3e20 100644 --- a/src/main/java/org/asteriskjava/tools/package.html +++ b/src/main/java/org/asteriskjava/tools/package.html @@ -1,27 +1,27 @@ - +

        Tools for debugging Asterisk and Asterisk-Java.

        - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/util/AstState.java b/src/main/java/org/asteriskjava/util/AstState.java index 2f4f7feda..afe67770d 100644 --- a/src/main/java/org/asteriskjava/util/AstState.java +++ b/src/main/java/org/asteriskjava/util/AstState.java @@ -1,18 +1,17 @@ package org.asteriskjava.util; -import java.util.Map; -import java.util.HashMap; import java.util.Collections; -import java.util.regex.Pattern; +import java.util.HashMap; +import java.util.Map; import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Utility methods related to channel state handling in Asterisk's channel.c. * * @since 1.0.0 */ -public class AstState -{ +public class AstState { /* from include/asterisk/channel.h */ /** @@ -67,9 +66,8 @@ public class AstState private static final Map inverseStateMap; - static - { - final Map tmpInverseStateMap = new HashMap(); + static { + final Map tmpInverseStateMap = new HashMap<>(); tmpInverseStateMap.put("Down", AST_STATE_DOWN); tmpInverseStateMap.put("Rsrvd", AST_STATE_RSRVD); @@ -87,8 +85,7 @@ public class AstState private static final Pattern UNKNOWN_STATE_PATTERN = Pattern.compile("^Unknown \\((\\d+)\\)$"); - private AstState() - { + private AstState() { } @@ -98,28 +95,21 @@ private AstState() * @param str state as a descriptive text. * @return numeric state. */ - public static Integer str2state(String str) - { + public static Integer str2state(String str) { Integer state; - if (str == null) - { + if (str == null) { return null; } state = inverseStateMap.get(str); - if (state == null) - { + if (state == null) { Matcher matcher = UNKNOWN_STATE_PATTERN.matcher(str); - if (matcher.matches()) - { - try - { + if (matcher.matches()) { + try { state = Integer.valueOf(matcher.group(1)); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { // should not happen as the pattern requires \d+ for the state. throw new IllegalArgumentException("Unable to convert state '" + str + "' to integer representation", e); } diff --git a/src/main/java/org/asteriskjava/util/AstUtil.java b/src/main/java/org/asteriskjava/util/AstUtil.java index 91941507f..98640c110 100644 --- a/src/main/java/org/asteriskjava/util/AstUtil.java +++ b/src/main/java/org/asteriskjava/util/AstUtil.java @@ -1,25 +1,23 @@ package org.asteriskjava.util; -import java.util.*; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; /** - * Some static utility methods to imitate Asterisk specific logic. - *

        - * See Asterisk's util.c. - *

        + * Some static utility methods to imitate Asterisk specific logic.
        + * See Asterisk's util.c.
        * Client code is not supposed to use this class. * * @author srt * @version $Id$ */ -public class AstUtil -{ +public class AstUtil { private static final Set TRUE_LITERALS; private static final Set NULL_LITERALS; - static - { - TRUE_LITERALS = new HashSet(20); + static { + TRUE_LITERALS = new HashSet<>(20); TRUE_LITERALS.add("yes"); TRUE_LITERALS.add("true"); TRUE_LITERALS.add("y"); @@ -28,12 +26,12 @@ public class AstUtil TRUE_LITERALS.add("on"); TRUE_LITERALS.add("enabled"); - NULL_LITERALS = new HashSet(20); + NULL_LITERALS = new HashSet<>(20); NULL_LITERALS.add(""); NULL_LITERALS.add("unknown"); NULL_LITERALS.add("none"); // VarSet event in pbx.c NULL_LITERALS.add(""); - NULL_LITERALS.add("-none-"); // IPaddress in PeerEntryEvent + NULL_LITERALS.add("-none-"); // IPaddress in PeerEntryEvent NULL_LITERALS.add("(none)"); NULL_LITERALS.add(""); NULL_LITERALS.add("(not set)"); @@ -43,23 +41,21 @@ public class AstUtil NULL_LITERALS.add("(null)"); // appData in ListDialplanEvent } - private AstUtil() - { - //hide constructor + private AstUtil() { + // hide constructor } /** * Checks if a String represents true or false - * according to Asterisk's logic. - *

        - * The original implementation is util.c is as follows: - *

        + * according to Asterisk's logic.
        + * The original implementation is util.c is as follows:
        + * *

              *     int ast_true(const char *s)
              *     {
              *         if (!s || ast_strlen_zero(s))
              *             return 0;
        -     * 

        + *
        * if (!strcasecmp(s, "yes") || * !strcasecmp(s, "true") || * !strcasecmp(s, "y") || @@ -67,64 +63,60 @@ private AstUtil() * !strcasecmp(s, "1") || * !strcasecmp(s, "on")) * return -1; - *

        + *
        * return 0; * } *

        - *

        + * + *
        * To support the dnd property of * {@link org.asteriskjava.manager.event.ZapShowChannelsEvent} this method * also consideres the string "Enabled" as true. * * @param o the Object (usually a String) to check for true. * @return true if s represents true, - * false otherwise. + * false otherwise. */ - public static boolean isTrue(Object o) - { - if (o == null) - { + public static boolean isTrue(Object o) { + if (o == null) { return false; } - if (o instanceof Boolean) - { + if (o instanceof Boolean) { return (Boolean) o; } - final String s; - if (o instanceof String) - { - s = (String) o; - } - else - { - s = o.toString(); - } - return TRUE_LITERALS.contains(s.toLowerCase(Locale.US)); + return TRUE_LITERALS.contains(o.toString().toLowerCase(Locale.ENGLISH)); } /** - * Parses a string for caller id information. - *

        - * The caller id string should be in the form "Some Name" <1234>. - *

        - * This resembles ast_callerid_parse in - * callerid.c but strips any whitespace. + * @param a an object + * @param b an object to be compared with {@code a} for equality + * @return {@code true} if the arguments are equal to each other and + * {@code false} otherwise + */ + public static boolean isEqual(Object a, Object b) { + return a == b || a != null && a.equals(b); + } + + /** + * Parses a string for caller id information.
        + * The caller id string should be in the form + * "Some Name" <1234>.
        + * This resembles ast_callerid_parse in callerid.c + * but strips any whitespace. * * @param s the string to parse * @return a String[] with name (index 0) and number (index 1) */ - public static String[] parseCallerId(String s) - { + public static String[] parseCallerId(String s) { final String[] result = new String[2]; final int lbPosition; final int rbPosition; String name; String number; - if (s == null) - { + if (s == null) { return result; } @@ -132,32 +124,24 @@ public static String[] parseCallerId(String s) rbPosition = s.lastIndexOf('>'); // no opening and closing brace? use value as CallerId name - if (lbPosition < 0 || rbPosition < 0) - { + if (lbPosition < 0 || rbPosition < 0) { name = s.trim(); - if (name.length() == 0) - { + if (name.length() == 0) { name = null; } result[0] = name; return result; } - else - { - number = s.substring(lbPosition + 1, rbPosition).trim(); - if (number.length() == 0) - { - number = null; - } + number = s.substring(lbPosition + 1, rbPosition).trim(); + if (number.length() == 0) { + number = null; } name = s.substring(0, lbPosition).trim(); - if (name.startsWith("\"") && name.endsWith("\"") && name.length() > 1) - { + if (name.startsWith("\"") && name.endsWith("\"") && name.length() > 1) { name = name.substring(1, name.length() - 1).trim(); } - if (name.length() == 0) - { + if (name.length() == 0) { name = null; } @@ -167,37 +151,64 @@ public static String[] parseCallerId(String s) } /** - * Checks if the value of s was null in Asterisk. - *

        + * Checks if the value of s was null in Asterisk.
        * This method is useful as Asterisk likes to replace null - * values with different string values like "unknown", "<unknown>" - * or "<null>". - *

        + * values with different string values like "unknown", "<unknown>" or + * "<null>".
        * To find such replacements search for S_OR in Asterisk's * source code. You will find things like + * *

              * S_OR(chan->cid.cid_num, "<unknown>")
              * fdprintf(fd, "agi_callerid: %s\n", S_OR(chan->cid.cid_num, "unknown"));
              * 
        + *

        * and more... * - * @param s the string to test, may be null. If s is not a string - * the only test that is performed is a check for null. + * @param s the string to test, may be null. If s is not a + * string the only test that is performed is a check for + * null. * @return true if the s was null in Asterisk; - * false otherwise. + * false otherwise. */ - public static boolean isNull(Object s) - { - if (s == null) - { + public static boolean isNull(Object s) { + if (s == null) { return true; } - if (!(s instanceof String)) - { + if (!(s instanceof String)) { return false; } - return NULL_LITERALS.contains(((String) s).toLowerCase(Locale.US)); + return NULL_LITERALS.contains(((String) s).toLowerCase(Locale.ENGLISH)); + } + + /** + * Converts a non-standard Asterisk boolean String value into something the Boolean class + * String constructor recognizes. + *

        + * Asterisk can return various strings that represent truth values. + * This method converts them into standard True/False, or null if null. + * + * @param value + * @return true if the String is "true" or "yes" (case insensitive). + * false if the String is "false" or "no" (case insensitive). + * null if the String is null. + * @throws IllegalArgumentException if any other value not listed above. + */ + + public static String convertAsteriskBooleanStringToStandardBooleanString(String value) { + if (value == null) return null; + switch (value.toLowerCase()) { + case "true": + case "yes": + return "True"; + case "false": + case "no": + return "False"; + default: + throw new IllegalArgumentException("value of:" + value + " was not recognized as a boolean"); + } + } } diff --git a/src/main/java/org/asteriskjava/util/Base64.java b/src/main/java/org/asteriskjava/util/Base64.java index f1b6ad43a..c327d7665 100644 --- a/src/main/java/org/asteriskjava/util/Base64.java +++ b/src/main/java/org/asteriskjava/util/Base64.java @@ -12,9 +12,17 @@ * and vice-versa.

        * From java.util.prefs. * - * @author Josh Bloch + * @deprecated Use {@link java.util.Base64} instead. + * + * @author Josh Bloch */ +@Deprecated public class Base64 { + + private Base64() { + + } + /** * Translates the specified byte array into a Base64 string as per * Preferences.put(byte[]). @@ -35,21 +43,21 @@ public static String byteArrayToAltBase64(byte[] a) { private static String byteArrayToBase64(byte[] a, boolean alternate) { int aLen = a.length; - int numFullGroups = aLen/3; - int numBytesInPartialGroup = aLen - 3*numFullGroups; - int resultLen = 4*((aLen + 2)/3); - StringBuffer result = new StringBuffer(resultLen); - char[] intToAlpha = (alternate ? intToAltBase64 : intToBase64); + int numFullGroups = aLen / 3; + int numBytesInPartialGroup = aLen - 3 * numFullGroups; + int resultLen = 4 * ((aLen + 2) / 3); + StringBuilder result = new StringBuilder(resultLen); + char[] intToAlpha = alternate ? intToAltBase64 : intToBase64; // Translate all full groups from byte array elements to Base64 int inCursor = 0; - for (int i=0; i> 2]); - result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]); - result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]); + result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]); + result.append(intToAlpha[(byte1 << 2) & 0x3f | (byte2 >> 6)]); result.append(intToAlpha[byte2 & 0x3f]); } @@ -63,8 +71,8 @@ private static String byteArrayToBase64(byte[] a, boolean alternate) { } else { // assert numBytesInPartialGroup == 2; int byte1 = a[inCursor++] & 0xff; - result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]); - result.append(intToAlpha[(byte1 << 2)&0x3f]); + result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]); + result.append(intToAlpha[(byte1 << 2) & 0x3f]); result.append('='); } } @@ -78,12 +86,12 @@ private static String byteArrayToBase64(byte[] a, boolean alternate) { * index values into their "Base64 Alphabet" equivalents as specified * in Table 1 of RFC 2045. */ - private static final char intToBase64[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' + private static final char[] intToBase64 = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; /** @@ -93,20 +101,20 @@ private static String byteArrayToBase64(byte[] a, boolean alternate) { * This alternate alphabet does not use the capital letters. It is * designed for use in environments where "case folding" occurs. */ - private static final char intToAltBase64[] = { - '!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':', - ';', '<', '>', '@', '[', ']', '^', '`', '_', '{', '|', '}', '~', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '?' + private static final char[] intToAltBase64 = { + '!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':', + ';', '<', '>', '@', '[', ']', '^', '`', '_', '{', '|', '}', '~', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '?' }; /** * Translates the specified Base64 string (as per Preferences.get(byte[])) * into a byte array. * - * @throw IllegalArgumentException if s is not a valid Base64 - * string. + * @throws IllegalArgumentException if s is not a valid Base64 + * string. */ public static byte[] base64ToByteArray(String s) { return base64ToByteArray(s, false); @@ -116,36 +124,36 @@ public static byte[] base64ToByteArray(String s) { * Translates the specified "alternate representation" Base64 string * into a byte array. * - * @throw IllegalArgumentException or ArrayOutOfBoundsException - * if s is not a valid alternate representation - * Base64 string. + * @throws IllegalArgumentException or ArrayOutOfBoundsException + * if s is not a valid alternate representation + * Base64 string. */ public static byte[] altBase64ToByteArray(String s) { return base64ToByteArray(s, true); } private static byte[] base64ToByteArray(String s, boolean alternate) { - byte[] alphaToInt = (alternate ? altBase64ToInt : base64ToInt); + byte[] alphaToInt = alternate ? altBase64ToInt : base64ToInt; int sLen = s.length(); - int numGroups = sLen/4; - if (4*numGroups != sLen) + int numGroups = sLen / 4; + if (4 * numGroups != sLen) throw new IllegalArgumentException( - "String length must be a multiple of four."); + "String length must be a multiple of four."); int missingBytesInLastGroup = 0; int numFullGroups = numGroups; if (sLen != 0) { - if (s.charAt(sLen-1) == '=') { + if (s.charAt(sLen - 1) == '=') { missingBytesInLastGroup++; numFullGroups--; } - if (s.charAt(sLen-2) == '=') + if (s.charAt(sLen - 2) == '=') missingBytesInLastGroup++; } - byte[] result = new byte[3*numGroups - missingBytesInLastGroup]; + byte[] result = new byte[3 * numGroups - missingBytesInLastGroup]; // Translate all full groups from base64 to byte array elements int inCursor = 0, outCursor = 0; - for (int i=0; i * Client code is not supposed to use this class. - * + * * @author srt * @version $Id$ */ -public class DateUtil -{ +public class DateUtil { private static final String DATE_TIME_PATTERN = "yy-MM-dd HH:mm:ss"; private static Date currentDate; - private DateUtil() - { + private DateUtil() { // hide constructor } /** * If set to a non null value uses the date given as current date on calls * to getDate(). Set to null to restore the normal behavior. - * + * * @param currentDate the date to return on calls to getDate() or - * null to return the real current date. + * null to return the real current date. */ - public static void overrideCurrentDate(Date currentDate) - { + public static void overrideCurrentDate(Date currentDate) { DateUtil.currentDate = currentDate; } /** * Returns the real current date or the date set with overrideCurrentDate(). - * + * * @return the real current date or the date set with overrideCurrentDate(). */ - public static Date getDate() - { - if (currentDate == null) - { + public static Date getDate() { + if (currentDate == null) { return new Date(); } - else - { - return currentDate; - } + return currentDate; } /** * Converts a date in the form of "yy-MM-dd HH:mm:ss" to a Date object using * the default time zone. - * + * * @param s date string in the form of "yy-MM-dd HH:mm:ss" - * @return the corresponding Java date object or null if it is not parsable. + * @return the corresponding Java date object or null if it is + * not parsable. */ - public static Date parseDateTime(String s) - { + public static Date parseDateTime(String s) { return parseDateTime(s, null); } /** * Converts a date in the form of "yy-MM-dd HH:mm:ss" to a Date object using * the given time zone. - * - * @param s date string in the form of "yy-MM-dd HH:mm:ss" - * @param tz the timezone to use or null for the default time zone. - * @return the corresponding Java date object or null if it is not parsable. + * + * @param s date string in the form of "yy-MM-dd HH:mm:ss" + * @param tz the timezone to use or null for the default time + * zone. + * @return the corresponding Java date object or null if it is + * not parsable. */ - public static Date parseDateTime(String s, TimeZone tz) - { + public static Date parseDateTime(String s, TimeZone tz) { DateFormat df; - if (s == null) - { + if (s == null) { return null; } df = new SimpleDateFormat(DATE_TIME_PATTERN); - if (tz != null) - { + if (tz != null) { df.setTimeZone(tz); } - try - { + try { return df.parse(s); - } - catch (ParseException e) - { + } catch (ParseException e) { return null; } } diff --git a/src/main/java/org/asteriskjava/util/Log.java b/src/main/java/org/asteriskjava/util/Log.java index 468e5cae1..dc2992ca7 100644 --- a/src/main/java/org/asteriskjava/util/Log.java +++ b/src/main/java/org/asteriskjava/util/Log.java @@ -17,19 +17,28 @@ package org.asteriskjava.util; /** - * Main interface used for logging throughout Asterisk-Java.

        + * Main interface used for logging throughout Asterisk-Java. + *

        * Concrete instances of this interface are obtained by calling * {@link org.asteriskjava.util.LogFactory#getLog(Class)}. - * + * * @author srt * @see org.asteriskjava.util.LogFactory */ -public interface Log -{ +public interface Log { void debug(Object obj); + void info(Object obj); + void warn(Object obj); + void warn(Object obj, Throwable exception); + void error(Object obj); + void error(Object obj, Throwable exception); + + boolean isDebugEnabled(); + + void debug(Object e, Throwable e2); } diff --git a/src/main/java/org/asteriskjava/util/LogFactory.java b/src/main/java/org/asteriskjava/util/LogFactory.java index 9e9d65df0..b8d23004e 100644 --- a/src/main/java/org/asteriskjava/util/LogFactory.java +++ b/src/main/java/org/asteriskjava/util/LogFactory.java @@ -22,42 +22,49 @@ import org.asteriskjava.util.internal.Slf4JLogger; /** - * Facade to hide details of the underlying logging system.

        - * If you want to reuse Asterisk-Java's logging abstraction layer - * add a private attribute to your class like this: + * Facade to hide details of the underlying logging system. + *

        + * If you want to reuse Asterisk-Java's logging abstraction layer add a private + * attribute to your class like this: + * *

          * private final Log logger = LogFactory.getLog(getClass());
          * 
        + *

        * and then use the methods defined in {@link org.asteriskjava.util.Log}: + * *

          * logger.error("Unable to create new instance of " + eventClass, ex);
          * 
        - * Asterisk-Java's logging abstraction layer uses log4j when available - * and falls back to java.util.logging otherwise. + *

        + * Asterisk-Java's logging abstraction layer uses log4j when available and falls + * back to java.util.logging otherwise. * * @author srt * @version $Id$ */ -public final class LogFactory -{ +public final class LogFactory { private static Boolean slf4jLoggingAvailable = null; /** - * Indicates if log4j is available on the classpath or not. If the - * check has not yet performed this is null. + * Indicates if log4j is available on the classpath or not. If the check has + * not yet performed this is null. */ private static Boolean log4jLoggingAvailable = null; /** - * Indicates if java.util.logging is available on the classpath or not. If the - * check has not yet performed this is null. + * Indicates if java.util.logging is available on the classpath or not. If + * the check has not yet performed this is null. */ private static Boolean javaLoggingAvailable = null; private static ClassLoader classLoader = LogFactory.class.getClassLoader(); - public static void setClassLoader(ClassLoader classLoader) - { + private LogFactory() { + + } + + public static void setClassLoader(ClassLoader classLoader) { LogFactory.classLoader = classLoader; } @@ -67,70 +74,48 @@ public static void setClassLoader(ClassLoader classLoader) * @param clazz the class to create the logger for. * @return the created logger. */ - public static Log getLog(Class clazz) - { - if (slf4jLoggingAvailable == null) - { - try - { + public synchronized static Log getLog(Class clazz) { + if (slf4jLoggingAvailable == null) { + try { classLoader.loadClass("org.slf4j.Logger"); slf4jLoggingAvailable = Boolean.TRUE; - } - catch (Exception e) - { + } catch (Exception e) { slf4jLoggingAvailable = Boolean.FALSE; } } - if (slf4jLoggingAvailable) - { - try - { + if (slf4jLoggingAvailable) { + try { return new Slf4JLogger(clazz); - } - catch (Throwable e) - { + } catch (Throwable e) { slf4jLoggingAvailable = Boolean.FALSE; } } - if (log4jLoggingAvailable == null) - { - try - { - classLoader.loadClass("org.apache.log4j.Logger"); + if (log4jLoggingAvailable == null) { + try { + classLoader.loadClass("org.apache.logging.log4j.Logger"); log4jLoggingAvailable = Boolean.TRUE; - } - catch (Exception e) - { + } catch (Exception e) { log4jLoggingAvailable = Boolean.FALSE; } } - if (log4jLoggingAvailable) - { + if (log4jLoggingAvailable) { return new Log4JLogger(clazz); } - if (javaLoggingAvailable == null) - { - try - { + if (javaLoggingAvailable == null) { + try { classLoader.loadClass("java.util.logging.Logger"); javaLoggingAvailable = Boolean.TRUE; - } - catch (Exception e) - { + } catch (Exception e) { javaLoggingAvailable = Boolean.FALSE; } } - if (javaLoggingAvailable) - { + if (javaLoggingAvailable) { return new JavaLoggingLog(clazz); } - else - { - return new NullLog(); - } + return new NullLog(); } } diff --git a/src/main/java/org/asteriskjava/util/MixMonitorDirection.java b/src/main/java/org/asteriskjava/util/MixMonitorDirection.java new file mode 100644 index 000000000..93866ea93 --- /dev/null +++ b/src/main/java/org/asteriskjava/util/MixMonitorDirection.java @@ -0,0 +1,27 @@ +package org.asteriskjava.util; + +/** + * MixMonitorDirection Which part of the recording to mute: read, write or both + * (from channel, to channel or both channels). + * + * @author adrian.videanu + */ +public enum MixMonitorDirection { + + FROM_CHANNEL("read"), TO_CHANNEL("write"), BOTH("both"); + + String stateName; + + MixMonitorDirection(String name) { + this.stateName = name; + } + + public String getStateName() { + return stateName; + } + + public void setStateName(String stateName) { + this.stateName = stateName; + } + +} diff --git a/src/main/java/org/asteriskjava/util/ReflectionUtil.java b/src/main/java/org/asteriskjava/util/ReflectionUtil.java index 7228b2b29..86a32e252 100644 --- a/src/main/java/org/asteriskjava/util/ReflectionUtil.java +++ b/src/main/java/org/asteriskjava/util/ReflectionUtil.java @@ -16,29 +16,42 @@ */ package org.asteriskjava.util; -import java.lang.reflect.Method; +import org.reflections.Reflections; + +import java.io.File; +import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLDecoder; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * Utility class that provides helper methods for reflection that is used by the - * fastagi and manager packages to access getter and setter methods.

        + * fastagi and manager packages to access getter and setter methods. + *

        * Client code is not supposed to use this class. * * @author srt */ -public class ReflectionUtil -{ - private ReflectionUtil() - { +public class ReflectionUtil { + private ReflectionUtil() { // hide constructor } /** - * Returns a Map of getter methods of the given class.

        + * Returns a Map of getter methods of the given class. + *

        * The key of the map contains the name of the attribute that can be * accessed by the getter, the value the getter itself (an instance of * java.lang.reflect.Method). A method is considered a getter if its name @@ -47,44 +60,58 @@ private ReflectionUtil() * @param clazz the class to return the getters for * @return a Map of attributes and their accessor methods (getters) */ - public static Map getGetters(final Class clazz) - { - final Map accessors = new HashMap(); + public static Map getGetters(final Class clazz) { + final Map accessors = new HashMap<>(); final Method[] methods = clazz.getMethods(); - for (Method method : methods) - { - String name; - String methodName; + for (Method method : methods) { + String name = null; + String methodName = method.getName(); - methodName = method.getName(); - if (!methodName.startsWith("get")) - { - continue; + if (methodName.startsWith("get")) { + name = methodName.substring(3); + } else if (methodName.startsWith("is")) { + name = methodName.substring(2); } - // skip methods with != 0 parameters - if (method.getParameterTypes().length != 0) - { + if (name == null || name.length() == 0) { continue; } - // ok seems to be an accessor - name = methodName.substring("get".length()).toLowerCase(Locale.ENGLISH); - - if (name.length() == 0) - { + // skip methods with != 0 parameters + if (method.getParameterTypes().length != 0) { continue; } - accessors.put(name, method); + accessors.put(name.toLowerCase(Locale.ENGLISH), method); } return accessors; } + private final static ConcurrentHashMap, Map> setterMap = new ConcurrentHashMap<>(); + /** - * Returns a Map of setter methods of the given class.

        + * The main benefit here is that there will not be repeated errors when + * inspecting classes for setters on every single Event being processed. + *
        + *
        + * While this method adds caching which is 100 times faster, the time + * Benefit is largely insignificant as the execution time was already very + * fast. + * + * @param clazz + * @return + */ + public static Map getSetters(Class clazz) { + return setterMap.computeIfAbsent(clazz, (c) -> { + return getSettersInternal(c); + }); + } + + /** + * Returns a Map of setter methods of the given class. + *

        * The key of the map contains the name of the attribute that can be * accessed by the setter, the value the setter itself (an instance of * java.lang.reflect.Method). A method is considered a setter if its name @@ -93,154 +120,205 @@ public static Map getGetters(final Class clazz) * @param clazz the class to return the setters for * @return a Map of attributes and their accessor methods (setters) */ - public static Map getSetters(Class clazz) - { - final Map accessors = new HashMap(); + private static Map getSettersInternal(Class clazz) { + final Map accessors = new HashMap<>(); final Method[] methods = clazz.getMethods(); - for (Method method : methods) - { + for (Method method : methods) { String name; - String methodName; - - methodName = method.getName(); - if (!methodName.startsWith("set")) - { + String methodName = method.getName(); + if (!methodName.startsWith("set")) { continue; } // skip methods with != 1 parameters - if (method.getParameterTypes().length != 1) - { + if (method.getParameterTypes().length != 1) { continue; } - // ok seems to be an accessor - name = methodName.substring("set".length()).toLowerCase(Locale.US); - accessors.put(name, method); - } + // OK seems to be an setter + name = methodName.substring("set".length()).toLowerCase(Locale.ENGLISH); + // if an event class implements a setter that exists in + // ManagerEvent, then prefer the setter from the extending class + Method existing = accessors.get(name); + if (existing != null) { + logger.warn("multiple setters (case insensitive) exist for " + name + " on class(es) " + + existing.getDeclaringClass() + " and " + method.getDeclaringClass()); + } + if (existing == null) { + // we don't have a mapping for this setter so add it. + accessors.put(name, method); + } else if (!method.getDeclaringClass().isAssignableFrom(existing.getDeclaringClass())) { + // we already have a mapping for this setter, but this one is + // from an extending class so replace it. + logger.warn("Preferring setter from extending class " + existing + " -> " + method); + accessors.put(name, method); + } else { + // there is already a mapping for this setter from class + logger.warn("Preferring setter from extending class " + method + " -> " + existing); + } + } return accessors; } + private static final Pattern ILLEGAL_CHARS = Pattern.compile("[^a-z0-9]+"); /** - * Strips all illegal charaters from the given lower case string. - * Illegal characters are all characters that are neither characters ('a' to 'z') nor digits ('0' to '9'). + * Strips all illegal characters from the given lower case string. Illegal + * characters are all characters that are neither alphabetic ('a' to 'z') + * nor digits ('0' to '9'). * * @param s the original string * @return the string with all illegal characters stripped */ - public static String stripIllegalCharacters(String s) - { - char c; - boolean needsStrip = false; - StringBuffer sb; - - if (s == null) - { + public static String stripIllegalCharacters(String s) { + if (s == null) { return null; } - - for (int i = 0; i < s.length(); i++) - { - c = s.charAt(i); - if (c >= '0' && c <= '9') - { - // continue - } // NOPMD - else if (c >= 'a' && c <= 'z') - { - // continue - } // NOPMD - else - { - needsStrip = true; - break; - } - } - - if (!needsStrip) - { - return s; - } - - sb = new StringBuffer(s.length()); - for (int i = 0; i < s.length(); i++) - { - c = s.charAt(i); - if (c >= '0' && c <= '9') - { - sb.append(c); - } - else if (c >= 'a' && c <= 'z') - { - sb.append(c); - } - } - - return sb.toString(); + return ILLEGAL_CHARS.matcher(s).replaceAll(""); } /** - * Checks if the class is available on the current thread's context class loader. + * Checks if the class is available on the current thread's context class + * loader. * * @param s fully qualified name of the class to check. - * @return true if the class is available, false otherwise. + * @return true if the class is available, false + * otherwise. */ - public static boolean isClassAvailable(String s) - { + public static boolean isClassAvailable(String s) { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - try - { + try { classLoader.loadClass(s); return true; - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { return false; } } /** - * Creates a new instance of the given class. The class is loaded using the current thread's context - * class loader and instantiated using its default constructor. + * Creates a new instance of the given class. The class is loaded using the + * current thread's context class loader and instantiated using its default + * constructor. * * @param s fully qualified name of the class to instantiate. * @return the new instance or null on failure. */ - public static Object newInstance(String s) - { + public static Object newInstance(String s) { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - try - { + try { Class clazz = classLoader.loadClass(s); Constructor constructor = clazz.getConstructor(); return constructor.newInstance(); - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { return null; - } - catch (IllegalAccessException e) - { + } catch (IllegalAccessException e) { return null; - } - catch (InstantiationException e) - { + } catch (InstantiationException e) { return null; - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { // no default constructor return null; - } - catch (InvocationTargetException e) - { + } catch (InvocationTargetException e) { // constructor threw an exception return null; } } + + private static final Log logger = LogFactory.getLog(ReflectionUtil.class); + + /** + * Find all non-abstract classes in the given package that + * implement/extend the provided type. + * + * @param packageName the package to search + * @param baseClassOrInterface the supertype or interface to filter by + * @return a Set of types that implement or extend the provided type + */ + public static Set> loadClasses(String packageName, Class baseClassOrInterface) { + Set> result = + Stream.concat( + Stream.of(baseClassOrInterface), + new Reflections(packageName) + .getSubTypesOf(baseClassOrInterface) + .stream()) + .filter(c -> !Modifier.isAbstract(c.getModifiers())) + .collect(Collectors.toSet()); + + logger.info("Loaded asd" + result.size()); + + return result; + } + + /** + * retrieve all the classes that can be found on the classpath for the + * specified packageName + * + * @param packageName + * @return + * @throws IOException + * @throws URISyntaxException + */ + private static Set getClassNamesFromPackage(String packageName) throws IOException, URISyntaxException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + Enumeration packageURLs; + Set names = new HashSet(); + + packageName = packageName.replace(".", "/"); + packageURLs = classLoader.getResources(packageName); + + while (packageURLs.hasMoreElements()) { + URL packageURL = packageURLs.nextElement(); + if (packageURL.getProtocol().equals("jar")) { + String jarFileName; + + Enumeration jarEntries; + String entryName; + + // build jar file name, then loop through entries + jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8"); + jarFileName = jarFileName.substring(5, jarFileName.indexOf("!")); + logger.info(">" + jarFileName); + try (JarFile jf = new JarFile(jarFileName);) { + jarEntries = jf.entries(); + while (jarEntries.hasMoreElements()) { + entryName = jarEntries.nextElement().getName(); + if (entryName.startsWith(packageName) && entryName.endsWith(".class")) { + entryName = entryName.substring(packageName.length() + 1, entryName.lastIndexOf('.')); + names.add(entryName); + } + } + } + + // loop through files in classpath + } else { + URI uri = new URI(packageURL.toString()); + File folder = new File(uri.getPath()); + // won't work with path which contains blank (%20) + // File folder = new File(packageURL.getFile()); + File[] files = folder.listFiles(); + if (files != null) { + for (File actual : files) { + String entryName = actual.getName(); + entryName = entryName.substring(0, entryName.lastIndexOf('.')); + names.add(entryName); + } + } + } + } + + // clean up + Iterator itr = names.iterator(); + while (itr.hasNext()) { + String name = itr.next(); + if (name.equals("package") || name.endsWith(".") || name.length() == 0) { + itr.remove(); + } + } + + return names; + } } diff --git a/src/main/java/org/asteriskjava/util/ServerSocketFacade.java b/src/main/java/org/asteriskjava/util/ServerSocketFacade.java index 196602ea2..f142ac96d 100644 --- a/src/main/java/org/asteriskjava/util/ServerSocketFacade.java +++ b/src/main/java/org/asteriskjava/util/ServerSocketFacade.java @@ -23,15 +23,14 @@ * TCP/IP sockets.

        * It hides the details of the underlying I/O system used for server socket * communication. - * + * * @author srt * @version $Id$ */ -public interface ServerSocketFacade -{ +public interface ServerSocketFacade { /** * Waits for a new incoming connection. - * + * * @return the new connection. * @throws IOException if an I/O error occurs when waiting for a connection. */ @@ -39,8 +38,18 @@ public interface ServerSocketFacade /** * Unbinds and closes the server socket. - * + * * @throws IOException if the server socket cannot be closed. */ void close() throws IOException; + + /** + * Connection is dropped if it stales on read longer than the timeout. + * + * @param socketReadTimeout the read timeout value to be used in + * milliseconds. + * @see java.net.Socket#setSoTimeout(int) + * @since 3.0.0 + */ + void setSocketReadTimeout(int socketReadTimeout); } diff --git a/src/main/java/org/asteriskjava/util/SocketConnectionFacade.java b/src/main/java/org/asteriskjava/util/SocketConnectionFacade.java index a383c253c..4169057be 100644 --- a/src/main/java/org/asteriskjava/util/SocketConnectionFacade.java +++ b/src/main/java/org/asteriskjava/util/SocketConnectionFacade.java @@ -24,19 +24,18 @@ * communication over TCP/IP sockets.

        * It hides the details of the underlying I/O system used for socket * communication. - * + * * @author srt * @version $Id$ */ -public interface SocketConnectionFacade -{ +public interface SocketConnectionFacade { /** * Reads a line of text from the socket connection. The current thread is * blocked until either the next line is received or an IOException * encounters.

        * Depending on the implementation different newline delimiters are used * ("\r\n" for the Manager API and "\n" for AGI). - * + * * @return the line of text received excluding the newline delimiter. * @throws IOException if the connection has been closed. */ @@ -44,17 +43,17 @@ public interface SocketConnectionFacade /** * Sends a given String to the socket connection. - * + * * @param s the String to send. * @throws IOException if the String cannot be sent, maybe because the - * connection has already been closed. + * connection has already been closed. */ void write(String s) throws IOException; /** * Flushes the socket connection by sending any buffered but yet unsent * data. - * + * * @throws IOException if the connection cannot be flushed. */ void flush() throws IOException; @@ -64,22 +63,22 @@ public interface SocketConnectionFacade * frees all associated ressources.

        * When calling close() any Thread currently blocked by a call to readLine() * will be unblocked and receive an IOException. - * + * * @throws IOException if the socket connection cannot be closed. */ void close() throws IOException; /** * Returns the connection state of the socket. - * + * * @return true if the socket successfuly connected to a - * server + * server */ boolean isConnected(); /** * Returns the local address this socket connection. - * + * * @return the local address this socket connection. * @since 0.2 */ @@ -87,7 +86,7 @@ public interface SocketConnectionFacade /** * Returns the local port of this socket connection. - * + * * @return the local port of this socket connection. * @since 0.2 */ @@ -95,7 +94,7 @@ public interface SocketConnectionFacade /** * Returns the remote address of this socket connection. - * + * * @return the remote address of this socket connection. * @since 0.2 */ @@ -103,7 +102,7 @@ public interface SocketConnectionFacade /** * Returns the remote port of this socket connection. - * + * * @return the remote port of this socket connection. * @since 0.2 */ diff --git a/src/main/java/org/asteriskjava/util/internal/FileTrace.java b/src/main/java/org/asteriskjava/util/internal/FileTrace.java index 944068e43..9fd442998 100644 --- a/src/main/java/org/asteriskjava/util/internal/FileTrace.java +++ b/src/main/java/org/asteriskjava/util/internal/FileTrace.java @@ -1,5 +1,6 @@ package org.asteriskjava.util.internal; +import org.asteriskjava.util.DateUtil; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; @@ -11,35 +12,34 @@ import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.Date; /** * Writes a trace file to the file system. */ -public class FileTrace implements Trace -{ +public class FileTrace implements Trace { public static final String TRACE_DIRECTORY_PROPERTY = "org.asteriskjava.trace.directory"; protected static final String FILE_PREFIX = "aj-trace"; protected static final String FILE_SUFFIX = ".txt"; - + private final Log logger = LogFactory.getLog(FileTrace.class); // ok to share instance as access to this object is synchronized anyway private final DateFormat df = new SimpleDateFormat("yyyyMMddHHmmsszzz"); - private Charset charset = Charset.forName("UTF-8"); + private Charset charset = StandardCharsets.UTF_8; private FileChannel channel; private boolean exceptionLogged = false; + private RandomAccessFile randomAccessFile; - public FileTrace(Socket socket) throws IOException - { - channel = new RandomAccessFile(getFile(socket), "rw").getChannel(); + public FileTrace(Socket socket) throws IOException { + randomAccessFile = new RandomAccessFile(getFile(socket), "rw"); + channel = randomAccessFile.getChannel(); print(getHeader(socket)); } - private String getHeader(Socket socket) - { + private String getHeader(Socket socket) { final StringBuilder sb = new StringBuilder(); sb.append("Local: "); sb.append(socket.getLocalAddress()); @@ -52,12 +52,11 @@ private String getHeader(Socket socket) sb.append(socket.getPort()); sb.append("\n"); sb.append("\n"); - + return sb.toString(); } - private File getFile(Socket socket) - { + private File getFile(Socket socket) { final String directory = System.getProperty(TRACE_DIRECTORY_PROPERTY, System.getProperty("java.io.tmpdir")); final String fileName = getFileName(socket); @@ -65,11 +64,10 @@ private File getFile(Socket socket) return new File(directory, fileName); } - private String getFileName(Socket socket) - { + private String getFileName(Socket socket) { final StringBuilder sb = new StringBuilder(FILE_PREFIX); sb.append("_"); - sb.append(df.format(new Date())); + sb.append(df.format(DateUtil.getDate())); sb.append("_"); sb.append(socket.getLocalAddress().getHostAddress()); sb.append("_"); @@ -82,50 +80,37 @@ private String getFileName(Socket socket) return sb.toString(); } - public synchronized void received(String s) - { - try - { + public synchronized void received(String s) { + try { print(format("<<< ", s)); - } - catch (IOException e) - { + } catch (IOException e) { logException(e); } } - public synchronized void sent(String s) - { - try - { + public synchronized void sent(String s) { + try { print(format(">>> ", s)); - } - catch (IOException e) - { + } catch (IOException e) { logException(e); } } - private void logException(IOException e) - { + private void logException(IOException e) { // avoid excessive failure logging - if (exceptionLogged) - { + if (exceptionLogged) { return; } logger.warn("Unable to write trace to disk", e); exceptionLogged = true; } - protected String format(String prefix, String s) - { - final StringBuilder sb = new StringBuilder(df.format(new Date())); + protected String format(String prefix, String s) { + final StringBuilder sb = new StringBuilder(df.format(DateUtil.getDate())); final String filler = String.format("%" + sb.length() + "s", ""); String[] lines = s.split("\n"); - for (int i = 0; i < lines.length; i++) - { - if (i != 0) - { + for (int i = 0; i < lines.length; i++) { + if (i != 0) { sb.append(filler); } sb.append(" "); @@ -136,25 +121,29 @@ protected String format(String prefix, String s) return sb.toString(); } - protected void print(String s) throws IOException - { + protected void print(String s) throws IOException { final CharBuffer charBuffer = CharBuffer.allocate(s.length()); charBuffer.put(s); charBuffer.flip(); print(charset.encode(charBuffer)); } - private void print(ByteBuffer byteBuffer) throws IOException - { + private void print(ByteBuffer byteBuffer) throws IOException { int bytesWritten = 0; - while (bytesWritten < byteBuffer.remaining()) - { + while (bytesWritten < byteBuffer.remaining()) { // Loop if only part of the buffer contents get written. bytesWritten = channel.write(byteBuffer); - if (bytesWritten == 0) - { + if (bytesWritten == 0) { throw new IOException("Unable to write trace to channel. Media may be full."); } } } + + public void close() { + try { + randomAccessFile.close(); + } catch (IOException e) { + logException(e); + } + } } diff --git a/src/main/java/org/asteriskjava/util/internal/JavaLoggingLog.java b/src/main/java/org/asteriskjava/util/internal/JavaLoggingLog.java index 163e0a734..7cf742460 100644 --- a/src/main/java/org/asteriskjava/util/internal/JavaLoggingLog.java +++ b/src/main/java/org/asteriskjava/util/internal/JavaLoggingLog.java @@ -17,21 +17,20 @@ package org.asteriskjava.util.internal; +import org.asteriskjava.util.Log; + import java.util.logging.Level; import java.util.logging.Logger; -import org.asteriskjava.util.Log; - /** - * Implementation of {@link Log} that maps to the Logger of - * the java.util.logging package. + * Implementation of {@link Log} that maps to the Logger of the + * java.util.logging package. *

        * Kindly donated by Sun's Steve Drach. - * + * * @author drach */ -public class JavaLoggingLog implements Log -{ +public class JavaLoggingLog implements Log { /** * The underlying commons-logging Log object to use. */ @@ -40,108 +39,97 @@ public class JavaLoggingLog implements Log /** * Creates a new JavaLoggingLog obtained from java.util.logging for the * given class. - * + * * @param clazz the class to log for. */ - public JavaLoggingLog(Class clazz) - { + public JavaLoggingLog(Class clazz) { log = Logger.getLogger(clazz.getName()); } - public void debug(Object obj) - { + public void debug(Object obj) { StackTraceElement ste = getInvokerSTE(); - if (ste != null) - { + if (ste != null) { log.logp(Level.FINE, ste.getClassName(), ste.getMethodName(), obj.toString()); - } - else - { + } else { log.fine(obj.toString()); } } - public void info(Object obj) - { + public void info(Object obj) { StackTraceElement ste = getInvokerSTE(); - if (ste != null) - { + if (ste != null) { log.logp(Level.INFO, ste.getClassName(), ste.getMethodName(), obj.toString()); - } - else - { + } else { log.info(obj.toString()); } } - public void warn(Object obj) - { + public void warn(Object obj) { StackTraceElement ste = getInvokerSTE(); - if (ste != null) - { + if (ste != null) { log.logp(Level.WARNING, ste.getClassName(), ste.getMethodName(), obj.toString()); - } - else - { + } else { log.warning(obj.toString()); } } - public void warn(Object obj, Throwable ex) - { + public void warn(Object obj, Throwable ex) { StackTraceElement ste = getInvokerSTE(); - if (ste != null) - { + if (ste != null) { log.logp(Level.WARNING, ste.getClassName(), ste.getMethodName(), obj.toString(), ex); - } - else - { + } else { log.log(Level.WARNING, obj.toString(), ex); } } - public void error(Object obj) - { + public void error(Object obj) { StackTraceElement ste = getInvokerSTE(); - if (ste != null) - { + if (ste != null) { log.logp(Level.SEVERE, ste.getClassName(), ste.getMethodName(), obj.toString()); - } - else - { + } else { log.severe(obj.toString()); } } - public void error(Object obj, Throwable ex) - { + public void error(Object obj, Throwable ex) { StackTraceElement ste = getInvokerSTE(); - if (ste != null) - { + if (ste != null) { log.logp(Level.SEVERE, ste.getClassName(), ste.getMethodName(), obj.toString(), ex); - } - else - { + } else { log.log(Level.SEVERE, obj.toString(), ex); } } - private StackTraceElement getInvokerSTE() - { - StackTraceElement stack[] = (new Throwable()).getStackTrace(); + private StackTraceElement getInvokerSTE() { + StackTraceElement[] stack = (new Throwable()).getStackTrace(); - if (stack.length > 2) - { + if (stack.length > 2) { return stack[2]; } return null; } + @Override + public boolean isDebugEnabled() { + return log.isLoggable(Level.FINE); + } + + @Override + public void debug(Object e, Throwable e2) { + StackTraceElement ste = getInvokerSTE(); + + if (ste != null) { + log.logp(Level.FINE, ste.getClassName(), ste.getMethodName(), e.toString(), e2); + } else { + log.log(Level.FINE, e.toString(), e2); + } + } + } diff --git a/src/main/java/org/asteriskjava/util/internal/LocationAwareWrapper.java b/src/main/java/org/asteriskjava/util/internal/LocationAwareWrapper.java new file mode 100644 index 000000000..3bd3df9b7 --- /dev/null +++ b/src/main/java/org/asteriskjava/util/internal/LocationAwareWrapper.java @@ -0,0 +1,372 @@ +package org.asteriskjava.util.internal; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.spi.LocationAwareLogger; + +public class LocationAwareWrapper implements Logger { + + private String FQCN; + private LocationAwareLogger logger; + + public LocationAwareWrapper(String FQCN, LocationAwareLogger logger) { + this.FQCN = FQCN; + this.logger = logger; + } + + @Override + public String getName() { + return logger.getName(); + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String msg) { + logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, null); + + } + + @Override + public void trace(String format, Object arg) { + logger.trace(format, arg); + + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + logger.trace(format, arg1, arg2); + + } + + @Override + public void trace(String format, Object... arguments) { + logger.trace(format, arguments); + + } + + @Override + public void trace(String msg, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, t); + + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return logger.isTraceEnabled(marker); + } + + @Override + public void trace(Marker marker, String msg) { + logger.log(marker, FQCN, LocationAwareLogger.TRACE_INT, msg, null, null); + + } + + @Override + public void trace(Marker marker, String format, Object arg) { + logger.trace(marker, format, arg); + + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + logger.trace(marker, format, arg1, arg2); + + } + + @Override + public void trace(Marker marker, String format, Object... arguments) { + logger.trace(marker, format, arguments); + + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + logger.log(marker, FQCN, LocationAwareLogger.TRACE_INT, msg, null, t); + + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String msg) { + logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, null); + + } + + @Override + public void debug(String format, Object arg) { + logger.debug(format, arg); + + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + logger.debug(format, arg1, arg2); + + } + + @Override + public void debug(String format, Object... arguments) { + logger.debug(format, arguments); + + } + + @Override + public void debug(String msg, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, t); + + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return logger.isDebugEnabled(marker); + } + + @Override + public void debug(Marker marker, String msg) { + logger.log(marker, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, null); + + } + + @Override + public void debug(Marker marker, String format, Object arg) { + logger.debug(marker, format, arg); + + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + logger.debug(marker, format, arg1, arg2); + + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + logger.debug(marker, format, arguments); + + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + logger.log(marker, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, t); + + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String msg) { + logger.log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, null); + + } + + @Override + public void info(String format, Object arg) { + logger.info(format, arg); + + } + + @Override + public void info(String format, Object arg1, Object arg2) { + logger.info(format, arg1, arg2); + + } + + @Override + public void info(String format, Object... arguments) { + logger.info(format, arguments); + + } + + @Override + public void info(String msg, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, t); + + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return logger.isInfoEnabled(marker); + } + + @Override + public void info(Marker marker, String msg) { + logger.log(marker, FQCN, LocationAwareLogger.INFO_INT, msg, null, null); + + } + + @Override + public void info(Marker marker, String format, Object arg) { + logger.info(marker, format, arg); + + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + logger.info(marker, format, arg1, arg2); + + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + logger.info(marker, format, arguments); + + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + logger.log(marker, FQCN, LocationAwareLogger.INFO_INT, msg, null, t); + + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String msg) { + logger.log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, null); + + } + + @Override + public void warn(String format, Object arg) { + logger.warn(format, arg); + + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + logger.warn(format, arg1, arg2); + + } + + @Override + public void warn(String format, Object... arguments) { + logger.warn(format, arguments); + + } + + @Override + public void warn(String msg, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, t); + + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return logger.isWarnEnabled(marker); + } + + @Override + public void warn(Marker marker, String msg) { + logger.log(marker, FQCN, LocationAwareLogger.WARN_INT, msg, null, null); + + } + + @Override + public void warn(Marker marker, String format, Object arg) { + logger.warn(marker, format, arg); + + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + logger.warn(marker, format, arg1, arg2); + + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + logger.warn(marker, format, arguments); + + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + logger.log(marker, FQCN, LocationAwareLogger.WARN_INT, msg, null, t); + + } + + @Override + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + @Override + public void error(String msg) { + logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, null); + + } + + @Override + public void error(String format, Object arg) { + logger.error(format, arg); + + } + + @Override + public void error(String format, Object arg1, Object arg2) { + logger.error(format, arg1, arg2); + + } + + @Override + public void error(String format, Object... arguments) { + logger.error(format, arguments); + + } + + @Override + public void error(String msg, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, t); + + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return logger.isErrorEnabled(marker); + } + + @Override + public void error(Marker marker, String msg) { + logger.log(marker, FQCN, LocationAwareLogger.ERROR_INT, msg, null, null); + + } + + @Override + public void error(Marker marker, String format, Object arg) { + logger.error(marker, format, arg); + + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + logger.error(marker, format, arg1, arg2); + + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + logger.error(marker, format, arguments); + + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + logger.log(marker, FQCN, LocationAwareLogger.ERROR_INT, msg, null, t); + + } + // Logger logger = LogManager.getLogger(); +} diff --git a/src/main/java/org/asteriskjava/util/internal/Log4JLogger.java b/src/main/java/org/asteriskjava/util/internal/Log4JLogger.java index 03b9a660d..d9ea34c9b 100644 --- a/src/main/java/org/asteriskjava/util/internal/Log4JLogger.java +++ b/src/main/java/org/asteriskjava/util/internal/Log4JLogger.java @@ -1,12 +1,12 @@ /* * Copyright 2001-2004 The Apache Software Foundation. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,25 +16,29 @@ package org.asteriskjava.util.internal; -import java.io.Serializable; -import org.apache.log4j.Logger; -import org.apache.log4j.Priority; -import org.apache.log4j.Level; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.spi.AbstractLogger; import org.asteriskjava.util.Log; +import java.io.Serializable; + /** - * Implementation of {@link Log} that maps directly to a Log4J Logger.

        + * Implementation of {@link Log} that maps directly to a Log4J + * Logger. + *

        * Initial configuration of the corresponding Logger instances should be done in - * the usual manner, as outlined in the Log4J documentation.

        + * the usual manner, as outlined in the Log4J documentation. + *

        * More or less "stolen" from Apache's commons-logging. - * + * * @author Scott Sanders * @author Rod Waldhoff * @author Robert Burrell Donkin * @version $Id$ */ -public class Log4JLogger implements Log, Serializable -{ +public class Log4JLogger implements Log, Serializable { // ------------------------------------------------------------- Attributes @@ -43,30 +47,21 @@ public class Log4JLogger implements Log, Serializable */ private static final long serialVersionUID = 3545240215095883829L; - /** The fully qualified name of the Log4JLogger class. */ + /** + * The fully qualified name of the Log4JLogger class. + */ private static final String FQCN = Log4JLogger.class.getName(); - private static final boolean IS12 = Priority.class.isAssignableFrom(Level.class); - - /** Log to this logger */ - private transient Logger logger = null; // NOPMD by srt on 7/5/06 11:18 PM - - /** Logger name */ - private String name = null; - - // ------------------------------------------------------------ Constructor - - public Log4JLogger() - { - } + /** + * Log to this logger + */ + private transient final AbstractLogger logger; /** * Base constructor. */ - public Log4JLogger(Class clazz) - { - this.name = clazz.getName(); - this.logger = getLogger(); + public Log4JLogger(Class clazz) { + this.logger = (AbstractLogger) LogManager.getLogger(clazz.getName()); } // --------------------------------------------------------- Implementation @@ -75,244 +70,136 @@ public Log4JLogger(Class clazz) * Log a message to the Log4j Logger with TRACE priority. * Currently logs to DEBUG level in Log4J. */ - public void trace(Object message) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.DEBUG, message, null); - } - else - { - getLogger().log(FQCN, Level.DEBUG, message, null); - } + public void trace(Object message) { + logger.logIfEnabled(FQCN, Level.TRACE, null, message, (Throwable) null); } /** * Log an error to the Log4j Logger with TRACE priority. * Currently logs to DEBUG level in Log4J. */ - public void trace(Object message, Throwable t) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.DEBUG, message, t); - } - else - { - getLogger().log(FQCN, Level.DEBUG, message, t); - } + public void trace(Object message, Throwable t) { + logger.logIfEnabled(FQCN, Level.TRACE, null, message, t); } /** * Log a message to the Log4j Logger with DEBUG priority. */ - public void debug(Object message) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.DEBUG, message, null); - } - else - { - getLogger().log(FQCN, Level.DEBUG, message, null); - } + @Override + public void debug(Object message) { + logger.logIfEnabled(FQCN, Level.DEBUG, null, message, (Throwable) null); } /** * Log an error to the Log4j Logger with DEBUG priority. */ - public void debug(Object message, Throwable t) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.DEBUG, message, t); - } - else - { - getLogger().log(FQCN, Level.DEBUG, message, t); - } + @Override + public void debug(Object message, Throwable t) { + logger.logIfEnabled(FQCN, Level.DEBUG, null, message, t); } /** * Log a message to the Log4j Logger with INFO priority. */ - public void info(Object message) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.INFO, message, null); - } - else - { - getLogger().log(FQCN, Level.INFO, message, null); - } + @Override + public void info(Object message) { + logger.logIfEnabled(FQCN, Level.INFO, null, message, (Throwable) null); + } /** * Log an error to the Log4j Logger with INFO priority. */ - public void info(Object message, Throwable t) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.INFO, message, t); - } - else - { - getLogger().log(FQCN, Level.INFO, message, t); - } + public void info(Object message, Throwable t) { + logger.logIfEnabled(FQCN, Level.INFO, null, message, t); } /** * Log a message to the Log4j Logger with WARN priority. */ - public void warn(Object message) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.WARN, message, null); - } - else - { - getLogger().log(FQCN, Level.WARN, message, null); - } + @Override + public void warn(Object message) { + logger.logIfEnabled(FQCN, Level.WARN, null, message, (Throwable) null); } /** * Log an error to the Log4j Logger with WARN priority. */ - public void warn(Object message, Throwable t) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.WARN, message, t); - } - else - { - getLogger().log(FQCN, Level.WARN, message, t); - } + @Override + public void warn(Object message, Throwable t) { + logger.logIfEnabled(FQCN, Level.WARN, null, message, t); } /** * Log a message to the Log4j Logger with ERROR priority. */ - public void error(Object message) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.ERROR, message, null); - } - else - { - getLogger().log(FQCN, Level.ERROR, message, null); - } + @Override + public void error(Object message) { + logger.logIfEnabled(FQCN, Level.ERROR, null, message, (Throwable) null); } /** * Log an error to the Log4j Logger with ERROR priority. */ - public void error(Object message, Throwable t) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.ERROR, message, t); - } - else - { - getLogger().log(FQCN, Level.ERROR, message, t); - } + @Override + public void error(Object message, Throwable t) { + logger.logIfEnabled(FQCN, Level.ERROR, null, message, t); } /** * Log a message to the Log4j Logger with FATAL priority. */ - public void fatal(Object message) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.FATAL, message, null); - } - else - { - getLogger().log(FQCN, Level.FATAL, message, null); - } + public void fatal(Object message) { + logger.logIfEnabled(FQCN, Level.FATAL, null, message, (Throwable) null); } /** * Log an error to the Log4j Logger with FATAL priority. */ - public void fatal(Object message, Throwable t) - { - if (IS12) - { - getLogger().log(FQCN, (Priority) Level.FATAL, message, t); - } - else - { - getLogger().log(FQCN, Level.FATAL, message, t); - } + public void fatal(Object message, Throwable t) { + logger.logIfEnabled(FQCN, Level.FATAL, null, message, t); } /** * Return the native Logger instance we are using. */ - public final Logger getLogger() - { - if (logger == null) - { - logger = Logger.getLogger(name); - } - return (this.logger); + public final Logger getLogger() { + return logger; } /** * Check whether the Log4j Logger used is enabled for DEBUG * priority. */ - public boolean isDebugEnabled() - { - return getLogger().isDebugEnabled(); + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); } /** * Check whether the Log4j Logger used is enabled for ERROR * priority. */ - public boolean isErrorEnabled() - { - if (IS12) - { - return getLogger().isEnabledFor((Priority) Level.ERROR); - } - else - { - return getLogger().isEnabledFor(Level.ERROR); - } + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } /** * Check whether the Log4j Logger used is enabled for FATAL * priority. */ - public boolean isFatalEnabled() - { - if (IS12) - { - return getLogger().isEnabledFor((Priority) Level.FATAL); - } - else - { - return getLogger().isEnabledFor(Level.FATAL); - } + public boolean isFatalEnabled() { + return logger.isFatalEnabled(); + } /** * Check whether the Log4j Logger used is enabled for INFO * priority. */ - public boolean isInfoEnabled() - { - return getLogger().isInfoEnabled(); + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); } /** @@ -320,24 +207,15 @@ public boolean isInfoEnabled() * priority. For Log4J, this returns the value of * isDebugEnabled() */ - public boolean isTraceEnabled() - { - return getLogger().isDebugEnabled(); + public boolean isTraceEnabled() { + return logger.isDebugEnabled(); } /** * Check whether the Log4j Logger used is enabled for WARN * priority. */ - public boolean isWarnEnabled() - { - if (IS12) - { - return getLogger().isEnabledFor((Priority) Level.WARN); - } - else - { - return getLogger().isEnabledFor(Level.WARN); - } + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); } } diff --git a/src/main/java/org/asteriskjava/util/internal/NullLog.java b/src/main/java/org/asteriskjava/util/internal/NullLog.java index acfdf21df..445080be5 100644 --- a/src/main/java/org/asteriskjava/util/internal/NullLog.java +++ b/src/main/java/org/asteriskjava/util/internal/NullLog.java @@ -19,44 +19,46 @@ import org.asteriskjava.util.Log; /** - * A Log implementation that does nothing.

        - * This logger is only used if neither log4j nor java.util.logging are - * available which should not happen anyway as Asterisk-Java depends on - * at least JDK 1.5. - * + * A Log implementation that does nothing. + *

        + * This logger is only used if neither log4j nor java.util.logging are available + * which should not happen anyway as Asterisk-Java depends on at least JDK 1.5. + * * @author srt * @version $Id$ */ -public class NullLog implements Log -{ +public class NullLog implements Log { /** * Creates a new NullLog. */ - public NullLog() - { + public NullLog() { + } + + public void debug(Object obj) { } - public void debug(Object obj) - { + public void info(Object obj) { } - public void info(Object obj) - { + public void warn(Object obj) { } - public void warn(Object obj) - { + public void warn(Object obj, Throwable ex) { } - public void warn(Object obj, Throwable ex) - { + public void error(Object obj) { } - public void error(Object obj) - { + public void error(Object obj, Throwable ex) { } - public void error(Object obj, Throwable ex) - { + @Override + public boolean isDebugEnabled() { + return false; + } + + @Override + public void debug(Object e, Throwable e2) { + } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/util/internal/ServerSocketFacadeImpl.java b/src/main/java/org/asteriskjava/util/internal/ServerSocketFacadeImpl.java index a947ba014..ccef0449c 100644 --- a/src/main/java/org/asteriskjava/util/internal/ServerSocketFacadeImpl.java +++ b/src/main/java/org/asteriskjava/util/internal/ServerSocketFacadeImpl.java @@ -16,43 +16,45 @@ */ package org.asteriskjava.util.internal; +import org.asteriskjava.util.ServerSocketFacade; +import org.asteriskjava.util.SocketConnectionFacade; + import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; -import org.asteriskjava.util.ServerSocketFacade; -import org.asteriskjava.util.SocketConnectionFacade; - /** * Default implementation of the ServerSocketFacade interface using standard * java.io classes (ServerSocket in this case). - * + * * @author srt * @version $Id$ */ -public class ServerSocketFacadeImpl implements ServerSocketFacade -{ +public class ServerSocketFacadeImpl implements ServerSocketFacade { private ServerSocket serverSocket; + private int socketReadTimeout = SocketConnectionFacadeImpl.MAX_SOCKET_READ_TIMEOUT_MILLIS; + public ServerSocketFacadeImpl(int port, int backlog, InetAddress bindAddress) - throws IOException - { + throws IOException { this.serverSocket = new ServerSocket(port, backlog, bindAddress); } - public SocketConnectionFacade accept() throws IOException - { + public SocketConnectionFacade accept() throws IOException { Socket socket; socket = serverSocket.accept(); - return new SocketConnectionFacadeImpl(socket); + return new SocketConnectionFacadeImpl(socket, socketReadTimeout); } - public void close() throws IOException - { + public void close() throws IOException { serverSocket.close(); } + + public void setSocketReadTimeout(int socketReadTimeout) { + this.socketReadTimeout = socketReadTimeout; + } } diff --git a/src/main/java/org/asteriskjava/util/internal/Slf4JLogger.java b/src/main/java/org/asteriskjava/util/internal/Slf4JLogger.java index 7e7dea1b5..0f208f44f 100644 --- a/src/main/java/org/asteriskjava/util/internal/Slf4JLogger.java +++ b/src/main/java/org/asteriskjava/util/internal/Slf4JLogger.java @@ -1,12 +1,12 @@ /* * Copyright 2001-2004 The Apache Software Foundation. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,36 +19,42 @@ import org.asteriskjava.util.Log; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.spi.LocationAwareLogger; import java.io.Serializable; /** - * Implementation of {@link org.asteriskjava.util.Log} that maps to a SLF4J Logger.

        + * Implementation of {@link org.asteriskjava.util.Log} that maps to a SLF4J + * Logger. + *

        * * @version $Id$ */ -public class Slf4JLogger implements Log, Serializable -{ +public class Slf4JLogger implements Log, Serializable { /** * The serial version identifier. */ private static final long serialVersionUID = 0L; - /** Log to this logger */ + /** + * Log to this logger + */ private transient Logger logger = null; - /** Logger name */ + static String FQCN = Slf4JLogger.class.getName(); + + /** + * Logger name + */ private Class clazz = null; - public Slf4JLogger() - { + public Slf4JLogger() { } /** * Base constructor. */ - public Slf4JLogger(Class clazz) - { + public Slf4JLogger(Class clazz) { this.clazz = clazz; this.logger = getLogger(); } @@ -57,119 +63,109 @@ public Slf4JLogger(Class clazz) * Log a message to the SLF4J Logger with TRACE priority. * Currently logs to DEBUG level in SLF4J. */ - public void trace(Object message) - { + public void trace(Object message) { getLogger().trace(message.toString()); } /** * Log an error to the SLF4J Logger with TRACE priority. */ - public void trace(Object message, Throwable t) - { + public void trace(Object message, Throwable t) { getLogger().trace(message.toString(), t); } /** * Log a message to the SLF4J Logger with DEBUG priority. */ - public void debug(Object message) - { + public void debug(Object message) { getLogger().debug(message.toString()); } /** * Log an error to the SLF4J Logger with DEBUG priority. */ - public void debug(Object message, Throwable t) - { + public void debug(Object message, Throwable t) { getLogger().debug(message.toString(), t); } /** * Log a message to the SLF4J Logger with INFO priority. */ - public void info(Object message) - { + public void info(Object message) { getLogger().info(message.toString()); } /** * Log an error to the SLF4J Logger with INFO priority. */ - public void info(Object message, Throwable t) - { + public void info(Object message, Throwable t) { getLogger().info(message.toString(), t); } /** * Log a message to the SLF4J Logger with WARN priority. */ - public void warn(Object message) - { + public void warn(Object message) { getLogger().warn(message.toString()); } /** * Log an error to the SLF4J Logger with WARN priority. */ - public void warn(Object message, Throwable t) - { + public void warn(Object message, Throwable t) { getLogger().warn(message.toString(), t); } /** * Log a message to the SLF4J Logger with ERROR priority. */ - public void error(Object message) - { + public void error(Object message) { getLogger().error(message.toString()); } /** * Log an error to the SLF4J Logger with ERROR priority. */ - public void error(Object message, Throwable t) - { + public void error(Object message, Throwable t) { getLogger().error(message.toString(), t); } /** - * Log a message to the SLF4J Logger with FATAL priority.

        + * Log a message to the SLF4J Logger with FATAL priority. + *

        * Currently uses the ERROR priority in SLF4J. */ - public void fatal(Object message) - { + public void fatal(Object message) { getLogger().error(message.toString()); } /** - * Log an error to the SLF4J Logger with FATAL priority.

        + * Log an error to the SLF4J Logger with FATAL priority. + *

        * Currently uses the ERROR priority in SLF4J. */ - public void fatal(Object message, Throwable t) - { + public void fatal(Object message, Throwable t) { getLogger().error(message.toString(), t); } /** * Return the native Logger instance we are using. */ - public final Logger getLogger() - { - if (logger == null) - { + public final Logger getLogger() { + if (logger == null) { logger = LoggerFactory.getLogger(clazz); } - return (this.logger); + if (logger instanceof LocationAwareLogger) { + return new LocationAwareWrapper(FQCN, (LocationAwareLogger) logger); + } + return this.logger; } /** * Check whether the SLF4J Logger used is enabled for DEBUG * priority. */ - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return getLogger().isDebugEnabled(); } @@ -177,17 +173,16 @@ public boolean isDebugEnabled() * Check whether the SLF4J Logger used is enabled for ERROR * priority. */ - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return getLogger().isErrorEnabled(); } /** * Check whether the SLF4J Logger used is enabled for FATAL - * priority. For SLF4J, this returns the value of isErrorEnabled() + * priority. For SLF4J, this returns the value of + * isErrorEnabled() */ - public boolean isFatalEnabled() - { + public boolean isFatalEnabled() { return isErrorEnabled(); } @@ -195,8 +190,7 @@ public boolean isFatalEnabled() * Check whether the SLF4J Logger used is enabled for INFO * priority. */ - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return getLogger().isInfoEnabled(); } @@ -204,8 +198,7 @@ public boolean isInfoEnabled() * Check whether the SLF4J Logger used is enabled for TRACE * priority. */ - public boolean isTraceEnabled() - { + public boolean isTraceEnabled() { return getLogger().isDebugEnabled(); } @@ -213,8 +206,7 @@ public boolean isTraceEnabled() * Check whether the SLF4J Logger used is enabled for WARN * priority. */ - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return getLogger().isWarnEnabled(); } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/util/internal/SocketConnectionFacadeImpl.java b/src/main/java/org/asteriskjava/util/internal/SocketConnectionFacadeImpl.java index 1f395ff6a..e50c6f0be 100644 --- a/src/main/java/org/asteriskjava/util/internal/SocketConnectionFacadeImpl.java +++ b/src/main/java/org/asteriskjava/util/internal/SocketConnectionFacadeImpl.java @@ -16,43 +16,38 @@ */ package org.asteriskjava.util.internal; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; +import org.asteriskjava.util.SocketConnectionFacade; +import org.asteriskjava.util.internal.streamreader.FastScanner; +import org.asteriskjava.util.internal.streamreader.FastScannerFactory; + +import javax.net.SocketFactory; +import javax.net.ssl.SSLSocketFactory; +import java.io.*; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; -import java.util.Scanner; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.NoSuchElementException; import java.util.regex.Pattern; -import javax.net.SocketFactory; -import javax.net.ssl.SSLSocketFactory; - -import org.asteriskjava.util.SocketConnectionFacade; - - /** * Default implementation of the SocketConnectionFacade interface using java.io. * * @author srt * @version $Id$ */ -public class SocketConnectionFacadeImpl implements SocketConnectionFacade -{ +public class SocketConnectionFacadeImpl implements SocketConnectionFacade { public static final Pattern CRNL_PATTERN = Pattern.compile("\r\n"); public static final Pattern NL_PATTERN = Pattern.compile("\n"); private Socket socket; - private Scanner scanner; + private FastScanner scanner; private BufferedWriter writer; private Trace trace; /** - * Creates a new instance for use with the Manager API that uses CRNL ("\r\n") as line delimiter. + * Creates a new instance for use with the Manager API that uses UTF-8 + * as the encoding and CRLF ("\r\n") as line delimiter. * * @param host the foreign host to connect to. * @param port the foreign port to connect to. @@ -61,149 +56,181 @@ public class SocketConnectionFacadeImpl implements SocketConnectionFacade * @param readTimeout see {@link Socket#setSoTimeout(int)} * @throws IOException if the connection cannot be established. */ - public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeout, int readTimeout) throws IOException - { - this(host, port, ssl, timeout, readTimeout, CRNL_PATTERN); + public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeout, int readTimeout) throws IOException { + this(host, port, ssl, timeout, readTimeout, StandardCharsets.UTF_8, CRNL_PATTERN); } - + /** - * Creates a new instance for use with the Manager API that uses the given line delimiter. + * Creates a new instance for use with the Manager API that uses the given + * encoding and CRLF ("\r\n") as line delimiter. * * @param host the foreign host to connect to. * @param port the foreign port to connect to. * @param ssl true to use SSL, false otherwise. * @param timeout 0 incidcates default * @param readTimeout see {@link Socket#setSoTimeout(int)} - * @param lineDelimiter a {@link Pattern} for matching the line delimiter for the socket + * @param encoding the encoding used for transmission of strings (all + * connections should use the same encoding) + * @throws IOException if the connection cannot be established. + */ + public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeout, int readTimeout, Charset encoding) + throws IOException { + this(host, port, ssl, timeout, readTimeout, encoding, CRNL_PATTERN); + } + + /** + * Creates a new instance for use with the Manager API that uses UTF-8 as + * encoding and the given line delimiter. + * + * @param host the foreign host to connect to. + * @param port the foreign port to connect to. + * @param ssl true to use SSL, false otherwise. + * @param timeout 0 incidcates default + * @param readTimeout see {@link Socket#setSoTimeout(int)} + * @param lineDelimiter a {@link Pattern} for matching the line delimiter + * for the socket + * @throws IOException if the connection cannot be established. + */ + public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeout, int readTimeout, + Pattern lineDelimiter) throws IOException { + this(host, port, ssl, timeout, readTimeout, StandardCharsets.UTF_8, lineDelimiter); + } + + /** + * Creates a new instance for use with the Manager API that uses the given + * encoding and line delimiter. + * + * @param host the foreign host to connect to. + * @param port the foreign port to connect to. + * @param ssl true to use SSL, false otherwise. + * @param timeout 0 incidcates default + * @param readTimeout see {@link Socket#setSoTimeout(int)} + * @param encoding the encoding used for transmission of strings (all + * connections should use the same encoding) + * @param lineDelimiter a {@link Pattern} for matching the line delimiter + * for the socket * @throws IOException if the connection cannot be established. */ - public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeout, int readTimeout, Pattern lineDelimiter) throws IOException - { + public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeout, int readTimeout, Charset encoding, + Pattern lineDelimiter) throws IOException { Socket socket; - if (ssl) - { + if (ssl) { socket = SSLSocketFactory.getDefault().createSocket(); - } - else - { + } else { socket = SocketFactory.getDefault().createSocket(); } socket.setSoTimeout(readTimeout); socket.connect(new InetSocketAddress(host, port), timeout); - initialize(socket, lineDelimiter); - if (System.getProperty(Trace.TRACE_PROPERTY, "false").equalsIgnoreCase("true")) - { + initialize(socket, encoding, lineDelimiter); + if (System.getProperty(Trace.TRACE_PROPERTY, "false").equalsIgnoreCase("true")) { trace = new FileTrace(socket); } } /** - * Creates a new instance for use with FastAGI that uses NL ("\n") as line delimiter. + * Creates a new instance for use with FastAGI that uses NL ("\n") as line + * delimiter. * * @param socket the underlying socket. * @throws IOException if the connection cannot be initialized. */ - SocketConnectionFacadeImpl(Socket socket) throws IOException - { - initialize(socket, NL_PATTERN); + SocketConnectionFacadeImpl(Socket socket) throws IOException { + this(socket, MAX_SOCKET_READ_TIMEOUT_MILLIS); + } + + /** + * Creates a new instance for use with FastAGI that uses NL ("\n") as line delimiter. + * + * @param socket the underlying socket. + * @param timeout 0 indicates default, -1 indicates infinite timeout (not recommended) + * @throws IOException if the connection cannot be initialized. + */ + SocketConnectionFacadeImpl(Socket socket, int timeout) throws IOException { + if (timeout == -1) { + timeout = 0; + } else if (timeout == 0) { + timeout = MAX_SOCKET_READ_TIMEOUT_MILLIS; + } + socket.setSoTimeout(timeout); + initialize(socket, StandardCharsets.UTF_8, NL_PATTERN); } - private void initialize(Socket socket, Pattern pattern) throws IOException - { + /** + * 3 hrs = 3 * 3660 * 1000 + */ + public static final int MAX_SOCKET_READ_TIMEOUT_MILLIS = 10800000; + + private void initialize(Socket socket, Charset encoding, Pattern pattern) throws IOException { this.socket = socket; InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + InputStreamReader reader = new InputStreamReader(inputStream, encoding); - this.scanner = new Scanner(reader); - this.scanner.useDelimiter(pattern); - this.writer = new BufferedWriter(new OutputStreamWriter(outputStream)); + this.scanner = FastScannerFactory.getReader(reader, pattern); + // this.scanner.useDelimiter(pattern); + this.writer = new BufferedWriter(new OutputStreamWriter(outputStream, encoding)); } - public String readLine() throws IOException - { - String line; - try - { + @Override + public String readLine() throws IOException { + String line = null; + try { line = scanner.next(); - } - catch (IllegalStateException e) - { - if (scanner.ioException() != null) - { - throw scanner.ioException(); - } - else - { - // throw new IOException("No more lines available", e); // JDK6 - throw new IOException("No more lines available: " + e.getMessage()); - } - } - catch (NoSuchElementException e) - { - if (scanner.ioException() != null) - { - throw scanner.ioException(); - } - else - { - // throw new IOException("No more lines available", e); // JDK6 - throw new IOException("No more lines available: " + e.getMessage()); - } + + } catch (IllegalStateException e) { + // throw new IOException("No more lines available", e); // JDK6 + throw new IOException("No more lines available: " + e.getMessage()); + } catch (NoSuchElementException e) { + // throw new IOException("No more lines available", e); // JDK6 + throw new IOException("No more lines available: " + e.getMessage()); } - if (trace != null) - { + if (trace != null) { trace.received(line); } return line; } - public void write(String s) throws IOException - { + public void write(String s) throws IOException { writer.write(s); - if (trace != null) - { + if (trace != null) { trace.sent(s); } } - public void flush() throws IOException - { + public void flush() throws IOException { writer.flush(); } - public void close() throws IOException - { + public void close() throws IOException { socket.close(); scanner.close(); + // close the trace only if it was activated (the object is not null) + if (trace != null) { + trace.close(); + } } - public boolean isConnected() - { + public boolean isConnected() { return socket.isConnected(); } - public InetAddress getLocalAddress() - { + public InetAddress getLocalAddress() { return socket.getLocalAddress(); } - public int getLocalPort() - { + public int getLocalPort() { return socket.getLocalPort(); } - public InetAddress getRemoteAddress() - { + public InetAddress getRemoteAddress() { return socket.getInetAddress(); } - public int getRemotePort() - { + public int getRemotePort() { return socket.getPort(); } } diff --git a/src/main/java/org/asteriskjava/util/internal/Trace.java b/src/main/java/org/asteriskjava/util/internal/Trace.java index 518d0c217..924d0a9ce 100644 --- a/src/main/java/org/asteriskjava/util/internal/Trace.java +++ b/src/main/java/org/asteriskjava/util/internal/Trace.java @@ -3,8 +3,7 @@ /** * Interface for tracing network traffic. */ -public interface Trace -{ +public interface Trace { /** * Name of the system property to enable tracing.

        * To enable tracing add -Dorg.asteriskjava.trace=true to the vm parameters when running Asterisk-Java. @@ -13,13 +12,21 @@ public interface Trace /** * Writes data that has been received from the network to the trace. + * * @param s the String that has been received. */ void received(String s); /** * Writes data that has been sent to the network to the trace. + * * @param s the String that has been sent. */ void sent(String s); + + + /** + * Closes allocated resources by trace implementation. + */ + void close(); } diff --git a/src/main/java/org/asteriskjava/util/internal/package.html b/src/main/java/org/asteriskjava/util/internal/package.html index e3b52ed3f..c9cec1a4a 100644 --- a/src/main/java/org/asteriskjava/util/internal/package.html +++ b/src/main/java/org/asteriskjava/util/internal/package.html @@ -1,28 +1,28 @@ - +

        Provides private implementations for interfaces defined in the - org.asteriskjava.util package.

        + org.asteriskjava.util package.

        - \ No newline at end of file + diff --git a/src/main/java/org/asteriskjava/util/internal/streamreader/FastScanner.java b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScanner.java new file mode 100644 index 000000000..5ca4eebde --- /dev/null +++ b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScanner.java @@ -0,0 +1,9 @@ +package org.asteriskjava.util.internal.streamreader; + +import java.io.Closeable; +import java.io.IOException; + +public interface FastScanner extends Closeable { + String next() throws IOException; + +} diff --git a/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerCrNl.java b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerCrNl.java new file mode 100644 index 000000000..cdbfac239 --- /dev/null +++ b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerCrNl.java @@ -0,0 +1,60 @@ +package org.asteriskjava.util.internal.streamreader; + +public class FastScannerCrNl extends FastScannerNl { + + private char crChar = '\r'; + private boolean seenReturn = false; + + public FastScannerCrNl(Readable reader) { + super(reader); + + } + + protected String getLine(boolean endOfLine) { + // iterate the builder looking for the delimiter chars + for (int i = start; i < end; i++) { + if (cbuf.get(i) == crChar) { + // flag that we've encountered the first of the two delimiter + // characters + seenReturn = true; + } else if (seenReturn && cbuf.get(i) == nlChar) { + // we've seen both of the delimiter characters, package up the + // data and return it... + if (i == start) { + // back track to remove a /r in the last packet + result.setLength(result.length() - 1); + } + if (i > start) { + // append the data to the StringBuilder + result.append(cbuf.subSequence(start, start + (i - start) - 1)); + } + // skip the delimiter character + start = i + 1; + + // get the resulting line + String tmp = result.toString(); + + // clear the StringBuilder + result.setLength(0); + + // clear the delimiter seen flag + seenReturn = false; + + return tmp; + } else { + // clear the delimiter seen flag + seenReturn = false; + } + } + if (end >= start) { + // we've hit the end of the buffer, add the data to the + // StringBuilder and return null so as to get + // the next part of the line + result.append(cbuf.subSequence(start, start + (end - start))).toString(); + start = 0; + end = 0; + } + return null; + } + +} diff --git a/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerFactory.java b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerFactory.java new file mode 100644 index 000000000..10c48ac77 --- /dev/null +++ b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerFactory.java @@ -0,0 +1,59 @@ +package org.asteriskjava.util.internal.streamreader; + +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.io.IOException; +import java.util.NoSuchElementException; +import java.util.Scanner; +import java.util.regex.Pattern; + +public class FastScannerFactory { + private static final Log logger = LogFactory.getLog(FastScannerFactory.class); + + private static volatile boolean useLegacyScanner = false; + + public static FastScanner getReader(Readable reader, Pattern pattern) { + if (!useLegacyScanner) { + if (pattern.pattern().equals("\r\n")) { + return new FastScannerCrNl(reader); + } + if (pattern.pattern().equals("\n")) { + return new FastScannerNl(reader); + } + } + + // fall back to legacy Scanner + + logger.warn("Using legacy scanner"); + Scanner scanner = new Scanner(reader); + scanner.useDelimiter(pattern); + + return getWrappedScanner(scanner); + + } + + public static void useLegacyScanner(boolean b) { + useLegacyScanner = b; + } + + private static FastScanner getWrappedScanner(final Scanner scanner) { + return new FastScanner() { + + @Override + public String next() throws IOException { + try { + return scanner.next(); + } catch (NoSuchElementException e) { + return null; + } + } + + @Override + public void close() { + scanner.close(); + } + + }; + } +} diff --git a/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerNl.java b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerNl.java new file mode 100644 index 000000000..a24327aa9 --- /dev/null +++ b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerNl.java @@ -0,0 +1,171 @@ +package org.asteriskjava.util.internal.streamreader; + +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + +import java.io.BufferedWriter; +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; +import java.util.concurrent.atomic.AtomicReference; + +public class FastScannerNl implements FastScanner { + private static final Log logger = LogFactory.getLog(FastScannerNl.class); + + private static final int BUFFER_SIZE = 8192; + + private AtomicReference readableReference = new AtomicReference<>(); + protected char nlChar = '\n'; + protected StringBuilder result = new StringBuilder(80); + protected CharBuffer cbuf = CharBuffer.allocate(BUFFER_SIZE); + protected int end = 0; + protected int start = 0; + private boolean closed = false; + // protected final Object sync = new Object(); + + private boolean isFirst = true; + + File logfile; + + private BufferedWriter writer; + + public FastScannerNl(Readable reader) { + this.readableReference.set(reader); + + // createFileWriter(); + + } + + public String next() throws IOException { + int bytes = 0; + + // check for a line in the buffer + String line = getLine(false); + if (line == null) { + // doing this instead of a synchronized block to avoid a possible + // deadlock between calling readable.read() and a call to close() on + // another thread, which it appears that Asterisk-Java permits + // and/or does + Readable readable = readableReference.get(); + + // read from the stream to the buffer + while (readable != null && (bytes = readable.read(cbuf)) > -1) { + // writeToFile(bytes); + + // set buffer position to 0 + cbuf.position(0); + + end = bytes; + + // try to get a line from the buffer + line = getLine(bytes >= 0); + + if (line != null) { + if (isFirst && line.length() == 0) { + // if the first character of the stream is the line + // terminator, try again + line = getLine(bytes >= 0); + } + break; + } + } + + } + // clear the first line flag + isFirst = false; + if (line == null) { + // the line is empty, get the contents from the StringBuilder if any + String tmp = result.toString(); + result.setLength(0); + + // if the reader is closed and there is no output + if (readableReference.get() == null && tmp.length() == 0) { + return null; + } + + // if at the end of the inputStream and there is no output + if (bytes == -1 && tmp.length() == 0) { + return null; + } + return tmp; + } + return line; + + } + + protected String getLine(boolean endOfLine) { + // iterate the buffer, looking for the end character + for (int i = start; i < end; i++) { + if (cbuf.get(i) == nlChar) { + if (i > start) { + // add the buffer contents up to i to the output buffer + result.append(cbuf.subSequence(start, start + (i - start))); + } + // skip the delimiter + start = i + 1; + + // get the output + String tmp = result.toString(); + + // reset the StringBuilder to 0 to avoid re-allocating memory + result.setLength(0); + return tmp; + + } + } + if (end >= start) { + // we've hit the end of the buffer, copy the contents to the + // StringBuilder, then return null so we'll loop again and get the + // next part + result.append(cbuf.subSequence(start, start + (end - start))).toString(); + start = 0; + end = 0; + } + return null; + } + + public void close() { + // synchronized (sync) + // { + if (closed) + return; + if (readableReference.get() instanceof Closeable) { + try { + ((Closeable) readableReference.get()).close(); + // closeFileWriter(); + } catch (IOException ioe) { + logger.error(ioe, ioe); + } + } + readableReference.set(null); + closed = true; + // } + } + + @SuppressWarnings("unused") + private void createFileWriter() { + try { + logfile = File.createTempFile(this.getClass().getSimpleName(), "txt"); + writer = Files.newBufferedWriter(logfile.toPath(), Charset.defaultCharset(), StandardOpenOption.APPEND); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @SuppressWarnings("unused") + private void writeToFile(int bytes) throws IOException { + String lines = new StringBuffer().append(cbuf, 0, bytes).toString(); + writer.append(lines, 0, bytes); + } + + @SuppressWarnings("unused") + private void closeFileWriter() throws IOException { + writer.flush(); + writer.close(); + } + +} diff --git a/src/main/java/org/asteriskjava/util/package.html b/src/main/java/org/asteriskjava/util/package.html index 73afd0d9c..b855f4a09 100644 --- a/src/main/java/org/asteriskjava/util/package.html +++ b/src/main/java/org/asteriskjava/util/package.html @@ -1,30 +1,30 @@ - +

        Provides various utility classes used throughout the library.

        Client code is generally not supposed to use classes or interfaces in this packages - with the exception of the logging support if they want to reuse Asterisk-Java's - logging abstraction layer.

        + with the exception of the logging support if they want to reuse Asterisk-Java's + logging abstraction layer.

        - \ No newline at end of file + diff --git a/src/site/site.xml b/src/site/site.xml index a887ce0c0..c4d42660a 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -44,8 +44,7 @@ - + @@ -53,14 +52,6 @@ - - - - ${reports} diff --git a/src/test/java/org/asteriskjava/AsteriskVersionTest.java b/src/test/java/org/asteriskjava/AsteriskVersionTest.java new file mode 100644 index 000000000..37fec6b02 --- /dev/null +++ b/src/test/java/org/asteriskjava/AsteriskVersionTest.java @@ -0,0 +1,44 @@ +package org.asteriskjava; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AsteriskVersionTest { + @Test + void testNullIfNoMatch() { + assertNull(AsteriskVersion.getDetermineVersionFromString("")); + } + + @Test + void test13() { + assertTrue(AsteriskVersion.getDetermineVersionFromString("Asterisk 13.1.0~dfsg-1.1ubuntu4.1") + .equals(AsteriskVersion.ASTERISK_13)); + } + + @Test + void test14() { + assertTrue(AsteriskVersion.getDetermineVersionFromString("Asterisk 14.1.0").equals(AsteriskVersion.ASTERISK_14)); + } + + @Test + void test15() { + assertTrue(AsteriskVersion.getDetermineVersionFromString("Asterisk 15.1.0").equals(AsteriskVersion.ASTERISK_15)); + } + + @Test + void test18() { + assertTrue(AsteriskVersion.getDetermineVersionFromString("Asterisk 18.1.0").equals(AsteriskVersion.ASTERISK_18)); + } + + @Test + void testCertified18() { + assertTrue(AsteriskVersion.getDetermineVersionFromString("Asterisk certified/18.9-cert2").equals(AsteriskVersion.ASTERISK_18)); + } + + @Test + void testCertified22() { + assertTrue(AsteriskVersion.getDetermineVersionFromString("Asterisk certified-22.8-cert2").equals(AsteriskVersion.ASTERISK_22)); + } +} diff --git a/src/test/java/org/asteriskjava/config/ConfigFileParserTest.java b/src/test/java/org/asteriskjava/config/ConfigFileParserTest.java index c65eeede1..9327f9bb1 100644 --- a/src/test/java/org/asteriskjava/config/ConfigFileParserTest.java +++ b/src/test/java/org/asteriskjava/config/ConfigFileParserTest.java @@ -1,21 +1,22 @@ package org.asteriskjava.config; -import junit.framework.TestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.CharBuffer; -public class ConfigFileParserTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.*; + +class ConfigFileParserTest { ConfigFileReader configFileReader; - @Override - public void setUp() - { + @BeforeEach + void setUp() { configFileReader = new ConfigFileReader(); } - public void testProcessLine() throws Exception - { + @Test + void testProcessLine() throws Exception { String s = " a ;-- comment --; = b ; a line comment"; CharBuffer buffer = CharBuffer.allocate(s.length()); @@ -24,132 +25,105 @@ public void testProcessLine() throws Exception configFileReader.appendCategory(new Category("cat")); ConfigElement configElement = configFileReader.processLine("test.conf", 1, buffer); - assertEquals("Incorrect type of configElement", ConfigVariable.class, configElement.getClass()); + assertEquals(ConfigVariable.class, configElement.getClass(), "Incorrect type of configElement"); ConfigVariable configVariable = (ConfigVariable) configElement; - assertEquals("Incorrect variable name", "a", configVariable.getName()); - assertEquals("Incorrect variable value", "b", configVariable.getValue()); - assertEquals("Incorrect comment", "a line comment", configElement.getComment()); + assertEquals("a", configVariable.getName(), "Incorrect variable name"); + assertEquals("b", configVariable.getValue(), "Incorrect variable value"); + assertEquals("a line comment", configElement.getComment(), "Incorrect comment"); } - public void testParseCategoryHeader() throws Exception - { + @Test + void testParseCategoryHeader() throws Exception { Category category; category = configFileReader.parseCategoryHeader("test.conf", 1, "[foo]"); - assertEquals("Incorrect category name", "foo", category.getName()); - assertEquals("Incorrect line number", 1, category.getLineNumber()); - assertEquals("Incorrect file name", "test.conf", category.getFileName()); + assertEquals("foo", category.getName(), "Incorrect category name"); + assertEquals(1, category.getLineNumber(), "Incorrect line number"); + assertEquals("test.conf", category.getFileName(), "Incorrect file name"); category = configFileReader.parseCategoryHeader("test.conf", 1, "[foo](!)"); - assertEquals("Incorrect category name", "foo", category.getName()); - assertTrue("Category not flagged as template", category.isTemplate()); + assertEquals("foo", category.getName(), "Incorrect category name"); + assertTrue(category.isTemplate(), "Category not flagged as template"); category = configFileReader.parseCategoryHeader("test.conf", 1, "[foo](+)"); - assertEquals("Incorrect category name", "foo", category.getName()); + assertEquals("foo", category.getName(), "Incorrect category name"); - try - { + try { configFileReader.parseCategoryHeader("test.conf", 1, "[foo](a)"); fail("Expected exception when requesting inheritance from a non-existing catagory"); - } - catch (ConfigParseException e) - { + } catch (ConfigParseException e) { assertEquals("Inheritance requested, but category 'a' does not exist, line 1 of test.conf", e.getMessage()); - assertEquals("Incorrect line number", 1, e.getLineNumber()); - assertEquals("Incorrect file name", "test.conf", e.getFileName()); + assertEquals(1, e.getLineNumber(), "Incorrect line number"); + assertEquals("test.conf", e.getFileName(), "Incorrect file name"); } - try - { + try { configFileReader.parseCategoryHeader("test.conf", 1, "[foo"); fail("Expected exception when closing ']' is missing"); - } - catch (ConfigParseException e) - { + } catch (ConfigParseException e) { assertEquals(e.getMessage(), "parse error: no closing ']', line 1 of test.conf"); } - try - { + try { configFileReader.parseCategoryHeader("test.conf", 1, "[foo](bar"); fail("Expected exception when closing ')' is missing"); - } - catch (ConfigParseException e) - { + } catch (ConfigParseException e) { assertEquals(e.getMessage(), "parse error: no closing ')', line 1 of test.conf"); } } - public void testParseDirective() throws ConfigParseException - { + @Test + void testParseDirective() throws ConfigParseException { ConfigDirective configDirective; configDirective = configFileReader.parseDirective("abc.conf", 20, "#include \"/etc/asterisk/inc.conf\""); - assertEquals("Incorrect type of configDirective", IncludeDirective.class, configDirective.getClass()); - assertEquals("Incorrect include file", "/etc/asterisk/inc.conf", ((IncludeDirective) configDirective).getIncludeFile()); - assertEquals("Incorrect line number", 20, configDirective.getLineNumber()); - assertEquals("Incorrect file name", "abc.conf", configDirective.getFileName()); + assertEquals(IncludeDirective.class, configDirective.getClass(), "Incorrect type of configDirective"); + assertEquals("/etc/asterisk/inc.conf", ((IncludeDirective) configDirective).getIncludeFile(), "Incorrect include file"); + assertEquals(20, configDirective.getLineNumber(), "Incorrect line number"); + assertEquals("abc.conf", configDirective.getFileName(), "Incorrect file name"); configDirective = configFileReader.parseDirective("abc.conf", 20, "#exec "); - assertEquals("Incorrect type of configDirective", ExecDirective.class, configDirective.getClass()); - assertEquals("Incorrect exec file", "/usr/local/test.sh", ((ExecDirective) configDirective).getExecFile()); - assertEquals("Incorrect line number", 20, configDirective.getLineNumber()); - assertEquals("Incorrect file name", "abc.conf", configDirective.getFileName()); + assertEquals(ExecDirective.class, configDirective.getClass(), "Incorrect type of configDirective"); + assertEquals("/usr/local/test.sh", ((ExecDirective) configDirective).getExecFile(), "Incorrect exec file"); + assertEquals(20, configDirective.getLineNumber(), "Incorrect line number"); + assertEquals("abc.conf", configDirective.getFileName(), "Incorrect file name"); - try - { + try { configFileReader.parseDirective("abc.conf", 20, "#foo"); fail("Expected exception when parsing a line with an unknown directive"); - } - catch (UnknownDirectiveException e) - { + } catch (UnknownDirectiveException e) { assertEquals("Unknown directive 'foo' at line 20 of abc.conf", e.getMessage()); } - try - { + try { configFileReader.parseDirective("/etc/asterisk/sip.conf", 805, "#include "); fail("Expected exception when parsing a line with a directive but no parameter"); - } - catch (MissingDirectiveParameterException e) - { - assertEquals("Directive '#include' needs an argument (filename) at line 805 of /etc/asterisk/sip.conf", e.getMessage()); + } catch (MissingDirectiveParameterException e) { + assertEquals("Directive '#include' needs an argument (filename) at line 805 of /etc/asterisk/sip.conf", + e.getMessage()); } } - public void testParseVariable() throws ConfigParseException - { + @Test + void testParseVariable() throws ConfigParseException { ConfigVariable variable; variable = configFileReader.parseVariable("extensions.conf", 20, "exten => s-NOANSWER,1,Hangup"); - assertEquals("Incorrect name", "exten", variable.getName()); - assertEquals("Incorrect value", "s-NOANSWER,1,Hangup", variable.getValue()); - assertEquals("Incorrect line number", 20, variable.getLineNumber()); - assertEquals("Incorrect file name", "extensions.conf", variable.getFileName()); + assertEquals("exten", variable.getName(), "Incorrect name"); + assertEquals("s-NOANSWER,1,Hangup", variable.getValue(), "Incorrect value"); + assertEquals(20, variable.getLineNumber(), "Incorrect line number"); + assertEquals("extensions.conf", variable.getFileName(), "Incorrect file name"); variable = configFileReader.parseVariable("extensions.conf", 20, "foo="); - assertEquals("Incorrect name", "foo", variable.getName()); - assertEquals("Incorrect value", "", variable.getValue()); + assertEquals("foo", variable.getName(), "Incorrect name"); + assertEquals("", variable.getValue(), "Incorrect value"); - try - { + try { configFileReader.parseVariable("extensions.conf", 20, "foo"); fail("Expected exception when parsing a line without a '='"); - } - catch (MissingEqualSignException e) - { + } catch (MissingEqualSignException e) { assertEquals("No '=' (equal sign) in line 20 of extensions.conf", e.getMessage()); } } - - public void XtestReadConfig() throws Exception - { - configFileReader.readFile("/etc/asterisk/sip2.conf"); - - for (Category category : configFileReader.getCategories()) - { - System.out.println(category.format()); - } - } } diff --git a/src/test/java/org/asteriskjava/fastagi/ClassNameMappingStrategyTest.java b/src/test/java/org/asteriskjava/fastagi/ClassNameMappingStrategyTest.java index 548c5cd37..4e887cfaf 100644 --- a/src/test/java/org/asteriskjava/fastagi/ClassNameMappingStrategyTest.java +++ b/src/test/java/org/asteriskjava/fastagi/ClassNameMappingStrategyTest.java @@ -16,29 +16,29 @@ */ package org.asteriskjava.fastagi; -import junit.framework.TestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class ClassNameMappingStrategyTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ClassNameMappingStrategyTest { private ClassNameMappingStrategy mappingStrategy; - @Override - protected void setUp() throws Exception - { - super.setUp(); + @BeforeEach + void setUp() { this.mappingStrategy = new ClassNameMappingStrategy(); } - public void testDetermineScript() - { + @Test + void testDetermineScript() { AgiScript scriptFirstPass; AgiScript scriptSecondPass; AgiRequest request; request = new SimpleAgiRequest() { @Override - public String getScript() - { + public String getScript() { return "org.asteriskjava.fastagi.HelloAgiScript"; } }; @@ -46,15 +46,13 @@ public String getScript() scriptFirstPass = mappingStrategy.determineScript(request); scriptSecondPass = mappingStrategy.determineScript(request); - assertEquals("incorrect script determined", - scriptFirstPass.getClass(), HelloAgiScript.class); + assertEquals(scriptFirstPass.getClass(), HelloAgiScript.class, "incorrect script determined"); - assertTrue("script instances are not cached", - scriptFirstPass == scriptSecondPass); + assertTrue(scriptFirstPass == scriptSecondPass, "script instances are not cached"); } - public void testDetermineScriptWithNonSharedInstance() - { + @Test + void testDetermineScriptWithNonSharedInstance() { AgiScript scriptFirstPass; AgiScript scriptSecondPass; AgiRequest request; @@ -62,8 +60,7 @@ public void testDetermineScriptWithNonSharedInstance() mappingStrategy.setShareInstances(false); request = new SimpleAgiRequest() { @Override - public String getScript() - { + public String getScript() { return "org.asteriskjava.fastagi.HelloAgiScript"; } }; @@ -71,10 +68,8 @@ public String getScript() scriptFirstPass = mappingStrategy.determineScript(request); scriptSecondPass = mappingStrategy.determineScript(request); - assertEquals("incorrect script determined", - scriptFirstPass.getClass(), HelloAgiScript.class); + assertEquals(scriptFirstPass.getClass(), HelloAgiScript.class, "incorrect script determined"); - assertTrue("returned a shared instance", - scriptFirstPass != scriptSecondPass); + assertTrue(scriptFirstPass != scriptSecondPass, "returned a shared instance"); } } diff --git a/src/test/java/org/asteriskjava/fastagi/CompositeMappingStrategyTest.java b/src/test/java/org/asteriskjava/fastagi/CompositeMappingStrategyTest.java index de0d28eca..eb8c9f3f3 100644 --- a/src/test/java/org/asteriskjava/fastagi/CompositeMappingStrategyTest.java +++ b/src/test/java/org/asteriskjava/fastagi/CompositeMappingStrategyTest.java @@ -1,33 +1,35 @@ package org.asteriskjava.fastagi; -import junit.framework.TestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class CompositeMappingStrategyTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class CompositeMappingStrategyTest { private CompositeMappingStrategy strategy; - @Override - public void setUp() - { + @BeforeEach + void setUp() { strategy = new CompositeMappingStrategy(new ResourceBundleMappingStrategy("test-mapping"), new ClassNameMappingStrategy()); } - public void testAJ37ResourceBundle() - { + @Test + void testAJ37ResourceBundle() { AgiRequest request = new SimpleAgiRequest(); AgiScript script = strategy.determineScript(request, null); - assertNotNull("no script determined", script); - assertEquals("incorrect script determined", script.getClass(), HelloAgiScript.class); + assertNotNull(script, "no script determined"); + assertEquals(script.getClass(), HelloAgiScript.class, "incorrect script determined"); } - public void testAJ37ClassName() - { + @Test + void testAJ37ClassName() { AgiRequest request = new SimpleAgiRequest("org.asteriskjava.fastagi.HelloAgiScript"); AgiScript script = strategy.determineScript(request, null); - assertNotNull("no script determined", script); - assertEquals("incorrect script determined", script.getClass(), HelloAgiScript.class); + assertNotNull(script, "no script determined"); + assertEquals(script.getClass(), HelloAgiScript.class, "incorrect script determined"); } } diff --git a/src/test/java/org/asteriskjava/fastagi/DefaultAgiServerTest.java b/src/test/java/org/asteriskjava/fastagi/DefaultAgiServerTest.java index 56a3f8b0c..2e08c0ffb 100644 --- a/src/test/java/org/asteriskjava/fastagi/DefaultAgiServerTest.java +++ b/src/test/java/org/asteriskjava/fastagi/DefaultAgiServerTest.java @@ -16,139 +16,119 @@ */ package org.asteriskjava.fastagi; -import java.io.IOException; - -import junit.framework.TestCase; -import static org.easymock.EasyMock.*; - -import org.asteriskjava.fastagi.DefaultAgiServer; import org.asteriskjava.util.ServerSocketFacade; import org.asteriskjava.util.SocketConnectionFacade; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class DefaultAgiServerTest extends TestCase -{ +class DefaultAgiServerTest { private DefaultAgiServer server; private MockedServerSocketFacade serverSocket; private SocketConnectionFacade socket; - @Override - protected void setUp() throws Exception - { - super.setUp(); - + @BeforeEach + void setUp() { serverSocket = new MockedServerSocketFacade(); server = new MockedDefaultAgiServer(); } - @Override - protected void tearDown() throws Exception - { - super.tearDown(); + @AfterEach + void tearDown() throws Exception { server.shutdown(); } - public void testDummy() - { - + @Test + void testDummy() { + } - - public void XtestStartup() throws Exception - { - socket = createMock(SocketConnectionFacade.class); - - expect(socket.readLine()).andReturn(null); - expect(socket.getLocalAddress()).andReturn(null); - expect(socket.getLocalPort()).andReturn(1); - expect(socket.getRemoteAddress()).andReturn(null); - expect(socket.getRemotePort()).andReturn(2); + + void XtestStartup() throws Exception { + socket = mock(SocketConnectionFacade.class); + + when(socket.readLine()) + .thenReturn(null) + .thenReturn(null); + when(socket.getLocalPort()).thenReturn(1); + when(socket.getRemoteAddress()).thenReturn(null); + when(socket.getRemotePort()).thenReturn(2); socket.write("VERBOSE \"No script configured for null\" 1\n"); socket.flush(); - expect(socket.readLine()).andReturn(null); + when(socket.readLine()).thenReturn(null); socket.close(); - replay(socket); - try - { + try { server.startup(); - } - catch (IOException e) - { + } catch (IOException e) { // swallow } Thread.sleep(500); - assertEquals("serverSocket.accept() not called 2 times", 2, - serverSocket.acceptCalls); - assertEquals("serverSocket.close() not called", 1, - serverSocket.closeCalls); - - verify(socket); + assertEquals(2, serverSocket.acceptCalls, "serverSocket.accept() not called 2 times"); + assertEquals(1, serverSocket.closeCalls, "serverSocket.close() not called"); } - class MockedDefaultAgiServer extends DefaultAgiServer - { + class MockedDefaultAgiServer extends DefaultAgiServer { @Override - protected ServerSocketFacade createServerSocket() - { + protected ServerSocketFacade createServerSocket() { return serverSocket; } } - class MockedServerSocketFacade implements ServerSocketFacade - { + class MockedServerSocketFacade implements ServerSocketFacade { public int acceptCalls = 0; public int closeCalls = 0; - public SocketConnectionFacade accept() throws IOException - { + public SocketConnectionFacade accept() throws IOException { acceptCalls++; - try - { + try { Thread.sleep(100); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - if (acceptCalls == 1) - { + if (acceptCalls == 1) { return socket; } - else - { - throw new IOException("Provoked IOException"); - } + throw new IOException("Provoked IOException"); } - public void close() throws IOException - { + public void close() throws IOException { closeCalls++; } + + public void setSocketReadTimeout(int socketReadTimeout) { + } } - public void testLoadConfigWithDefaultPort() - { + @Test + void testLoadConfigWithDefaultPort() { DefaultAgiServer defaultAgiServer; defaultAgiServer = new DefaultAgiServer(); - assertEquals("Invalid default port", 4573, defaultAgiServer.getPort()); + assertEquals(4573, defaultAgiServer.getPort(), "Invalid default port"); } - public void testLoadConfigWithPort() - { + @Test + void testLoadConfigWithPort() { DefaultAgiServer defaultAgiServer; defaultAgiServer = new DefaultAgiServer("test1-fastagi"); - assertEquals("Port property not recognized", 1234, defaultAgiServer.getPort()); + assertEquals(1234, defaultAgiServer.getPort(), "Port property not recognized"); } - public void testLoadConfigWithBindPort() - { + @Test + void testLoadConfigWithBindPort() { DefaultAgiServer defaultAgiServer; defaultAgiServer = new DefaultAgiServer("test2-fastagi"); - assertEquals("BindPort property not recognized", 2345, defaultAgiServer.getPort()); + assertEquals(2345, defaultAgiServer.getPort(), "BindPort property not recognized"); } } diff --git a/src/test/java/org/asteriskjava/fastagi/HelloAgiScript.java b/src/test/java/org/asteriskjava/fastagi/HelloAgiScript.java index b12c10cb6..e0f85762a 100644 --- a/src/test/java/org/asteriskjava/fastagi/HelloAgiScript.java +++ b/src/test/java/org/asteriskjava/fastagi/HelloAgiScript.java @@ -18,19 +18,16 @@ /** * Test script for use with the ResourceBundleMappingStrategyTest. - * + * * @author srt * @version $Id$ */ -public class HelloAgiScript implements AgiScript -{ - public HelloAgiScript() - { +public class HelloAgiScript implements AgiScript { + public HelloAgiScript() { } - public void service(AgiRequest request, AgiChannel channel) throws AgiException - { + public void service(AgiRequest request, AgiChannel channel) throws AgiException { channel.streamFile("tt-monkeysintro"); } } diff --git a/src/test/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategyTest.java b/src/test/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategyTest.java index ad57bae32..e8d24b332 100644 --- a/src/test/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategyTest.java +++ b/src/test/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategyTest.java @@ -16,27 +16,22 @@ */ package org.asteriskjava.fastagi; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.*; -import org.asteriskjava.fastagi.AgiRequest; -import org.asteriskjava.fastagi.AgiScript; -import org.asteriskjava.fastagi.ResourceBundleMappingStrategy; - -public class ResourceBundleMappingStrategyTest extends TestCase -{ +class ResourceBundleMappingStrategyTest { private ResourceBundleMappingStrategy mappingStrategy; - @Override - protected void setUp() throws Exception - { - super.setUp(); + @BeforeEach + void setUp() { this.mappingStrategy = new ResourceBundleMappingStrategy(); this.mappingStrategy.setResourceBundleName("test-mapping"); } - public void testDetermineScript() - { + @Test + void testDetermineScript() { AgiScript scriptFirstPass; AgiScript scriptSecondPass; AgiRequest request; @@ -46,27 +41,24 @@ public void testDetermineScript() scriptFirstPass = mappingStrategy.determineScript(request); scriptSecondPass = mappingStrategy.determineScript(request); - assertNotNull("no script determined", scriptFirstPass); - assertEquals("incorrect script determined", - scriptFirstPass.getClass(), HelloAgiScript.class); + assertNotNull(scriptFirstPass, "no script determined"); + assertEquals(scriptFirstPass.getClass(), HelloAgiScript.class, "incorrect script determined"); - assertTrue("script instances are not cached", - scriptFirstPass == scriptSecondPass); + assertTrue(scriptFirstPass == scriptSecondPass, "script instances are not cached"); } - public void testDetermineScriptWithResourceBundleUnavailable() - { + @Test + void testDetermineScriptWithResourceBundleUnavailable() { AgiRequest request; request = new SimpleAgiRequest(); - mappingStrategy - .setResourceBundleName("net.sf.asterisk.fastagi.unavailable"); + mappingStrategy.setResourceBundleName("net.sf.asterisk.fastagi.unavailable"); assertNull(mappingStrategy.determineScript(request)); } - public void testDetermineScriptWithNonSharedInstance() - { + @Test + void testDetermineScriptWithNonSharedInstance() { AgiScript scriptFirstPass; AgiScript scriptSecondPass; AgiRequest request; @@ -77,10 +69,8 @@ public void testDetermineScriptWithNonSharedInstance() scriptFirstPass = mappingStrategy.determineScript(request); scriptSecondPass = mappingStrategy.determineScript(request); - assertEquals("incorrect script determined", - scriptFirstPass.getClass(), HelloAgiScript.class); + assertEquals(scriptFirstPass.getClass(), HelloAgiScript.class, "incorrect script determined"); - assertTrue("returned a shared instance", - scriptFirstPass != scriptSecondPass); + assertTrue(scriptFirstPass != scriptSecondPass, "returned a shared instance"); } } diff --git a/src/test/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategyTest.java b/src/test/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategyTest.java index 0571d8390..31f6e03d2 100644 --- a/src/test/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategyTest.java +++ b/src/test/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategyTest.java @@ -1,24 +1,25 @@ package org.asteriskjava.fastagi; -import junit.framework.TestCase; -import static org.asteriskjava.fastagi.ScriptEngineMappingStrategy.getExtension; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; -public class ScriptEngineMappingStrategyTest extends TestCase -{ +import static org.asteriskjava.fastagi.ScriptEngineMappingStrategy.getExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ScriptEngineMappingStrategyTest { private ScriptEngineMappingStrategy scriptEngineMappingStrategy; - @Override - protected void setUp() throws Exception - { - super.setUp(); + @BeforeEach + void setUp() { this.scriptEngineMappingStrategy = new ScriptEngineMappingStrategy(); } - public void testSearchFile() throws IOException - { + @Test + void testSearchFile() throws IOException { assertNull(scriptEngineMappingStrategy.searchFile(null, new String[]{"src", "test", "."})); assertNull(scriptEngineMappingStrategy.searchFile("pom.xml", null)); assertNull(scriptEngineMappingStrategy.searchFile("pom.xml", new String[]{})); @@ -27,14 +28,15 @@ public void testSearchFile() throws IOException scriptEngineMappingStrategy.searchFile("pom.xml", new String[]{"bla", "src", "."}).getPath()); } - public void testSearchFileOutsidePath() throws IOException - { - // file should not be found for security reasons if it is not below the path + @Test + void testSearchFileOutsidePath() { + // file should not be found for security reasons if it is not below the + // path assertNull(scriptEngineMappingStrategy.searchFile("../pom.xml", new String[]{"src"})); } - public void testGetExtension() - { + @Test + void testGetExtension() { assertEquals("txt", getExtension("hello.txt")); assertEquals("txt", getExtension("/some/path/hello.txt")); assertEquals("txt", getExtension("C:\\some\\path\\hello.txt")); diff --git a/src/test/java/org/asteriskjava/fastagi/SimpleAgiRequest.java b/src/test/java/org/asteriskjava/fastagi/SimpleAgiRequest.java index 2667479a6..411678e29 100644 --- a/src/test/java/org/asteriskjava/fastagi/SimpleAgiRequest.java +++ b/src/test/java/org/asteriskjava/fastagi/SimpleAgiRequest.java @@ -16,198 +16,171 @@ */ package org.asteriskjava.fastagi; +import org.asteriskjava.AsteriskVersion; + import java.net.InetAddress; import java.util.Map; -public class SimpleAgiRequest implements AgiRequest -{ +public class SimpleAgiRequest implements AgiRequest { InetAddress localAddress; int localPort; InetAddress remoteAddress; int remotePort; private String script; + private AsteriskVersion asteriskVersion = AsteriskVersion.ASTERISK_13; - public SimpleAgiRequest() - { + public SimpleAgiRequest() { this.script = "hello.agi"; } - - public SimpleAgiRequest(String script) - { + + public SimpleAgiRequest(String script) { this.script = script; } - - public Map getRequest() - { + + public Map getRequest() { throw new UnsupportedOperationException(); } - public String getScript() - { + public String getScript() { return script; } - public String getRequestURL() - { + public String getRequestURL() { throw new UnsupportedOperationException(); } - public String getChannel() - { + public String getChannel() { throw new UnsupportedOperationException(); } - public String getUniqueId() - { + public String getUniqueId() { throw new UnsupportedOperationException(); } - public String getType() - { + public String getType() { throw new UnsupportedOperationException(); } - public String getLanguage() - { + public String getLanguage() { throw new UnsupportedOperationException(); } /** - * Returns the Caller*ID number, for example "1234".

        - * Note: even with Asterisk 1.0 is contains only the numerical part - * of the Caller ID. + * Returns the Caller*ID number, for example "1234". + *

        + * Note: even with Asterisk 1.0 is contains only the numerical part of the + * Caller ID. * - * @return the Caller*ID number, for example "1234", if no Caller*ID is set or it - * is "unknown" null is returned. + * @return the Caller*ID number, for example "1234", if no Caller*ID is set + * or it is "unknown" null is returned. * @deprecated as of 0.3, use {@link #getCallerIdNumber()} instead. */ - public String getCallerId() - { + public String getCallerId() { throw new UnsupportedOperationException(); } - public String getCallerIdNumber() - { + public String getCallerIdNumber() { throw new UnsupportedOperationException(); } - public String getCallerIdName() - { + public String getCallerIdName() { throw new UnsupportedOperationException(); } - public String getDnid() - { + public String getDnid() { throw new UnsupportedOperationException(); } - public String getRdnis() - { + public String getRdnis() { throw new UnsupportedOperationException(); } - public String getContext() - { + public String getContext() { throw new UnsupportedOperationException(); } - public String getExtension() - { + public String getExtension() { throw new UnsupportedOperationException(); } - public Integer getPriority() - { + public Integer getPriority() { throw new UnsupportedOperationException(); } - public Boolean getEnhanced() - { + public Boolean getEnhanced() { throw new UnsupportedOperationException(); } - public String getAccountCode() - { + public String getAccountCode() { throw new UnsupportedOperationException(); } - public Integer getCallingAni2() - { + public Integer getCallingAni2() { throw new UnsupportedOperationException(); } - public Integer getCallingPres() - { + public Integer getCallingPres() { throw new UnsupportedOperationException(); } - public Integer getCallingTns() - { + public Integer getCallingTns() { throw new UnsupportedOperationException(); } - public Integer getCallingTon() - { + public Integer getCallingTon() { throw new UnsupportedOperationException(); } - public String getParameter(String name) - { + public String getParameter(String name) { throw new UnsupportedOperationException(); } - public String[] getParameterValues(String name) - { + public String[] getParameterValues(String name) { throw new UnsupportedOperationException(); } - public Map getParameterMap() - { + public Map getParameterMap() { throw new UnsupportedOperationException(); } - public String[] getArguments() - { + public String[] getArguments() { throw new UnsupportedOperationException(); } - public InetAddress getLocalAddress() - { + public InetAddress getLocalAddress() { return localAddress; } - public void setLocalAddress(InetAddress localAddress) - { + public void setLocalAddress(InetAddress localAddress) { this.localAddress = localAddress; } - public int getLocalPort() - { + public int getLocalPort() { return localPort; } - public void setLocalPort(int localPort) - { + public void setLocalPort(int localPort) { this.localPort = localPort; } - public InetAddress getRemoteAddress() - { + public InetAddress getRemoteAddress() { return remoteAddress; } - public void setRemoteAddress(InetAddress remoteAddress) - { + public void setRemoteAddress(InetAddress remoteAddress) { this.remoteAddress = remoteAddress; } - public int getRemotePort() - { + public int getRemotePort() { return remotePort; } - public void setRemotePort(int remotePort) - { + public void setRemotePort(int remotePort) { this.remotePort = remotePort; } -} \ No newline at end of file + + @Override + public AsteriskVersion getAsteriskVersion() { + return asteriskVersion; + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/AbstractAgiCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/AbstractAgiCommandTest.java index 9b9c9efbd..e0e0c0790 100644 --- a/src/test/java/org/asteriskjava/fastagi/command/AbstractAgiCommandTest.java +++ b/src/test/java/org/asteriskjava/fastagi/command/AbstractAgiCommandTest.java @@ -1,82 +1,186 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; -import junit.framework.TestCase; +import org.asteriskjava.AsteriskVersion; +import org.junit.jupiter.api.Test; + +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.AsteriskVersion.ASTERISK_18; +import static org.asteriskjava.AsteriskVersion.ASTERISK_1_4; + +class AbstractAgiCommandTest { + @Test + void shouldBuildCommand() { + //given + MyCommand myCommand = new MyCommand("just a string"); + + //when + String actual = myCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("MY \"just a string\""); + } + + @Test + void shouldHandleNull() { + //given + MyCommand myCommand = new MyCommand(null); + + //when + String actual = myCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("MY \"\""); + } -public class AbstractAgiCommandTest extends TestCase -{ - private MyCommand myCommand; + @Test + void shouldHandleEmptyString() { + //given + MyCommand myCommand = new MyCommand(""); - public void testEscapeAndQuote() - { - myCommand = new MyCommand("just a string"); + //when + String actual = myCommand.buildCommand(); - assertEquals("MY \"just a string\"", myCommand.buildCommand()); + //then + assertThat(actual).isEqualTo("MY \"\""); } - public void testEscapeAndQuoteWithNullString() - { - myCommand = new MyCommand(null); + @Test + void shouldEscapeAndQuoteWithStringContainingQuotes() { + //given + MyCommand myCommand = new MyCommand("\"John Doe\" is calling"); + + //given + String actual = myCommand.buildCommand(); - assertEquals("MY \"\"", myCommand.buildCommand()); + //when + assertThat(actual).isEqualTo("MY \"\\\"John Doe\\\" is calling\""); } - public void testEscapeAndQuoteWithEmptyString() - { - myCommand = new MyCommand(""); + @Test + void shouldEscapeAndQuoteWithStringContainingNewline() { + //given + MyCommand myCommand = new MyCommand("Caller is:\nJohn Doe"); + + //when + String actual = myCommand.buildCommand(); - assertEquals("MY \"\"", myCommand.buildCommand()); + //then + assertThat(actual).isEqualTo("MY \"Caller is:John Doe\""); } - public void testEscapeAndQuoteWithStringContainingQuotes() - { - myCommand = new MyCommand("\"John Doe\" is calling"); + @Test + void shouldEscapedQuotesAJ192() { + //given + MyCommand myCommand = new MyCommand("first \\\" second \\\" third"); - assertEquals("MY \"\\\"John Doe\\\" is calling\"", myCommand.buildCommand()); + //when + String actual = myCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("MY \"first \\\\\\\" second \\\\\\\" third\""); } - public void testEscapeAndQuoteWithStringContainingNewline() - { - myCommand = new MyCommand("Caller is:\nJohn Doe"); + @Test + void shouldFormatToString() { + //given + MyCommand myCommand = new MyCommand("just a string"); + + //when + String actual = myCommand.toString(); + + //then + assertThat(actual).contains("command='MY \"just a string\"'"); + } + + @Test + void shouldHandleCommandWithMultipleStrings() { + //given + MyMultipleCommand myMultipleCommand = new MyMultipleCommand(new String[]{"first string", "another string"}); + + //when + String actual = myMultipleCommand.buildCommand(); - assertEquals("MY \"Caller is:John Doe\"", myCommand.buildCommand()); + //then + assertThat(actual).isEqualTo("MY \"first string,another string\""); } - public void testEscapedQuotesAJ192() { - myCommand = new MyCommand("first \\\" second \\\" third"); + @Test + void shouldHandleNullForArrayStrings() { + //given + MyMultipleCommand myMultipleCommand = new MyMultipleCommand(null); - assertEquals("MY \"first \\\\\\\" second \\\\\\\" third\"", myCommand.buildCommand()); + //when + String actual = myMultipleCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("MY \"\""); + } + + @Test + void shouldReturnDefaultAsteriskVersion() { + //given + MyCommand myCommand = new MyCommand("string"); + + //when + AsteriskVersion asteriskVersion = myCommand.getAsteriskVersion(); + + //then + assertThat(asteriskVersion).isEqualTo(ASTERISK_1_4); + } + + @Test + void shouldSetAsteriskVersion() { + //given + MyCommand myCommand = new MyCommand("string"); + + //when + myCommand.setAsteriskVersion(ASTERISK_18); + + //then + assertThat(myCommand.getAsteriskVersion()).isEqualTo(ASTERISK_18); + } + + private static class MyCommand extends AbstractAgiCommand { + private static final long serialVersionUID = 3976731484641833012L; + private final String command; + + public MyCommand(String command) { + this.command = command; + } + + @Override + public String buildCommand() { + return format("MY %s", escapeAndQuote(command)); + } } - public class MyCommand extends AbstractAgiCommand - { + private static class MyMultipleCommand extends AbstractAgiCommand { private static final long serialVersionUID = 3976731484641833012L; - private String s; + private final String[] commands; - public MyCommand(String s) - { - this.s = s; + public MyMultipleCommand(String[] commands) { + this.commands = commands; } @Override - public String buildCommand() - { - return "MY " + escapeAndQuote(s); + public String buildCommand() { + return format("MY %s", escapeAndQuote(commands)); } } } diff --git a/src/test/java/org/asteriskjava/fastagi/command/AnswerCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/AnswerCommandTest.java new file mode 100644 index 000000000..fa5afa247 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/AnswerCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class AnswerCommandTest { + @Test + void shouldBuildAnswerCommand() { + //given + AnswerCommand answerCommand = new AnswerCommand(); + + //when + String command = answerCommand.buildCommand(); + + //then + assertThat(command).isEqualTo("ANSWER"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/AsyncAgiBreakCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/AsyncAgiBreakCommandTest.java new file mode 100644 index 000000000..977807619 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/AsyncAgiBreakCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class AsyncAgiBreakCommandTest { + @Test + void shouldBuildAsyncAgiBreakCommand() { + //given + AsyncAgiBreakCommand asyncAgiBreakCommand = new AsyncAgiBreakCommand(); + + //when + String command = asyncAgiBreakCommand.buildCommand(); + + //then + assertThat(command).isEqualTo("ASYNCAGI BREAK"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/BridgeCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/BridgeCommandTest.java new file mode 100644 index 000000000..8ec408885 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/BridgeCommandTest.java @@ -0,0 +1,50 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.AsteriskVersion.ASTERISK_12; +import static org.asteriskjava.AsteriskVersion.ASTERISK_13; + +class BridgeCommandTest { + @Test + void shouldBuildBridgeCommand() { + //given + BridgeCommand bridgeCommand = new BridgeCommand("SIP/1234", "p"); + bridgeCommand.setAsteriskVersion(ASTERISK_13); + + //when + String actual = bridgeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"bridge\" \"SIP/1234\",\"p\""); + } + + @Test + void shouldBuildBridgeCommandForAsteriskLessThan13() { + //given + BridgeCommand bridgeCommand = new BridgeCommand("SIP/1234", "p"); + bridgeCommand.setAsteriskVersion(ASTERISK_12); + + //when + String actual = bridgeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"bridge\" \"SIP/1234\"|\"p\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/ChannelStatusCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/ChannelStatusCommandTest.java new file mode 100644 index 000000000..556e4d485 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/ChannelStatusCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class ChannelStatusCommandTest { + @Test + void shouldBuildChannelStatusCommandForCurrentChannel() { + //given + ChannelStatusCommand channelStatusCommand = new ChannelStatusCommand(); + + //when + String actual = channelStatusCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("CHANNEL STATUS"); + } + + @Test + void shouldBuildChannelStatusCommand() { + //given + ChannelStatusCommand channelStatusCommand = new ChannelStatusCommand("SIP/1234"); + + //when + String actual = channelStatusCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("CHANNEL STATUS \"SIP/1234\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/ConfbridgeCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/ConfbridgeCommandTest.java new file mode 100644 index 000000000..4e87f7a0e --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/ConfbridgeCommandTest.java @@ -0,0 +1,48 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.AsteriskVersion.ASTERISK_10; + +class ConfbridgeCommandTest { + @Test + void shouldBuildConfbridgeCommand() { + //given + ConfbridgeCommand confbridgeCommand = new ConfbridgeCommand("room", "fancybridge"); + + //when + String actual = confbridgeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"confbridge\" \"room\"|\"fancybridge\""); + } + + @Test + void shouldBuildConfbridgeCommandForAsteriskGreaterThan10() { + //given + ConfbridgeCommand confbridgeCommand = new ConfbridgeCommand("room", "fancybridge"); + confbridgeCommand.setAsteriskVersion(ASTERISK_10); + + //when + String actual = confbridgeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"confbridge\" \"room\",\"fancybridge\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/ControlStreamFileCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/ControlStreamFileCommandTest.java new file mode 100644 index 000000000..e01480c74 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/ControlStreamFileCommandTest.java @@ -0,0 +1,83 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class ControlStreamFileCommandTest { + @Test + void shouldBuildControlStreamFileCommand() { + //given + ControlStreamFileCommand controlStreamFileCommand = new ControlStreamFileCommand("some-file"); + + //when + String actual = controlStreamFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("CONTROL STREAM FILE \"some-file\" \"\""); + } + + @Test + void shouldBuildControlStreamFileCommandWithEscapeDigits() { + //given + ControlStreamFileCommand controlStreamFileCommand = new ControlStreamFileCommand("some-file", "15"); + + //when + String actual = controlStreamFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("CONTROL STREAM FILE \"some-file\" \"15\""); + } + + @Test + void shouldBuildControlStreamFileCommandWithOffset() { + //given + ControlStreamFileCommand controlStreamFileCommand = new ControlStreamFileCommand("some-file", "15", 10); + + //when + String actual = controlStreamFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("CONTROL STREAM FILE \"some-file\" \"15\" 10"); + } + + @Test + void shouldBuildControlStreamFileCommandWithControlDigits() { + //given + ControlStreamFileCommand controlStreamFileCommand = new ControlStreamFileCommand("some-file", "15", 10, "[", "]", "-"); + + //when + String actual = controlStreamFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("CONTROL STREAM FILE \"some-file\" \"15\" 10 [ ] -"); + } + + @Test + void shouldBuildControlStreamFileCommandWithOffsetSetToZeroWhenOnlyControlDigitsAreSet() { + //given + ControlStreamFileCommand controlStreamFileCommand = new ControlStreamFileCommand("some-file"); + controlStreamFileCommand.setControlDigits("[", "]"); + + //when + String actual = controlStreamFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("CONTROL STREAM FILE \"some-file\" \"\" 0 [ ]"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/DatabaseDelCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/DatabaseDelCommandTest.java new file mode 100644 index 000000000..7f97a4de1 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/DatabaseDelCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class DatabaseDelCommandTest { + @Test + void shouldBuildDatabaseDelCommandForFamilyOnly() { + //given + DatabaseDelCommand databaseDelCommand = new DatabaseDelCommand("family"); + + //when + String actual = databaseDelCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("DATABASE DEL \"family\""); + } + + @Test + void shouldBuildDatabaseDelCommandForFamilyAndKey() { + //given + DatabaseDelCommand databaseDelCommand = new DatabaseDelCommand("family", "key"); + + //when + String actual = databaseDelCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("DATABASE DEL \"family\" \"key\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/DatabaseDelTreeCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/DatabaseDelTreeCommandTest.java new file mode 100644 index 000000000..033597880 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/DatabaseDelTreeCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class DatabaseDelTreeCommandTest { + @Test + void shouldBuildDatabaseDelTreeCommandForFamilyOnly() { + //given + DatabaseDelTreeCommand databaseDelTreeCommand = new DatabaseDelTreeCommand("family"); + + //when + String actual = databaseDelTreeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("DATABASE DELTREE \"family\""); + } + + @Test + void shouldBuildDatabaseDelTreeCommandForFamilyAndKeyTree() { + //given + DatabaseDelTreeCommand databaseDelTreeCommand = new DatabaseDelTreeCommand("family", "keyTree"); + + //when + String actual = databaseDelTreeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("DATABASE DELTREE \"family\" \"keyTree\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/DatabaseGetCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/DatabaseGetCommandTest.java new file mode 100644 index 000000000..4a65e9e59 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/DatabaseGetCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class DatabaseGetCommandTest { + @Test + void shouldBuildDatabaseGetCommand() { + //given + DatabaseGetCommand databaseGetCommand = new DatabaseGetCommand("family", "key"); + + //when + String actual = databaseGetCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("DATABASE GET \"family\" \"key\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/DatabasePutCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/DatabasePutCommandTest.java new file mode 100644 index 000000000..b62c37250 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/DatabasePutCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class DatabasePutCommandTest { + @Test + void shouldBuildDatabasePutCommand() { + //given + DatabasePutCommand databasePutCommand = new DatabasePutCommand("family", "key", "value"); + + //when + String actual = databasePutCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("DATABASE PUT \"family\" \"key\" \"value\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/DialCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/DialCommandTest.java new file mode 100644 index 000000000..a68ab3266 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/DialCommandTest.java @@ -0,0 +1,48 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.AsteriskVersion.ASTERISK_10; + +class DialCommandTest { + @Test + void shouldBuildDialCommand() { + //given + DialCommand dialCommand = new DialCommand("PJSIP/alice", 30, "c"); + + //when + String actual = dialCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"dial\" \"PJSIP/alice\"|\"30\"|\"c\""); + } + + @Test + void shouldBuildDialCommandForAsteriskGreaterThan10() { + //given + DialCommand dialCommand = new DialCommand("PJSIP/alice", 30, "c"); + dialCommand.setAsteriskVersion(ASTERISK_10); + + //when + String actual = dialCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"dial\" \"PJSIP/alice\",\"30\",\"c\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/ExecCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/ExecCommandTest.java index 780c815e2..09cf4d6c9 100644 --- a/src/test/java/org/asteriskjava/fastagi/command/ExecCommandTest.java +++ b/src/test/java/org/asteriskjava/fastagi/command/ExecCommandTest.java @@ -1,54 +1,82 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class ExecCommandTest { + @Test + void shouldExecApplicationWithoutOptions() { + //given + ExecCommand execCommand = new ExecCommand("DIAL"); -public class ExecCommandTest extends TestCase -{ - private ExecCommand execCommand; + //when + String actual = execCommand.buildCommand(); - public void testDefault() - { - execCommand = new ExecCommand("DIAL"); - assertEquals("EXEC \"DIAL\" \"\"", execCommand.buildCommand()); + //then + assertThat(actual).isEqualTo("EXEC \"DIAL\" \"\""); } - public void testWithSingleOption() - { - execCommand = new ExecCommand("DIAL", "SIP/1234"); - assertEquals("EXEC \"DIAL\" \"SIP/1234\"", execCommand.buildCommand()); + @Test + void shouldExecApplicationWithSingleOption() { + //given + ExecCommand execCommand = new ExecCommand("DIAL", "SIP/1234"); + + //when + String actual = execCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"DIAL\" \"SIP/1234\""); } - public void testWithMultipleOptionsSingleParameterPipeSeparated() - { - execCommand = new ExecCommand("DIAL", "SIP/1234|30"); - assertEquals("EXEC \"DIAL\" \"SIP/1234|30\"", execCommand.buildCommand()); + @Test + void shouldExecWithMultipleOptionsSingleParameterPipeSeparated() { + //given + ExecCommand execCommand = new ExecCommand("DIAL", "SIP/1234|30"); + + //when + String actual = execCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"DIAL\" \"SIP/1234|30\""); } - public void testWithMultipleOptionsSingleParameterCommaSeparated() - { - execCommand = new ExecCommand("DIAL", "SIP/1234,30"); - assertEquals("EXEC \"DIAL\" \"SIP/1234,30\"", execCommand.buildCommand()); + @Test + void shouldExecWithMultipleOptionsSingleParameterCommaSeparated() { + //given + ExecCommand execCommand = new ExecCommand("DIAL", "SIP/1234,30"); + + //when + String actual = execCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"DIAL\" \"SIP/1234,30\""); } - public void testWithMultipleOptionsMultipleParameters() - { - execCommand = new ExecCommand("DIAL", "SIP/1234", "30"); - assertEquals("EXEC \"DIAL\" \"SIP/1234,30\"", execCommand.buildCommand()); + @Test + void shouldExecWithMultipleOptionsMultipleParameters() { + //given + ExecCommand execCommand = new ExecCommand("DIAL", "SIP/1234", "30"); + + //when + String actual = execCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"DIAL\" \"SIP/1234,30\""); } } diff --git a/src/test/java/org/asteriskjava/fastagi/command/GetDataCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/GetDataCommandTest.java index 2ead26068..1c78d5f5d 100644 --- a/src/test/java/org/asteriskjava/fastagi/command/GetDataCommandTest.java +++ b/src/test/java/org/asteriskjava/fastagi/command/GetDataCommandTest.java @@ -1,60 +1,94 @@ /* - * Copyright 2004-2006 Stefan Reuter + * Copyright 2004-2022 Asterisk-Java contributors * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package org.asteriskjava.fastagi.command; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; -import org.asteriskjava.fastagi.command.GetDataCommand; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class GetDataCommandTest extends TestCase -{ +class GetDataCommandTest { private GetDataCommand getDataCommand; - public void testDefault() - { - getDataCommand = new GetDataCommand("VAR1"); - assertEquals("GET DATA \"VAR1\"", getDataCommand.buildCommand()); + @Test + void shouldBuildGetDataCommand() { + //given + GetDataCommand getDataCommand = new GetDataCommand("VAR1"); + + //when + String actual = getDataCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GET DATA \"VAR1\""); } - public void testSetTimeout() - { - getDataCommand = new GetDataCommand("VAR1"); + @Test + void shouldSetTimeoutWhenBuildGetDataCommand() { + //given + GetDataCommand getDataCommand = new GetDataCommand("VAR1"); getDataCommand.setTimeout(10000); - assertEquals(10000, getDataCommand.getTimeout()); - assertEquals(1024, getDataCommand.getMaxDigits()); - assertEquals("GET DATA \"VAR1\" 10000", getDataCommand.buildCommand()); + + //when + String actual = getDataCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GET DATA \"VAR1\" 10000"); + assertThat(getDataCommand.getTimeout()).isEqualTo(10000); + assertThat(getDataCommand.getMaxDigits()).isEqualTo(1024); } - public void testSetMaxDigits() - { - getDataCommand = new GetDataCommand("VAR1"); + @Test + void shouldSetMaxDigitsWhenBuildGetDataCommand() { + //given + GetDataCommand getDataCommand = new GetDataCommand("VAR1"); getDataCommand.setMaxDigits(10); - assertEquals(0, getDataCommand.getTimeout()); - assertEquals(10, getDataCommand.getMaxDigits()); - assertEquals("GET DATA \"VAR1\" 0 10", getDataCommand.buildCommand()); + + //when + String actual = getDataCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GET DATA \"VAR1\" 0 10"); + assertThat(getDataCommand.getTimeout()).isEqualTo(0); + assertThat(getDataCommand.getMaxDigits()).isEqualTo(10); } - public void testSetTimeoutAndMaxDigits() - { - getDataCommand = new GetDataCommand("VAR1"); + @Test + void shouldSetTimeoutAndSetMaxDigitsWhenBuildGetDataCommand() { + //given + GetDataCommand getDataCommand = new GetDataCommand("VAR1"); getDataCommand.setTimeout(10000); getDataCommand.setMaxDigits(20); - assertEquals(10000, getDataCommand.getTimeout()); - assertEquals(20, getDataCommand.getMaxDigits()); - assertEquals("GET DATA \"VAR1\" 10000 20", getDataCommand.buildCommand()); + + //when + String actual = getDataCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GET DATA \"VAR1\" 10000 20"); + assertThat(getDataCommand.getTimeout()).isEqualTo(10000); + assertThat(getDataCommand.getMaxDigits()).isEqualTo(20); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1025}) + void shouldThrowExceptionWhenMaxDigitsIsOutOfRange(int maxDigits) { + //when/then + assertThatThrownBy(() -> new GetDataCommand("VAR1", 10, maxDigits)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxDigits must be in [1..1024]"); } } diff --git a/src/test/java/org/asteriskjava/fastagi/command/GetFullVariableCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/GetFullVariableCommandTest.java new file mode 100644 index 000000000..85ad38d1e --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/GetFullVariableCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class GetFullVariableCommandTest { + @Test + void shouldBuildGetFullVariableCommand() { + //given + GetFullVariableCommand getFullVariableCommand = new GetFullVariableCommand("VAR"); + + //when + String actual = getFullVariableCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GET FULL VARIABLE \"VAR\""); + } + + @Test + void shouldBuildGetFullVariableCommandWithChannel() { + //given + GetFullVariableCommand getFullVariableCommand = new GetFullVariableCommand("VAR", "SIP/1234"); + + //when + String actual = getFullVariableCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GET FULL VARIABLE \"VAR\" \"SIP/1234\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/GetOptionCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/GetOptionCommandTest.java new file mode 100644 index 000000000..380d887f7 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/GetOptionCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class GetOptionCommandTest { + @Test + void shouldBuildGetOptionCommand() { + //given + GetOptionCommand getOptionCommand = new GetOptionCommand("file-name", "15"); + + //when + String actual = getOptionCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GET OPTION \"file-name\" \"15\""); + } + + @Test + void shouldBuildGetOptionCommandWithTimeout() { + //given + GetOptionCommand getOptionCommand = new GetOptionCommand("file-name", "15", 30); + + //when + String actual = getOptionCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GET OPTION \"file-name\" \"15\" 30"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/GosubCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/GosubCommandTest.java new file mode 100644 index 000000000..a282ed5e5 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/GosubCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class GosubCommandTest { + @Test + void shouldBuildGosubCommand() { + //given + GosubCommand gosubCommand = new GosubCommand("phones", "102", "1"); + + //when + String actual = gosubCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GOSUB \"phones\" \"102\" \"1\""); + } + + @Test + void shouldBuildGosubCommandWithArguments() { + //given + GosubCommand gosubCommand = new GosubCommand("phones", "102", "1", "agr1", "agr2"); + + //when + String actual = gosubCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GOSUB \"phones\" \"102\" \"1\" \"agr1,agr2\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/HangupCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/HangupCommandTest.java new file mode 100644 index 000000000..bd05d2e52 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/HangupCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class HangupCommandTest { + @Test + void shouldBuildHangupCommandForCurrentChannel() { + //given + HangupCommand hangupCommand = new HangupCommand(); + + //when + String actual = hangupCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("HANGUP"); + } + + @Test + void shouldBuildHangupCommand() { + //given + HangupCommand hangupCommand = new HangupCommand("SIP/1234"); + + //when + String actual = hangupCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("HANGUP \"SIP/1234\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/MeetmeCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/MeetmeCommandTest.java new file mode 100644 index 000000000..4bad219b2 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/MeetmeCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class MeetmeCommandTest { + @Test + void shouldBuildMeetmeCommand() { + //given + MeetmeCommand meetmeCommand = new MeetmeCommand("room", "Ac"); + + //when + String actual = meetmeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"meetme\" \"room\"|\"Ac\""); + } + + @Test + void shouldBuildMeetmeCommandWithoutOptions() { + //given + MeetmeCommand meetmeCommand = new MeetmeCommand("room", null); + + //when + String actual = meetmeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"meetme\" \"room\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/NoopCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/NoopCommandTest.java new file mode 100644 index 000000000..f6b3d39c8 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/NoopCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class NoopCommandTest { + @Test + void shouldBuildNoopCommand() { + //given + NoopCommand noopCommand = new NoopCommand(); + + //when + String actual = noopCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("NOOP"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/QueueCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/QueueCommandTest.java new file mode 100644 index 000000000..96413a4bf --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/QueueCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class QueueCommandTest { + @Test + void shouldBuildQueueCommand() { + //given + QueueCommand queueCommand = new QueueCommand("queue-name"); + + //when + String actual = queueCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"queue\" \"queue-name\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/ReceiveCharCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/ReceiveCharCommandTest.java new file mode 100644 index 000000000..682c3a8ca --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/ReceiveCharCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class ReceiveCharCommandTest { + @Test + void shouldBuildReceiveCharCommand() { + //given + ReceiveCharCommand receiveCharCommand = new ReceiveCharCommand(); + + //when + String actual = receiveCharCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("RECEIVE CHAR 0"); + } + + @Test + void shouldBuildReceiveCharCommandWithTimeout() { + //given + ReceiveCharCommand receiveCharCommand = new ReceiveCharCommand(20); + + //when + String actual = receiveCharCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("RECEIVE CHAR 20"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/ReceiveTextCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/ReceiveTextCommandTest.java new file mode 100644 index 000000000..ea7c21b89 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/ReceiveTextCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class ReceiveTextCommandTest { + @Test + void shouldBuildReceiveTextCommand() { + //given + ReceiveTextCommand receiveTextCommand = new ReceiveTextCommand(); + + //when + String actual = receiveTextCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("RECEIVE TEXT 0"); + } + + @Test + void shouldBuildReceiveCharCommandWithTimeout() { + //given + ReceiveTextCommand receiveTextCommand = new ReceiveTextCommand(20); + + //when + String actual = receiveTextCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("RECEIVE TEXT 20"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/RecordFileCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/RecordFileCommandTest.java new file mode 100644 index 000000000..051924f49 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/RecordFileCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class RecordFileCommandTest { + @Test + void shouldBuildRecordFileCommand() { + //given + RecordFileCommand recordFileCommand = new RecordFileCommand("some-file", "wav", "4", 10); + + //when + String actual = recordFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("RECORD FILE \"some-file\" \"wav\" \"4\" 10 0 s=0"); + } + + @Test + void shouldBuildRecordFileCommandWithOffsetBeepAndMaxSilence() { + //given + RecordFileCommand recordFileCommand = new RecordFileCommand("some-file", "wav", "4", 10, 10, true, 15); + + //when + String actual = recordFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("RECORD FILE \"some-file\" \"wav\" \"4\" 10 10 BEEP s=15"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SayAlphaCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SayAlphaCommandTest.java new file mode 100644 index 000000000..030bd1f4a --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SayAlphaCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SayAlphaCommandTest { + @Test + void shouldBuildSayAlphaCommand() { + //given + SayAlphaCommand sayAlphaCommand = new SayAlphaCommand("some text"); + + //when + String actual = sayAlphaCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY ALPHA \"some text\" \"\""); + } + + @Test + void shouldBuildSayAlphaCommandWithEscapeDigits() { + //given + SayAlphaCommand sayAlphaCommand = new SayAlphaCommand("some text", "8"); + + //when + String actual = sayAlphaCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY ALPHA \"some text\" \"8\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SayDateTimeCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SayDateTimeCommandTest.java new file mode 100644 index 000000000..8e60a24d5 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SayDateTimeCommandTest.java @@ -0,0 +1,74 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import java.time.Instant; + +import static org.assertj.core.api.Assertions.assertThat; + +class SayDateTimeCommandTest { + private final long time = Instant.parse("2022-09-03T11:48:30.00Z").getEpochSecond(); + + @Test + void shouldBuildSayDateTimeCommand() { + //given + SayDateTimeCommand sayDateTimeCommand = new SayDateTimeCommand(time); + + //when + String actual = sayDateTimeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY DATETIME 1662205710 \"\""); + } + + @Test + void shouldBuildSayDateTimeCommandWithEscapeDigits() { + //given + SayDateTimeCommand sayDateTimeCommand = new SayDateTimeCommand(time, "1"); + + //when + String actual = sayDateTimeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY DATETIME 1662205710 \"1\""); + } + + @Test + void shouldBuildSayDateTimeCommandWithEscapeDigitsAndFormat() { + //given + SayDateTimeCommand sayDateTimeCommand = new SayDateTimeCommand(time, "1", "Y k"); + + //when + String actual = sayDateTimeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY DATETIME 1662205710 \"1\" \"Y k\""); + } + + @Test + void shouldBuildSayDateTimeCommandWithEscapeDigitsAndDefaultFormatAndTimezons() { + //given + SayDateTimeCommand sayDateTimeCommand = new SayDateTimeCommand(time, "1", null, "Poland"); + + //when + String actual = sayDateTimeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY DATETIME 1662205710 \"1\" \"ABdY 'digits/at' IMp\" \"Poland\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SayDigitsCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SayDigitsCommandTest.java new file mode 100644 index 000000000..e15572b12 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SayDigitsCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SayDigitsCommandTest { + @Test + void shouldBuildSayDigitsCommand() { + //given + SayDigitsCommand sayDigitsCommand = new SayDigitsCommand("1234"); + + //when + String actual = sayDigitsCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY DIGITS \"1234\" \"\""); + } + + @Test + void shouldBuildSayDigitsCommandWithEscapeDigit() { + //given + SayDigitsCommand sayDigitsCommand = new SayDigitsCommand("1234", "90"); + + //when + String actual = sayDigitsCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY DIGITS \"1234\" \"90\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SayNumberCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SayNumberCommandTest.java new file mode 100644 index 000000000..3b313e458 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SayNumberCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SayNumberCommandTest { + @Test + void shouldBuildSayNumberCommand() { + //given + SayNumberCommand sayNumberCommand = new SayNumberCommand("5426"); + + //when + String actual = sayNumberCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY NUMBER \"5426\" \"\""); + } + + @Test + void shouldBuildSayNumberCommandWithEscapeDigits() { + //given + SayNumberCommand sayNumberCommand = new SayNumberCommand("5426", "98"); + + //when + String actual = sayNumberCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY NUMBER \"5426\" \"98\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SayPhoneticCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SayPhoneticCommandTest.java new file mode 100644 index 000000000..f1c6a24e4 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SayPhoneticCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SayPhoneticCommandTest { + @Test + void shouldBuildSayPhonetic() { + //given + SayPhoneticCommand sayPhoneticCommand = new SayPhoneticCommand("some text"); + + //when + String actual = sayPhoneticCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY PHONETIC \"some text\" \"\""); + } + + @Test + void shouldBuildSayPhoneticWithEscapeDigits() { + //given + SayPhoneticCommand sayPhoneticCommand = new SayPhoneticCommand("some text", "89"); + + //when + String actual = sayPhoneticCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY PHONETIC \"some text\" \"89\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SayTimeCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SayTimeCommandTest.java new file mode 100644 index 000000000..88e2d953d --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SayTimeCommandTest.java @@ -0,0 +1,50 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import java.time.Instant; + +import static org.assertj.core.api.Assertions.assertThat; + +class SayTimeCommandTest { + private final long time = Instant.parse("2022-09-03T11:48:30.00Z").getEpochSecond(); + + @Test + void shouldBuildSayTimeCommand() { + //given + SayTimeCommand sayTimeCommand = new SayTimeCommand(time); + + //when + String actual = sayTimeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY TIME 1662205710 \"\""); + } + + @Test + void shouldBuildSayTimeCommandWithEscapeDigits() { + //given + SayTimeCommand sayTimeCommand = new SayTimeCommand(time, "89"); + + //when + String actual = sayTimeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SAY TIME 1662205710 \"89\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SendImageCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SendImageCommandTest.java new file mode 100644 index 000000000..15debddf5 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SendImageCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SendImageCommandTest { + @Test + void shouldBuildSendImageCommand() { + //given + SendImageCommand sendImageCommand = new SendImageCommand("image.png"); + + //when + String actual = sendImageCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SEND IMAGE \"image.png\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SendTextCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SendTextCommandTest.java new file mode 100644 index 000000000..a3b20a9a0 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SendTextCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SendTextCommandTest { + @Test + void shouldBuildSendTextCommand() { + //given + SendTextCommand sendTextCommand = new SendTextCommand("text to send"); + + //when + String actual = sendTextCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SEND TEXT \"text to send\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SetAutoHangupCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SetAutoHangupCommandTest.java new file mode 100644 index 000000000..064d96de5 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SetAutoHangupCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SetAutoHangupCommandTest { + @Test + void shouldBuildSetAutoHangupCommand() { + //given + SetAutoHangupCommand setAutoHangupCommand = new SetAutoHangupCommand(5); + + //when + String actual = setAutoHangupCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SET AUTOHANGUP 5"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SetCallerIdCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SetCallerIdCommandTest.java new file mode 100644 index 000000000..72ba1a8d2 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SetCallerIdCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SetCallerIdCommandTest { + @Test + void shouldBuildSetAutoHangupCommand() { + //given + SetCallerIdCommand setCallerIdCommand = new SetCallerIdCommand("500333444"); + + //when + String actual = setCallerIdCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SET CALLERID \"500333444\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SetContextCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SetContextCommandTest.java new file mode 100644 index 000000000..813ada1cb --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SetContextCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SetContextCommandTest { + @Test + void shouldBuildSetContextCommand() { + //given + SetContextCommand setContextCommand = new SetContextCommand("phones"); + + //when + String actual = setContextCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SET CONTEXT \"phones\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SetExtensionCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SetExtensionCommandTest.java new file mode 100644 index 000000000..da901c843 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SetExtensionCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SetExtensionCommandTest { + @Test + void shouldBuildSetExtensionCommand() { + //given + SetExtensionCommand setExtensionCommand = new SetExtensionCommand("SIP/123"); + + //when + String actual = setExtensionCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SET EXTENSION \"SIP/123\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SetMusicOffCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SetMusicOffCommandTest.java new file mode 100644 index 000000000..4c2b92514 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SetMusicOffCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SetMusicOffCommandTest { + @Test + void shouldBuildSetMusicOffCommand() { + //given + SetMusicOffCommand setMusicOffCommand = new SetMusicOffCommand(); + + //when + String actual = setMusicOffCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SET MUSIC OFF"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SetMusicOnCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SetMusicOnCommandTest.java new file mode 100644 index 000000000..f93bf3390 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SetMusicOnCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SetMusicOnCommandTest { + @Test + void shouldBuildSetMusicOnCommand() { + //given + SetMusicOnCommand setMusicOnCommand = new SetMusicOnCommand(); + + //when + String actual = setMusicOnCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SET MUSIC ON"); + } + + @Test + void shouldBuildSetMusicOnCommandWithClass() { + //given + SetMusicOnCommand setMusicOnCommand = new SetMusicOnCommand("moh-class"); + + //when + String actual = setMusicOnCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SET MUSIC ON \"moh-class\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SetPriorityCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SetPriorityCommandTest.java new file mode 100644 index 000000000..d63844bc1 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SetPriorityCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SetPriorityCommandTest { + @Test + void shouldBuildSetPriorityCommand() { + //given + SetPriorityCommand setPriorityCommand = new SetPriorityCommand("1"); + + //when + String actual = setPriorityCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SET PRIORITY \"1\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SetVariableCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SetVariableCommandTest.java new file mode 100644 index 000000000..b3c5f1cfb --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SetVariableCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SetVariableCommandTest { + @Test + void shouldBuildSetVariableCommand() { + //given + SetVariableCommand setVariableCommand = new SetVariableCommand("name", "value"); + + //when + String actual = setVariableCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SET VARIABLE \"name\" \"value\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SpeechActivateGrammarCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SpeechActivateGrammarCommandTest.java new file mode 100644 index 000000000..ea1fe404c --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SpeechActivateGrammarCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SpeechActivateGrammarCommandTest { + @Test + void shouldBuildSpeechActivateGrammarCommand() { + //given + SpeechActivateGrammarCommand speechActivateGrammarCommand = new SpeechActivateGrammarCommand("grammar name"); + + //when + String actual = speechActivateGrammarCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SPEECH ACTIVATE GRAMMAR \"grammar name\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SpeechCreateCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SpeechCreateCommandTest.java new file mode 100644 index 000000000..5fc77aac6 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SpeechCreateCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SpeechCreateCommandTest { + @Test + void shouldBuildSpeechCreateCommand() { + //given + SpeechCreateCommand speechCreateCommand = new SpeechCreateCommand("engine"); + + //when + String actual = speechCreateCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SPEECH CREATE \"engine\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SpeechDeactivateGrammarCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SpeechDeactivateGrammarCommandTest.java new file mode 100644 index 000000000..40309be00 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SpeechDeactivateGrammarCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SpeechDeactivateGrammarCommandTest { + @Test + void shouldBuildSpeechDeactivateGrammarCommand() { + //given + SpeechDeactivateGrammarCommand speechDeactivateGrammarCommand = new SpeechDeactivateGrammarCommand("grammar"); + + //when + String actual = speechDeactivateGrammarCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SPEECH DEACTIVATE GRAMMAR \"grammar\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SpeechDestroyCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SpeechDestroyCommandTest.java new file mode 100644 index 000000000..d3e5f3a41 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SpeechDestroyCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SpeechDestroyCommandTest { + @Test + void shouldBuildSpeechDestroyCommand() { + //given + SpeechDestroyCommand speechDestroyCommand = new SpeechDestroyCommand(); + + //when + String actual = speechDestroyCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SPEECH DESTROY"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SpeechLoadGrammarCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SpeechLoadGrammarCommandTest.java new file mode 100644 index 000000000..24be43c8f --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SpeechLoadGrammarCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SpeechLoadGrammarCommandTest { + @Test + void shouldBuildSpeechLoadGrammarCommand() { + //given + SpeechLoadGrammarCommand speechLoadGrammarCommand = new SpeechLoadGrammarCommand("grammar-name", "/path/to/grammar"); + + //when + String actual = speechLoadGrammarCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SPEECH LOAD GRAMMAR \"grammar-name\" \"/path/to/grammar\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SpeechRecognizeCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SpeechRecognizeCommandTest.java new file mode 100644 index 000000000..4ac6d098a --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SpeechRecognizeCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SpeechRecognizeCommandTest { + @Test + void shouldBuildSpeechRecognizeCommand() { + //given + SpeechRecognizeCommand speechRecognizeCommand = new SpeechRecognizeCommand("prompt", 10); + + //when + String actual = speechRecognizeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SPEECH RECOGNIZE \"prompt\" 10 0"); + } + + @Test + void shouldBuildSpeechRecognizeCommandWithOffset() { + //given + SpeechRecognizeCommand speechRecognizeCommand = new SpeechRecognizeCommand("prompt", 10, 20); + + //when + String actual = speechRecognizeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SPEECH RECOGNIZE \"prompt\" 10 20"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SpeechSetCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SpeechSetCommandTest.java new file mode 100644 index 000000000..bc337efa3 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SpeechSetCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SpeechSetCommandTest { + @Test + void shouldBuildSpeechSetCommand() { + //given + SpeechSetCommand speechSetCommand = new SpeechSetCommand("name", "value"); + + //when + String actual = speechSetCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SPEECH SET \"name\" \"value\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/SpeechUnloadGrammarCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/SpeechUnloadGrammarCommandTest.java new file mode 100644 index 000000000..1d2b0a84b --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/SpeechUnloadGrammarCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class SpeechUnloadGrammarCommandTest { + @Test + void shouldBuildSpeechUnloadGrammarCommand() { + //given + SpeechUnloadGrammarCommand speechUnloadGrammarCommand = new SpeechUnloadGrammarCommand("name"); + + //when + String actual = speechUnloadGrammarCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("SPEECH UNLOAD GRAMMAR \"name\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/StreamFileCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/StreamFileCommandTest.java new file mode 100644 index 000000000..fba122f23 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/StreamFileCommandTest.java @@ -0,0 +1,58 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class StreamFileCommandTest { + @Test + void shouldBuildStreamFileCommand() { + //given + StreamFileCommand streamFileCommand = new StreamFileCommand("file"); + + //when + String actual = streamFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("STREAM FILE \"file\" \"\""); + } + + @Test + void shouldBuildStreamFileCommandWithEscapeDigits() { + //given + StreamFileCommand streamFileCommand = new StreamFileCommand("file", "45"); + + //when + String actual = streamFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("STREAM FILE \"file\" \"45\""); + } + + @Test + void shouldBuildStreamFileCommandWithEscapeDigitsAndOffset() { + //given + StreamFileCommand streamFileCommand = new StreamFileCommand("file", "45", 20); + + //when + String actual = streamFileCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("STREAM FILE \"file\" \"45\" 20"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/TddModeCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/TddModeCommandTest.java new file mode 100644 index 000000000..aa0fafc27 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/TddModeCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class TddModeCommandTest { + @Test + void shouldBuildTddModeCommand() { + //given + TddModeCommand tddModeCommand = new TddModeCommand("on"); + + //when + String actual = tddModeCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("TDD MODE \"on\""); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/VerboseCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/VerboseCommandTest.java new file mode 100644 index 000000000..ee63a8aba --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/VerboseCommandTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class VerboseCommandTest { + @Test + void shouldBuildVerboseCommand() { + //given + VerboseCommand verboseCommand = new VerboseCommand("message to print", 1); + + //when + String actual = verboseCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("VERBOSE \"message to print\" 1"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/command/WaitForDigitCommandTest.java b/src/test/java/org/asteriskjava/fastagi/command/WaitForDigitCommandTest.java new file mode 100644 index 000000000..299a4f113 --- /dev/null +++ b/src/test/java/org/asteriskjava/fastagi/command/WaitForDigitCommandTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.fastagi.command; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class WaitForDigitCommandTest { + @Test + void shouldBuildWaitForDigitCommand() { + //given + WaitForDigitCommand waitForDigitCommand = new WaitForDigitCommand(); + + //when + String actual = waitForDigitCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("WAIT FOR DIGIT -1"); + } + + @Test + void shouldBuildWaitForDigitCommandWithTimeout() { + //given + WaitForDigitCommand waitForDigitCommand = new WaitForDigitCommand(10); + + //when + String actual = waitForDigitCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("WAIT FOR DIGIT 10"); + } +} diff --git a/src/test/java/org/asteriskjava/fastagi/internal/AgiChannelImplTest.java b/src/test/java/org/asteriskjava/fastagi/internal/AgiChannelImplTest.java index 7136d0424..8a9b8ffff 100644 --- a/src/test/java/org/asteriskjava/fastagi/internal/AgiChannelImplTest.java +++ b/src/test/java/org/asteriskjava/fastagi/internal/AgiChannelImplTest.java @@ -16,36 +16,33 @@ */ package org.asteriskjava.fastagi.internal; -import java.util.List; - -import junit.framework.TestCase; -import static org.easymock.EasyMock.*; - -import org.asteriskjava.fastagi.AgiChannel; -import org.asteriskjava.fastagi.InvalidCommandSyntaxException; -import org.asteriskjava.fastagi.InvalidOrUnknownCommandException; +import org.asteriskjava.fastagi.*; import org.asteriskjava.fastagi.command.NoopCommand; -import org.asteriskjava.fastagi.internal.AgiChannelImpl; import org.asteriskjava.fastagi.reply.AgiReply; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class AgiChannelImplTest extends TestCase -{ +class AgiChannelImplTest { private AgiWriter agiWriter; private AgiReader agiReader; private AgiChannel agiChannel; - @Override - protected void setUp() throws Exception - { - super.setUp(); - - this.agiWriter = createMock(AgiWriter.class); - this.agiReader = createMock(AgiReader.class); + @BeforeEach + void setUp() { + this.agiWriter = mock(AgiWriter.class); + this.agiReader = mock(AgiReader.class); this.agiChannel = new AgiChannelImpl(null, agiWriter, agiReader); } - public void testSendCommand() throws Exception - { + @Test + void testSendCommand() throws Exception { SimpleAgiReply reply; NoopCommand command; @@ -55,21 +52,13 @@ public void testSendCommand() throws Exception command = new NoopCommand(); - agiWriter.sendCommand(command); - expect(agiReader.readReply()).andReturn(reply); - - replay(agiWriter); - replay(agiReader); + when(agiReader.readReply()).thenReturn(reply); assertEquals(reply, agiChannel.sendCommand(command)); - - verify(agiWriter); - verify(agiReader); } - public void testSendCommandWithInvalidOrUnknownCommandResponse() - throws Exception - { + @Test + void testSendCommandWithInvalidOrUnknownCommandResponse() throws Exception { SimpleAgiReply reply; NoopCommand command; @@ -79,30 +68,18 @@ public void testSendCommandWithInvalidOrUnknownCommandResponse() command = new NoopCommand(); - agiWriter.sendCommand(command); - expect(agiReader.readReply()).andReturn(reply); - - replay(agiWriter); - replay(agiReader); + when(agiReader.readReply()).thenReturn(reply); - try - { + try { agiChannel.sendCommand(command); fail("must throw InvalidOrUnknownCommandException"); + } catch (InvalidOrUnknownCommandException e) { + assertEquals("Invalid or unknown command: NOOP", e.getMessage(), "Incorrect message"); } - catch (InvalidOrUnknownCommandException e) - { - assertEquals("Incorrect message", - "Invalid or unknown command: NOOP", e.getMessage()); - } - - verify(agiWriter); - verify(agiReader); } - public void testSendCommandWithInvalidCommandSyntaxResponse() - throws Exception - { + @Test + void testSendCommandWithInvalidCommandSyntaxResponse() throws Exception { SimpleAgiReply reply; NoopCommand command; @@ -114,105 +91,78 @@ public void testSendCommandWithInvalidCommandSyntaxResponse() command = new NoopCommand(); - agiWriter.sendCommand(command); - expect(agiReader.readReply()).andReturn(reply); + when(agiReader.readReply()).thenReturn(reply); - replay(agiWriter); - replay(agiReader); - - try - { + try { agiChannel.sendCommand(command); fail("must throw InvalidCommandSyntaxException"); + } catch (InvalidCommandSyntaxException e) { + assertEquals("Invalid command syntax: NOOP Synopsis", e.getMessage(), "Incorrect message"); + assertEquals("NOOP Synopsis", e.getSynopsis(), "Incorrect sysnopsis"); + assertEquals("NOOP Usage", e.getUsage(), "Incorrect usage"); } - catch (InvalidCommandSyntaxException e) - { - assertEquals("Incorrect message", - "Invalid command syntax: NOOP Synopsis", e.getMessage()); - assertEquals("Incorrect sysnopsis", "NOOP Synopsis", e - .getSynopsis()); - assertEquals("Incorrect usage", "NOOP Usage", e.getUsage()); - } - - verify(agiWriter); - verify(agiReader); } - public class SimpleAgiReply implements AgiReply - { - private static final long serialVersionUID = 1L; - private int status; + public static class SimpleAgiReply implements AgiReply { + private static final long serialVersionUID = 1L; + private int status; private String result; private String synopsis; private String usage; - - public String getFirstLine() - { + + public String getFirstLine() { throw new UnsupportedOperationException(); } - public void setUsage(String usage) - { + public void setUsage(String usage) { this.usage = usage; } - public void setSynopsis(String synopsis) - { + public void setSynopsis(String synopsis) { this.synopsis = synopsis; } - public void setResult(String result) - { + public void setResult(String result) { this.result = result; } - public void setStatus(int status) - { + public void setStatus(int status) { this.status = status; } - public List getLines() - { + public List getLines() { throw new UnsupportedOperationException(); } - public int getResultCode() - { + public int getResultCode() { throw new UnsupportedOperationException(); } - public char getResultCodeAsChar() - { + public char getResultCodeAsChar() { throw new UnsupportedOperationException(); } - public String getResult() - { + public String getResult() { return result; } - public int getStatus() - { + public int getStatus() { return status; } - public String getAttribute(String name) - { + public String getAttribute(String name) { throw new UnsupportedOperationException(); } - public String getExtra() - { + public String getExtra() { throw new UnsupportedOperationException(); } - public String getSynopsis() - { + public String getSynopsis() { return synopsis; } - public String getUsage() - { + public String getUsage() { return usage; } } diff --git a/src/test/java/org/asteriskjava/fastagi/internal/AgiReaderImplTest.java b/src/test/java/org/asteriskjava/fastagi/internal/AgiReaderImplTest.java index c78eee68c..58e351cb0 100644 --- a/src/test/java/org/asteriskjava/fastagi/internal/AgiReaderImplTest.java +++ b/src/test/java/org/asteriskjava/fastagi/internal/AgiReaderImplTest.java @@ -16,144 +16,124 @@ */ package org.asteriskjava.fastagi.internal; -import java.net.InetAddress; - -import junit.framework.TestCase; -import static org.easymock.EasyMock.*; - import org.asteriskjava.fastagi.AgiHangupException; +import org.asteriskjava.fastagi.AgiReader; import org.asteriskjava.fastagi.AgiRequest; -import org.asteriskjava.fastagi.internal.FastAgiReader; import org.asteriskjava.fastagi.reply.AgiReply; import org.asteriskjava.util.SocketConnectionFacade; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.net.InetAddress; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class AgiReaderImplTest extends TestCase -{ +class AgiReaderImplTest { private AgiReader agiReader; private SocketConnectionFacade socket; - @Override - protected void setUp() throws Exception - { - super.setUp(); - this.socket = createMock(SocketConnectionFacade.class); + @BeforeEach + void setUp() { + this.socket = mock(SocketConnectionFacade.class); this.agiReader = new FastAgiReader(socket); } - public void testReadRequest() throws Exception - { + @Test + void testReadRequest() throws Exception { AgiRequest request; - expect(socket.readLine()).andReturn("agi_network: yes"); - expect(socket.readLine()).andReturn("agi_network_script: myscript.agi"); - expect(socket.readLine()).andReturn("agi_request: agi://host/myscript.agi"); - expect(socket.readLine()).andReturn("agi_channel: SIP/1234-d715"); - expect(socket.readLine()).andReturn(""); + when(socket.readLine()) + .thenReturn("agi_network: yes") + .thenReturn("agi_network_script: myscript.agi") + .thenReturn("agi_request: agi://host/myscript.agi") + .thenReturn("agi_channel: SIP/1234-d715") + .thenReturn(""); byte[] ipLocal = new byte[4]; ipLocal[0] = Integer.valueOf(192).byteValue(); ipLocal[1] = Integer.valueOf(168).byteValue(); ipLocal[2] = Integer.valueOf(0).byteValue(); ipLocal[3] = Integer.valueOf(1).byteValue(); - expect(socket.getLocalAddress()).andReturn(InetAddress.getByAddress(ipLocal)); - expect(socket.getLocalPort()).andReturn(1234); + when(socket.getLocalAddress()).thenReturn(InetAddress.getByAddress(ipLocal)); + when(socket.getLocalPort()).thenReturn(1234); byte[] ipRemote = new byte[4]; ipRemote[0] = Integer.valueOf(192).byteValue(); ipRemote[1] = Integer.valueOf(168).byteValue(); ipRemote[2] = Integer.valueOf(0).byteValue(); ipRemote[3] = Integer.valueOf(2).byteValue(); - expect(socket.getRemoteAddress()).andReturn(InetAddress.getByAddress(ipRemote)); - expect(socket.getRemotePort()).andReturn(1235); - - replay(socket); + when(socket.getRemoteAddress()).thenReturn(InetAddress.getByAddress(ipRemote)); + when(socket.getRemotePort()).thenReturn(1235); request = agiReader.readRequest(); - assertEquals("incorrect script", "myscript.agi", request.getScript()); - assertEquals("incorrect requestURL", "agi://host/myscript.agi", request.getRequestURL()); - assertEquals("incorrect channel", "SIP/1234-d715", request.getChannel()); - assertEquals("incorrect local address", ipLocal[0], request.getLocalAddress().getAddress()[0]); - assertEquals("incorrect local address", ipLocal[1], request.getLocalAddress().getAddress()[1]); - assertEquals("incorrect local address", ipLocal[2], request.getLocalAddress().getAddress()[2]); - assertEquals("incorrect local address", ipLocal[3], request.getLocalAddress().getAddress()[3]); - assertEquals("incorrect local port", 1234, request.getLocalPort()); - assertEquals("incorrect remote address", ipRemote[0], request.getRemoteAddress().getAddress()[0]); - assertEquals("incorrect remote address", ipRemote[1], request.getRemoteAddress().getAddress()[1]); - assertEquals("incorrect remote address", ipRemote[2], request.getRemoteAddress().getAddress()[2]); - assertEquals("incorrect remote address", ipRemote[3], request.getRemoteAddress().getAddress()[3]); - assertEquals("incorrect remote port", 1235, request.getRemotePort()); - - verify(socket); + assertEquals("myscript.agi", request.getScript(), "incorrect script"); + assertEquals("agi://host/myscript.agi", request.getRequestURL(), "incorrect requestURL"); + assertEquals("SIP/1234-d715", request.getChannel(), "incorrect channel"); + assertEquals(ipLocal[0], request.getLocalAddress().getAddress()[0], "incorrect local address"); + assertEquals(ipLocal[1], request.getLocalAddress().getAddress()[1], "incorrect local address"); + assertEquals(ipLocal[2], request.getLocalAddress().getAddress()[2], "incorrect local address"); + assertEquals(ipLocal[3], request.getLocalAddress().getAddress()[3], "incorrect local address"); + assertEquals(1234, request.getLocalPort(), "incorrect local port"); + assertEquals(ipRemote[0], request.getRemoteAddress().getAddress()[0], "incorrect remote address"); + assertEquals(ipRemote[1], request.getRemoteAddress().getAddress()[1], "incorrect remote address"); + assertEquals(ipRemote[2], request.getRemoteAddress().getAddress()[2], "incorrect remote address"); + assertEquals(ipRemote[3], request.getRemoteAddress().getAddress()[3], "incorrect remote address"); + assertEquals(1235, request.getRemotePort(), "incorrect remote port"); } - public void testReadReply() throws Exception - { + @Test + void testReadReply() throws Exception { AgiReply reply; - expect(socket.readLine()).andReturn("200 result=49 endpos=2240"); - - replay(socket); + when(socket.readLine()).thenReturn("200 result=49 endpos=2240"); reply = agiReader.readReply(); - assertEquals("Incorrect status", AgiReply.SC_SUCCESS, reply.getStatus()); - assertEquals("Incorrect result", 49, reply.getResultCode()); - - verify(socket); + assertEquals(AgiReply.SC_SUCCESS, reply.getStatus(), "Incorrect status"); + assertEquals(49, reply.getResultCode(), "Incorrect result"); } - public void testReadReplyInvalidOrUnknownCommand() throws Exception - { + @Test + void testReadReplyInvalidOrUnknownCommand() throws Exception { AgiReply reply; - expect(socket.readLine()).andReturn("510 Invalid or unknown command"); - - replay(socket); + when(socket.readLine()).thenReturn("510 Invalid or unknown command"); reply = agiReader.readReply(); - assertEquals("Incorrect status", AgiReply.SC_INVALID_OR_UNKNOWN_COMMAND, reply.getStatus()); - - verify(socket); + assertEquals(AgiReply.SC_INVALID_OR_UNKNOWN_COMMAND, reply.getStatus(), "Incorrect status"); } - public void testReadReplyInvalidCommandSyntax() throws Exception - { + @Test + void testReadReplyInvalidCommandSyntax() throws Exception { AgiReply reply; - expect(socket.readLine()).andReturn("520-Invalid command syntax. Proper usage follows:"); - expect(socket.readLine()).andReturn(" Usage: DATABASE DEL "); - expect(socket.readLine()).andReturn(" Deletes an entry in the Asterisk database for a"); - expect(socket.readLine()).andReturn(" given family and key."); - expect(socket.readLine()).andReturn(" Returns 1 if succesful, 0 otherwise"); - expect(socket.readLine()).andReturn("520 End of proper usage."); - - replay(socket); + when(socket.readLine()) + .thenReturn("520-Invalid command syntax. Proper usage follows:") + .thenReturn(" Usage: DATABASE DEL ") + .thenReturn(" Deletes an entry in the Asterisk database for a") + .thenReturn(" given family and key.") + .thenReturn(" Returns 1 if succesful, 0 otherwise") + .thenReturn("520 End of proper usage."); reply = agiReader.readReply(); - assertEquals("Incorrect status", AgiReply.SC_INVALID_COMMAND_SYNTAX, reply.getStatus()); - assertEquals("Incorrect synopsis", "DATABASE DEL ", reply.getSynopsis()); - - verify(socket); + assertEquals(AgiReply.SC_INVALID_COMMAND_SYNTAX, reply.getStatus(), "Incorrect status"); + assertEquals("DATABASE DEL ", reply.getSynopsis(), "Incorrect synopsis"); } - public void testReadReplyWhenHungUp() throws Exception - { - expect(socket.readLine()).andReturn(null); - - replay(socket); + @Test + void testReadReplyWhenHungUp() throws Exception { + when(socket.readLine()).thenReturn(null); - try - { + try { agiReader.readReply(); fail("Must throw AgiHangupException"); + } catch (AgiHangupException e) { } - catch (AgiHangupException e) - { - } - - verify(socket); } } diff --git a/src/test/java/org/asteriskjava/fastagi/internal/AgiReplyImplTest.java b/src/test/java/org/asteriskjava/fastagi/internal/AgiReplyImplTest.java index d63372ebd..6b8699bdd 100644 --- a/src/test/java/org/asteriskjava/fastagi/internal/AgiReplyImplTest.java +++ b/src/test/java/org/asteriskjava/fastagi/internal/AgiReplyImplTest.java @@ -16,145 +16,144 @@ */ package org.asteriskjava.fastagi.internal; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; - -import org.asteriskjava.fastagi.internal.AgiReplyImpl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class AgiReplyImplTest extends TestCase -{ +class AgiReplyImplTest { private List lines; - @Override - protected void setUp() - { - this.lines = new ArrayList(); + @BeforeEach + void setUp() { + this.lines = new ArrayList<>(); } - public void testBuildReply() - { + @Test + void testBuildReply() { AgiReplyImpl reply; lines.add("200 result=49"); reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_SUCCESS, reply.getStatus()); - assertEquals("Incorrect result", 49, reply.getResultCode()); - assertEquals("Incorrect result as character", '1', reply.getResultCodeAsChar()); - assertEquals("Incorrect result when get via getAttribute()", "49", reply.getAttribute("result")); + assertEquals(AgiReplyImpl.SC_SUCCESS, reply.getStatus(), "Incorrect status"); + assertEquals(49, reply.getResultCode(), "Incorrect result"); + assertEquals('1', reply.getResultCodeAsChar(), "Incorrect result as character"); + assertEquals("49", reply.getAttribute("result"), "Incorrect result when get via getAttribute()"); } - public void testBuildReplyWithAdditionalAttribute() - { + @Test + void testBuildReplyWithAdditionalAttribute() { AgiReplyImpl reply; lines.add("200 result=49 endpos=2240"); reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_SUCCESS, reply.getStatus()); - assertEquals("Incorrect result", 49, reply.getResultCode()); - assertEquals("Incorrect result as character", '1', reply.getResultCodeAsChar()); - assertEquals("Incorrect result when get via getAttribute()", "49", reply.getAttribute("result")); - assertEquals("Incorrect endpos attribute", "2240", reply.getAttribute("endpos")); + assertEquals(AgiReplyImpl.SC_SUCCESS, reply.getStatus(), "Incorrect status"); + assertEquals(49, reply.getResultCode(), "Incorrect result"); + assertEquals('1', reply.getResultCodeAsChar(), "Incorrect result as character"); + assertEquals("49", reply.getAttribute("result"), "Incorrect result when get via getAttribute()"); + assertEquals("2240", reply.getAttribute("endpos"), "Incorrect endpos attribute"); } - public void testBuildReplyWithMultipleAdditionalAttribute() - { + @Test + void testBuildReplyWithMultipleAdditionalAttribute() { AgiReplyImpl reply; lines.add("200 result=49 startpos=1234 endpos=2240"); reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_SUCCESS, reply.getStatus()); - assertEquals("Incorrect result", 49, reply.getResultCode()); - assertEquals("Incorrect result as character", '1', reply.getResultCodeAsChar()); - assertEquals("Incorrect result when get via getAttribute()", "49", reply.getAttribute("result")); - assertEquals("Incorrect startpos attribute", "1234", reply.getAttribute("startpos")); - assertEquals("Incorrect endpos attribute", "2240", reply.getAttribute("endpos")); + assertEquals(AgiReplyImpl.SC_SUCCESS, reply.getStatus(), "Incorrect status"); + assertEquals(49, reply.getResultCode(), "Incorrect result"); + assertEquals('1', reply.getResultCodeAsChar(), "Incorrect result as character"); + assertEquals("49", reply.getAttribute("result"), "Incorrect result when get via getAttribute()"); + assertEquals("1234", reply.getAttribute("startpos"), "Incorrect startpos attribute"); + assertEquals("2240", reply.getAttribute("endpos"), "Incorrect endpos attribute"); } - public void testBuildReplyWithQuotedAttribute() - { + @Test + void testBuildReplyWithQuotedAttribute() { AgiReplyImpl reply; lines.add("200 result=1 (speech) endpos=0 results=1 score0=969 text0=\"123456789\" grammar0=digits"); reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_SUCCESS, reply.getStatus()); - assertEquals("Incorrect result", 1, reply.getResultCode()); - assertEquals("Incorrect result when get via getAttribute()", "1", reply.getAttribute("result")); - assertEquals("Incorrect endpos attribute", "0", reply.getAttribute("endpos")); - assertEquals("Incorrect extra", "speech", reply.getExtra()); - assertEquals("Incorrect text0 attribute", "123456789", reply.getAttribute("text0")); + assertEquals(AgiReplyImpl.SC_SUCCESS, reply.getStatus(), "Incorrect status"); + assertEquals(1, reply.getResultCode(), "Incorrect result"); + assertEquals("1", reply.getAttribute("result"), "Incorrect result when get via getAttribute()"); + assertEquals("0", reply.getAttribute("endpos"), "Incorrect endpos attribute"); + assertEquals("speech", reply.getExtra(), "Incorrect extra"); + assertEquals("123456789", reply.getAttribute("text0"), "Incorrect text0 attribute"); } - public void testBuildReplyWithQuotedAttribute2() - { + @Test + void testBuildReplyWithQuotedAttribute2() { AgiReplyImpl reply; lines.add("200 result=1 (speech) endpos=0 results=1 score0=969 text0=\"hi \\\"joe!\\\"\" grammar0=digits"); reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_SUCCESS, reply.getStatus()); - assertEquals("Incorrect result", 1, reply.getResultCode()); - assertEquals("Incorrect result when get via getAttribute()", "1", reply.getAttribute("result")); - assertEquals("Incorrect endpos attribute", "0", reply.getAttribute("endpos")); - assertEquals("Incorrect extra", "speech", reply.getExtra()); - assertEquals("Incorrect text0 attribute", "hi \"joe!\"", reply.getAttribute("text0")); + assertEquals(AgiReplyImpl.SC_SUCCESS, reply.getStatus(), "Incorrect status"); + assertEquals(1, reply.getResultCode(), "Incorrect result"); + assertEquals("1", reply.getAttribute("result"), "Incorrect result when get via getAttribute()"); + assertEquals("0", reply.getAttribute("endpos"), "Incorrect endpos attribute"); + assertEquals("speech", reply.getExtra(), "Incorrect extra"); + assertEquals("hi \"joe!\"", reply.getAttribute("text0"), "Incorrect text0 attribute"); } - public void testBla() - { + void testBla() { System.out.println(005); } - public void testBuildReplyWithParenthesis() - { + @Test + void testBuildReplyWithParenthesis() { AgiReplyImpl reply; lines.add("200 result=1 ((hello)(world))"); reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_SUCCESS, reply.getStatus()); - assertEquals("Incorrect result", 1, reply.getResultCode()); - assertEquals("Incorrect parenthesis", "(hello)(world)", reply.getExtra()); + assertEquals(AgiReplyImpl.SC_SUCCESS, reply.getStatus(), "Incorrect status"); + assertEquals(1, reply.getResultCode(), "Incorrect result"); + assertEquals("(hello)(world)", reply.getExtra(), "Incorrect parenthesis"); } - public void testBuildReplyWithAdditionalAttributeAndParenthesis() - { + @Test + void testBuildReplyWithAdditionalAttributeAndParenthesis() { AgiReplyImpl reply; lines.add("200 result=1 ((hello)(world)) endpos=2240"); reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_SUCCESS, reply.getStatus()); - assertEquals("Incorrect result", 1, reply.getResultCode()); - assertEquals("Incorrect parenthesis", "(hello)(world)", reply.getExtra()); - assertEquals("Incorrect endpos attribute", "2240", reply.getAttribute("endpos")); + assertEquals(AgiReplyImpl.SC_SUCCESS, reply.getStatus(), "Incorrect status"); + assertEquals(1, reply.getResultCode(), "Incorrect result"); + assertEquals("(hello)(world)", reply.getExtra(), "Incorrect parenthesis"); + assertEquals("2240", reply.getAttribute("endpos"), "Incorrect endpos attribute"); } - public void testBuildReplyInvalidOrUnknownCommand() - { + @Test + void testBuildReplyInvalidOrUnknownCommand() { AgiReplyImpl reply; lines.add("510 Invalid or unknown command"); reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_INVALID_OR_UNKNOWN_COMMAND, reply.getStatus()); + assertEquals(AgiReplyImpl.SC_INVALID_OR_UNKNOWN_COMMAND, reply.getStatus(), "Incorrect status"); } - public void testBuildReplyInvalidCommandSyntax() - { + @Test + void testBuildReplyInvalidCommandSyntax() { AgiReplyImpl reply; lines.add("520-Invalid command syntax. Proper usage follows:"); @@ -166,15 +165,13 @@ public void testBuildReplyInvalidCommandSyntax() reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_INVALID_COMMAND_SYNTAX, reply.getStatus()); - assertEquals("Incorrect synopsis", "DATABASE DEL ", reply.getSynopsis()); - assertEquals("Incorrect usage", - "Deletes an entry in the Asterisk database for a given family and key. Returns 1 if succesful, 0 otherwise", - reply.getUsage()); + assertEquals(AgiReplyImpl.SC_INVALID_COMMAND_SYNTAX, reply.getStatus(), "Incorrect status"); + assertEquals("DATABASE DEL ", reply.getSynopsis(), "Incorrect synopsis"); + assertEquals("Deletes an entry in the Asterisk database for a given family and key. Returns 1 if succesful, 0 otherwise", reply.getUsage(), "Incorrect usage"); } - public void testBuildReplyInvalidCommandSyntaxWithOnlyUsage() - { + @Test + void testBuildReplyInvalidCommandSyntaxWithOnlyUsage() { AgiReplyImpl reply; lines.add("520-Invalid command syntax. Proper usage follows:"); @@ -186,38 +183,36 @@ public void testBuildReplyInvalidCommandSyntaxWithOnlyUsage() reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_INVALID_COMMAND_SYNTAX, reply.getStatus()); - // due to the lazy initialization in use this getUsage() could fail if we don't call it before getSynopsis() - assertEquals("Incorrect usage", - "Deletes an entry in the Asterisk database for a given family and key. Returns 1 if succesful, 0 otherwise", - reply.getUsage()); - assertEquals("Incorrect synopsis", "DATABASE DEL ", reply.getSynopsis()); + assertEquals(AgiReplyImpl.SC_INVALID_COMMAND_SYNTAX, reply.getStatus(), "Incorrect status"); + // due to the lazy initialization in use this getUsage() could fail if + // we don't call it before getSynopsis() + assertEquals("Deletes an entry in the Asterisk database for a given family and key. Returns 1 if succesful, 0 otherwise", reply.getUsage(), "Incorrect usage"); + assertEquals("DATABASE DEL ", reply.getSynopsis(), "Incorrect synopsis"); } - public void testBuildReplyWithLeadingSpace() - { + @Test + void testBuildReplyWithLeadingSpace() { AgiReplyImpl reply; lines.add("200 result= (timeout)"); reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_SUCCESS, reply.getStatus()); - assertEquals("Incorrect extra", "timeout", reply.getExtra()); + assertEquals(AgiReplyImpl.SC_SUCCESS, reply.getStatus(), "Incorrect status"); + assertEquals("timeout", reply.getExtra(), "Incorrect extra"); } - - public void testBuildReplyWithEmptyResultAndTimeout() - { + + @Test + void testBuildReplyWithEmptyResultAndTimeout() { AgiReplyImpl reply; lines.add("200 result= (timeout)"); reply = new AgiReplyImpl(lines); - assertFalse("Incorrect result",reply.getResult().equals("timeout")); - assertEquals("Incorrect result", "", reply.getResult()); - assertEquals("Incorrect extra", "timeout", reply.getExtra()); - + assertFalse(reply.getResult().equals("timeout"), "Incorrect result"); + assertEquals("", reply.getResult(), "Incorrect result"); + assertEquals("timeout", reply.getExtra(), "Incorrect extra"); } } diff --git a/src/test/java/org/asteriskjava/fastagi/internal/AgiRequestImplTest.java b/src/test/java/org/asteriskjava/fastagi/internal/AgiRequestImplTest.java index edeead66b..10a19be8f 100644 --- a/src/test/java/org/asteriskjava/fastagi/internal/AgiRequestImplTest.java +++ b/src/test/java/org/asteriskjava/fastagi/internal/AgiRequestImplTest.java @@ -16,24 +16,19 @@ */ package org.asteriskjava.fastagi.internal; +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.fastagi.AgiRequest; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; - -import org.asteriskjava.fastagi.AgiRequest; -import org.asteriskjava.fastagi.internal.AgiRequestImpl; - -public class AgiRequestImplTest extends TestCase -{ - @Override - protected void setUp() - { - } +import static org.junit.jupiter.api.Assertions.*; +class AgiRequestImplTest { @SuppressWarnings("deprecation") - public void testBuildRequest() - { + @Test + void testBuildRequest() { List lines; AgiRequest request; @@ -54,29 +49,31 @@ public void testBuildRequest() lines.add("agi_priority: 1"); lines.add("agi_enhanced: 0.0"); lines.add("agi_accountcode: "); + lines.add("agi_version: 13.1.0~dfsg-1.1ubuntu4.1"); request = new AgiRequestImpl(lines); - assertEquals("incorrect script", "myscript.agi", request.getScript()); - assertEquals("incorrect requestURL", "agi://host/myscript.agi", request.getRequestURL()); - assertEquals("incorrect channel", "SIP/1234-d715", request.getChannel()); - assertEquals("incorrect uniqueId", "SIP/1234-d715", request.getChannel()); - assertEquals("incorrect type", "SIP", request.getType()); - assertEquals("incorrect uniqueId", "1110023416.6", request.getUniqueId()); - assertEquals("incorrect language", "en", request.getLanguage()); - assertEquals("incorrect callerId", "1234", request.getCallerId()); - assertEquals("incorrect callerIdName", "John Doe", request.getCallerIdName()); - assertEquals("incorrect dnid", "8870", request.getDnid()); - assertEquals("incorrect rdnis", "9876", request.getRdnis()); - assertEquals("incorrect context", "local", request.getContext()); - assertEquals("incorrect extension", "8870", request.getExtension()); - assertEquals("incorrect priority", new Integer(1), request.getPriority()); - assertEquals("incorrect enhanced", Boolean.FALSE, request.getEnhanced()); - assertNull("incorrect accountCode must not be set", request.getAccountCode()); + assertEquals("myscript.agi", request.getScript(), "incorrect script"); + assertEquals("agi://host/myscript.agi", request.getRequestURL(), "incorrect requestURL"); + assertEquals("SIP/1234-d715", request.getChannel(), "incorrect channel"); + assertEquals("SIP/1234-d715", request.getChannel(), "incorrect uniqueId"); + assertEquals("SIP", request.getType(), "incorrect type"); + assertEquals("1110023416.6", request.getUniqueId(), "incorrect uniqueId"); + assertEquals("en", request.getLanguage(), "incorrect language"); + assertEquals("1234", request.getCallerId(), "incorrect callerId"); + assertEquals("John Doe", request.getCallerIdName(), "incorrect callerIdName"); + assertEquals("8870", request.getDnid(), "incorrect dnid"); + assertEquals("9876", request.getRdnis(), "incorrect rdnis"); + assertEquals("local", request.getContext(), "incorrect context"); + assertEquals("8870", request.getExtension(), "incorrect extension"); + assertEquals(Integer.valueOf(1), request.getPriority(), "incorrect priority"); + assertEquals(Boolean.FALSE, request.getEnhanced(), "incorrect enhanced"); + assertNull(request.getAccountCode(), "incorrect accountCode must not be set"); + assertEquals(AsteriskVersion.ASTERISK_13, request.getAsteriskVersion(), "incorret Asterisk Version Number"); } - public void testBuildRequestWithAccountCode() - { + @Test + void testBuildRequestWithAccountCode() { List lines; AgiRequest request; @@ -88,12 +85,12 @@ public void testBuildRequestWithAccountCode() request = new AgiRequestImpl(lines); - assertEquals("incorrect accountCode", "12345", request.getAccountCode()); + assertEquals("12345", request.getAccountCode(), "incorrect accountCode"); } @SuppressWarnings("deprecation") - public void testBuildRequestWithoutCallerIdName() - { + @Test + void testBuildRequestWithoutCallerIdName() { List lines; AgiRequest request; @@ -103,14 +100,15 @@ public void testBuildRequestWithoutCallerIdName() request = new AgiRequestImpl(lines); - assertEquals("incorrect callerId", "1234", request.getCallerId()); - assertEquals("incorrect callerIdNumber", "1234", request.getCallerIdNumber()); - //assertNull("callerIdName must not be set", request.getCallerIdName()); + assertEquals("1234", request.getCallerId(), "incorrect callerId"); + assertEquals("1234", request.getCallerIdNumber(), "incorrect callerIdNumber"); + // assertNull("callerIdName must not be set", + // request.getCallerIdName()); } @SuppressWarnings("deprecation") - public void testBuildRequestWithoutCallerIdNameButBracket() - { + @Test + void testBuildRequestWithoutCallerIdNameButBracket() { List lines; AgiRequest request; @@ -120,14 +118,14 @@ public void testBuildRequestWithoutCallerIdNameButBracket() request = new AgiRequestImpl(lines); - assertEquals("incorrect callerId", "1234", request.getCallerId()); - assertEquals("incorrect callerIdNumber", "1234", request.getCallerIdNumber()); - assertNull("callerIdName must not be set", request.getCallerIdName()); + assertEquals("1234", request.getCallerId(), "incorrect callerId"); + assertEquals("1234", request.getCallerIdNumber(), "incorrect callerIdNumber"); + assertNull(request.getCallerIdName(), "callerIdName must not be set"); } @SuppressWarnings("deprecation") - public void testBuildRequestWithoutCallerIdNameButBracketAndQuotesAndSpace() - { + @Test + void testBuildRequestWithoutCallerIdNameButBracketAndQuotesAndSpace() { List lines; AgiRequest request; @@ -137,14 +135,14 @@ public void testBuildRequestWithoutCallerIdNameButBracketAndQuotesAndSpace() request = new AgiRequestImpl(lines); - assertEquals("incorrect callerId", "1234", request.getCallerId()); - assertEquals("incorrect callerIdNumber", "1234", request.getCallerIdNumber()); - assertNull("callerIdName must not be set", request.getCallerIdName()); + assertEquals("1234", request.getCallerId(), "incorrect callerId"); + assertEquals("1234", request.getCallerIdNumber(), "incorrect callerIdNumber"); + assertNull(request.getCallerIdName(), "callerIdName must not be set"); } @SuppressWarnings("deprecation") - public void testBuildRequestWithQuotedCallerIdName() - { + @Test + void testBuildRequestWithQuotedCallerIdName() { List lines; AgiRequest request; @@ -154,14 +152,14 @@ public void testBuildRequestWithQuotedCallerIdName() request = new AgiRequestImpl(lines); - assertEquals("incorrect callerId", "1234", request.getCallerId()); - assertEquals("incorrect callerIdNumber", "1234", request.getCallerIdNumber()); - assertEquals("incorrect callerIdName", "John Doe", request.getCallerIdName()); + assertEquals("1234", request.getCallerId(), "incorrect callerId"); + assertEquals("1234", request.getCallerIdNumber(), "incorrect callerIdNumber"); + assertEquals("John Doe", request.getCallerIdName(), "incorrect callerIdName"); } @SuppressWarnings("deprecation") - public void testBuildRequestWithQuotedCallerIdNameAndSpace() - { + @Test + void testBuildRequestWithQuotedCallerIdNameAndSpace() { List lines; AgiRequest request; @@ -171,14 +169,14 @@ public void testBuildRequestWithQuotedCallerIdNameAndSpace() request = new AgiRequestImpl(lines); - assertEquals("incorrect callerId", "1234", request.getCallerId()); - assertEquals("incorrect callerIdNumber", "1234", request.getCallerIdNumber()); - assertEquals("incorrect callerIdName", "John Doe", request.getCallerIdName()); + assertEquals("1234", request.getCallerId(), "incorrect callerId"); + assertEquals("1234", request.getCallerIdNumber(), "incorrect callerIdNumber"); + assertEquals("John Doe", request.getCallerIdName(), "incorrect callerIdName"); } @SuppressWarnings("deprecation") - public void testBuildRequestWithoutCallerId() - { + @Test + void testBuildRequestWithoutCallerId() { List lines; AgiRequest request; @@ -188,18 +186,18 @@ public void testBuildRequestWithoutCallerId() request = new AgiRequestImpl(lines); - assertNull("callerId must not be set", request.getCallerId()); - assertNull("callerIdNumber must not be set", request.getCallerIdNumber()); - assertNull("callerIdName must not be set", request.getCallerIdName()); + assertNull(request.getCallerId(), "callerId must not be set"); + assertNull(request.getCallerIdNumber(), "callerIdNumber must not be set"); + assertNull(request.getCallerIdName(), "callerIdName must not be set"); } /* - * Asterisk 1.2 now uses agi_callerid and agi_calleridname so we don't need to process - * it ourselves. + * Asterisk 1.2 now uses agi_callerid and agi_calleridname so we don't need + * to process it ourselves. */ @SuppressWarnings("deprecation") - public void testBuildRequestCallerIdAsterisk12() - { + @Test + void testBuildRequestCallerIdAsterisk12() { List lines; AgiRequest request; @@ -210,14 +208,14 @@ public void testBuildRequestCallerIdAsterisk12() request = new AgiRequestImpl(lines); - assertEquals("incorrect callerId", "1234", request.getCallerId()); - assertEquals("incorrect callerIdNumber", "1234", request.getCallerIdNumber()); - assertEquals("incorrect callerIdName", "John Doe", request.getCallerIdName()); + assertEquals("1234", request.getCallerId(), "incorrect callerId"); + assertEquals("1234", request.getCallerIdNumber(), "incorrect callerIdNumber"); + assertEquals("John Doe", request.getCallerIdName(), "incorrect callerIdName"); } @SuppressWarnings("deprecation") - public void testBuildRequestCallerIdAsterisk12WithUnknownCallerId() - { + @Test + void testBuildRequestCallerIdAsterisk12WithUnknownCallerId() { List lines; AgiRequest request; @@ -228,14 +226,14 @@ public void testBuildRequestCallerIdAsterisk12WithUnknownCallerId() request = new AgiRequestImpl(lines); - assertNull("callerId must not be set if \"unknown\"", request.getCallerId()); - assertNull("callerIdNumber must not be set if \"unknown\"", request.getCallerIdNumber()); - assertEquals("incorrect callerIdName", "John Doe", request.getCallerIdName()); + assertNull(request.getCallerId(), "callerId must not be set if \"unknown\""); + assertNull(request.getCallerIdNumber(), "callerIdNumber must not be set if \"unknown\""); + assertEquals("John Doe", request.getCallerIdName(), "incorrect callerIdName"); } @SuppressWarnings("deprecation") - public void testBuildRequestCallerIdAsterisk12WithUnknownCallerIdName() - { + @Test + void testBuildRequestCallerIdAsterisk12WithUnknownCallerIdName() { List lines; AgiRequest request; @@ -246,13 +244,13 @@ public void testBuildRequestCallerIdAsterisk12WithUnknownCallerIdName() request = new AgiRequestImpl(lines); - assertEquals("incorrect callerId", "1234", request.getCallerId()); - assertEquals("incorrect callerIdNumber", "1234", request.getCallerIdNumber()); - assertNull("callerIdName must not be set if \"unknown\"", request.getCallerIdName()); + assertEquals("1234", request.getCallerId(), "incorrect callerId"); + assertEquals("1234", request.getCallerIdNumber(), "incorrect callerIdNumber"); + assertNull(request.getCallerIdName(), "callerIdName must not be set if \"unknown\""); } - public void testBuildRequestCallerIdWithUnknownDnid() - { + @Test + void testBuildRequestCallerIdWithUnknownDnid() { List lines; AgiRequest request; @@ -262,11 +260,11 @@ public void testBuildRequestCallerIdWithUnknownDnid() request = new AgiRequestImpl(lines); - assertNull("dnid must not be set if \"unknown\"", request.getDnid()); + assertNull(request.getDnid(), "dnid must not be set if \"unknown\""); } - public void testBuildRequestCallerIdWithUnknownRdnis() - { + @Test + void testBuildRequestCallerIdWithUnknownRdnis() { List lines; AgiRequest request; @@ -276,23 +274,20 @@ public void testBuildRequestCallerIdWithUnknownRdnis() request = new AgiRequestImpl(lines); - assertNull("rdnis must not be set if \"unknown\"", request.getRdnis()); + assertNull(request.getRdnis(), "rdnis must not be set if \"unknown\""); } - public void testBuildRequestWithNullEnvironment() - { - try - { + @Test + void testBuildRequestWithNullEnvironment() { + try { new AgiRequestImpl(null); fail("No IllegalArgumentException thrown."); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { } } - public void testBuildRequestWithUnusualInput() - { + @Test + void testBuildRequestWithUnusualInput() { List lines; AgiRequest request; @@ -305,11 +300,11 @@ public void testBuildRequestWithUnusualInput() request = new AgiRequestImpl(lines); - assertEquals("incorrect channel", "SIP/1234-a892", request.getChannel()); + assertEquals("SIP/1234-a892", request.getChannel(), "incorrect channel"); } - public void testBuildRequestWithoutParameters() - { + @Test + void testBuildRequestWithoutParameters() { List lines; AgiRequest request; @@ -320,17 +315,17 @@ public void testBuildRequestWithoutParameters() request = new AgiRequestImpl(lines); - assertEquals("incorrect script", "myscript.agi", request.getScript()); - assertEquals("incorrect requestURL", "agi://host/myscript.agi", request.getRequestURL()); - assertEquals("incorrect value for unset parameter 'param1'", null, request.getParameter("param1")); - assertNotNull("getParameterValues() must not return null", request.getParameterValues("param1")); - assertEquals("incorrect size of values for unset parameter 'param1'", 0, request.getParameterValues("param1").length); - assertNotNull("getParameterMap() must not return null", request.getParameterMap()); - assertEquals("incorrect size of getParameterMap()", 0, request.getParameterMap().size()); + assertEquals("myscript.agi", request.getScript(), "incorrect script"); + assertEquals("agi://host/myscript.agi", request.getRequestURL(), "incorrect requestURL"); + assertEquals(null, request.getParameter("param1"), "incorrect value for unset parameter 'param1'"); + assertNotNull(request.getParameterValues("param1"), "getParameterValues() must not return null"); + assertEquals(0, request.getParameterValues("param1").length, "incorrect size of values for unset parameter 'param1'"); + assertNotNull(request.getParameterMap(), "getParameterMap() must not return null"); + assertEquals(0, request.getParameterMap().size(), "incorrect size of getParameterMap()"); } - public void testBuildRequestWithSingleValueParameters() - { + @Test + void testBuildRequestWithSingleValueParameters() { List lines; AgiRequest request; @@ -341,17 +336,17 @@ public void testBuildRequestWithSingleValueParameters() request = new AgiRequestImpl(lines); - assertEquals("incorrect script", "myscript.agi", request.getScript()); - assertEquals("incorrect requestURL", "agi://host/myscript.agi?param1=value1¶m2=value2", request.getRequestURL()); - assertEquals("incorrect value for parameter 'param1'", "value1", request.getParameter("param1")); - assertEquals("incorrect value for parameter 'param2'", "value2", request.getParameter("param2")); - assertEquals("incorrect value for unset parameter 'param3'", null, request.getParameter("param3")); - assertEquals("incorrect size of getParameterMap()", 2, request.getParameterMap().size()); - assertEquals("incorrect value for parameter 'param1' when obtained from map", "value1", ((String[]) request.getParameterMap().get("param1"))[0]); + assertEquals("myscript.agi", request.getScript(), "incorrect script"); + assertEquals("agi://host/myscript.agi?param1=value1¶m2=value2", request.getRequestURL(), "incorrect requestURL"); + assertEquals("value1", request.getParameter("param1"), "incorrect value for parameter 'param1'"); + assertEquals("value2", request.getParameter("param2"), "incorrect value for parameter 'param2'"); + assertEquals(null, request.getParameter("param3"), "incorrect value for unset parameter 'param3'"); + assertEquals(2, request.getParameterMap().size(), "incorrect size of getParameterMap()"); + assertEquals("value1", request.getParameterMap().get("param1")[0], "incorrect value for parameter 'param1' when obtained from map"); } - public void testBuildRequestWithMultiValueParameter() - { + @Test + void testBuildRequestWithMultiValueParameter() { List lines; AgiRequest request; @@ -362,16 +357,15 @@ public void testBuildRequestWithMultiValueParameter() request = new AgiRequestImpl(lines); - assertEquals("incorrect script", "myscript.agi", request.getScript()); - assertEquals("incorrect requestURL", - "agi://host/myscript.agi?param1=value1¶m1=value2", request.getRequestURL()); - assertEquals("incorrect number of values for parameter 'param1'", 2, request.getParameterValues("param1").length); - assertEquals("incorrect value[0] for parameter 'param1'", "value1", request.getParameterValues("param1")[0]); - assertEquals("incorrect value[1] for parameter 'param1'", "value2", request.getParameterValues("param1")[1]); + assertEquals("myscript.agi", request.getScript(), "incorrect script"); + assertEquals("agi://host/myscript.agi?param1=value1¶m1=value2", request.getRequestURL(), "incorrect requestURL"); + assertEquals(2, request.getParameterValues("param1").length, "incorrect number of values for parameter 'param1'"); + assertEquals("value1", request.getParameterValues("param1")[0], "incorrect value[0] for parameter 'param1'"); + assertEquals("value2", request.getParameterValues("param1")[1], "incorrect value[1] for parameter 'param1'"); } - public void testBuildRequestWithEmptyValueParameter() - { + @Test + void testBuildRequestWithEmptyValueParameter() { List lines; AgiRequest request; @@ -382,15 +376,15 @@ public void testBuildRequestWithEmptyValueParameter() request = new AgiRequestImpl(lines); - assertEquals("incorrect script", "myscript.agi", request.getScript()); - assertEquals("incorrect requestURL", "agi://host/myscript.agi?param1", request.getRequestURL()); - assertEquals("incorrect value for parameter 'param1'", "", request.getParameter("param1")); - assertEquals("incorrect number of values for parameter 'param1'", 1, request.getParameterValues("param1").length); - assertEquals("incorrect value[0] for parameter 'param1'", "", request.getParameterValues("param1")[0]); + assertEquals("myscript.agi", request.getScript(), "incorrect script"); + assertEquals("agi://host/myscript.agi?param1", request.getRequestURL(), "incorrect requestURL"); + assertEquals("", request.getParameter("param1"), "incorrect value for parameter 'param1'"); + assertEquals(1, request.getParameterValues("param1").length, "incorrect number of values for parameter 'param1'"); + assertEquals("", request.getParameterValues("param1")[0], "incorrect value[0] for parameter 'param1'"); } - public void testBuildRequestWithUrlEncodedParameter() - { + @Test + void testBuildRequestWithUrlEncodedParameter() { List lines; AgiRequest request; @@ -401,13 +395,13 @@ public void testBuildRequestWithUrlEncodedParameter() request = new AgiRequestImpl(lines); - assertEquals("incorrect script", "myscript.agi", request.getScript()); - assertEquals("incorrect requestURL", "agi://host/myscript.agi?param1=my%20value", request.getRequestURL()); - assertEquals("incorrect value for parameter 'param1'", "my value", request.getParameter("param1")); + assertEquals("myscript.agi", request.getScript(), "incorrect script"); + assertEquals("agi://host/myscript.agi?param1=my%20value", request.getRequestURL(), "incorrect requestURL"); + assertEquals("my value", request.getParameter("param1"), "incorrect value for parameter 'param1'"); } - public void testGetParameter() - { + @Test + void testGetParameter() { List lines; AgiRequest request; @@ -418,12 +412,12 @@ public void testGetParameter() request = new AgiRequestImpl(lines); - assertEquals("incorrect requestURL", "agi://host/myscript.agi?param1=my%20value", request.getRequestURL()); - assertEquals("incorrect value for parameter 'param1'", "my value", request.getParameter("param1")); + assertEquals("agi://host/myscript.agi?param1=my%20value", request.getRequestURL(), "incorrect requestURL"); + assertEquals("my value", request.getParameter("param1"), "incorrect value for parameter 'param1'"); } - public void testGetArguments() - { + @Test + void testGetArguments() { List lines; AgiRequest request; @@ -436,14 +430,14 @@ public void testGetArguments() request = new AgiRequestImpl(lines); - assertEquals("incorrect requestURL", "agi://host/myscript.agi", request.getRequestURL()); - assertEquals("invalid number of arguments", 2, request.getArguments().length); - assertEquals("incorrect value for first argument", "value1", request.getArguments()[0]); - assertEquals("incorrect value for second argument", "value2", request.getArguments()[1]); + assertEquals("agi://host/myscript.agi", request.getRequestURL(), "incorrect requestURL"); + assertEquals(2, request.getArguments().length, "invalid number of arguments"); + assertEquals("value1", request.getArguments()[0], "incorrect value for first argument"); + assertEquals("value2", request.getArguments()[1], "incorrect value for second argument"); } - public void testGetArgumentsWithEmptyArgument() - { + @Test + void testGetArgumentsWithEmptyArgument() { List lines; AgiRequest request; @@ -457,15 +451,15 @@ public void testGetArgumentsWithEmptyArgument() request = new AgiRequestImpl(lines); - assertEquals("incorrect requestURL", "agi://host/myscript.agi", request.getRequestURL()); - assertEquals("invalid number of arguments", 3, request.getArguments().length); - assertEquals("incorrect value for first argument", "value1", request.getArguments()[0]); - assertEquals("incorrect value for second argument", null, request.getArguments()[1]); - assertEquals("incorrect value for third argument", "value3", request.getArguments()[2]); + assertEquals("agi://host/myscript.agi", request.getRequestURL(), "incorrect requestURL"); + assertEquals(3, request.getArguments().length, "invalid number of arguments"); + assertEquals("value1", request.getArguments()[0], "incorrect value for first argument"); + assertEquals(null, request.getArguments()[1], "incorrect value for second argument"); + assertEquals("value3", request.getArguments()[2], "incorrect value for third argument"); } - public void testGetArgumentsWithNoArgumentsPassed() - { + @Test + void testGetArgumentsWithNoArgumentsPassed() { List lines; AgiRequest request; @@ -476,8 +470,8 @@ public void testGetArgumentsWithNoArgumentsPassed() request = new AgiRequestImpl(lines); - assertEquals("incorrect requestURL", "agi://host/myscript.agi", request.getRequestURL()); - assertNotNull("getArguments() must never return null", request.getArguments()); - assertEquals("invalid number of arguments", 0, request.getArguments().length); + assertEquals("agi://host/myscript.agi", request.getRequestURL(), "incorrect requestURL"); + assertNotNull(request.getArguments(), "getArguments() must never return null"); + assertEquals(0, request.getArguments().length, "invalid number of arguments"); } } diff --git a/src/test/java/org/asteriskjava/fastagi/internal/AgiWriterImplTest.java b/src/test/java/org/asteriskjava/fastagi/internal/AgiWriterImplTest.java index 97c1ca25d..d6188bbac 100644 --- a/src/test/java/org/asteriskjava/fastagi/internal/AgiWriterImplTest.java +++ b/src/test/java/org/asteriskjava/fastagi/internal/AgiWriterImplTest.java @@ -16,39 +16,34 @@ */ package org.asteriskjava.fastagi.internal; -import junit.framework.TestCase; -import static org.easymock.EasyMock.*; - +import org.asteriskjava.fastagi.AgiWriter; import org.asteriskjava.fastagi.command.StreamFileCommand; -import org.asteriskjava.fastagi.internal.FastAgiWriter; import org.asteriskjava.util.SocketConnectionFacade; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; -public class AgiWriterImplTest extends TestCase -{ +class AgiWriterImplTest { private AgiWriter agiWriter; private SocketConnectionFacade socket; - @Override - protected void setUp() throws Exception - { - super.setUp(); - this.socket = createMock(SocketConnectionFacade.class); + @BeforeEach + void setUp() { + this.socket = mock(SocketConnectionFacade.class); this.agiWriter = new FastAgiWriter(socket); } - public void testSendCommand() throws Exception - { + @Test + void testSendCommand() throws Exception { StreamFileCommand command; - + command = new StreamFileCommand("welcome"); - - socket.write("STREAM FILE \"welcome\" \"\"\n"); - socket.flush(); - - replay(socket); - + agiWriter.sendCommand(command); - - verify(socket); + + verify(socket).write("STREAM FILE \"welcome\" \"\"\n"); + verify(socket).flush(); } } diff --git a/src/test/java/org/asteriskjava/live/CallerIdTest.java b/src/test/java/org/asteriskjava/live/CallerIdTest.java index e189ffa80..8c3ba17de 100644 --- a/src/test/java/org/asteriskjava/live/CallerIdTest.java +++ b/src/test/java/org/asteriskjava/live/CallerIdTest.java @@ -1,14 +1,15 @@ package org.asteriskjava.live; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; -public class CallerIdTest extends TestCase -{ - public void testEquals() - { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CallerIdTest { + @Test + void testEquals() { CallerId callerId1; CallerId callerId2; - + callerId1 = new CallerId("Hans Wurst", "1234"); callerId2 = new CallerId("Hans Wurst", "1234"); assertEquals(callerId1, callerId2); @@ -20,22 +21,22 @@ public void testEquals() callerId1 = new CallerId(null, "1234"); callerId2 = new CallerId(null, "1234"); assertEquals(callerId1, callerId2); - + callerId1 = new CallerId(null, null); callerId2 = new CallerId(null, null); assertEquals(callerId1, callerId2); } - public void testValueOf() - { + @Test + void testValueOf() { CallerId callerId = new CallerId("Hans Wurst", "1234"); assertEquals(callerId, CallerId.valueOf("\"Hans Wurst\" <1234>")); assertEquals(callerId, CallerId.valueOf("Hans Wurst <1234>")); assertEquals(callerId, CallerId.valueOf(callerId.toString())); } - public void testValueOfWithNullLiteralInName() - { + @Test + void testValueOfWithNullLiteralInName() { CallerId callerId = new CallerId(null, "1234"); assertEquals(callerId, CallerId.valueOf("\"\" <1234>")); assertEquals(callerId, CallerId.valueOf("\"\" <1234>")); @@ -43,32 +44,34 @@ public void testValueOfWithNullLiteralInName() assertEquals(callerId, CallerId.valueOf(callerId.toString())); } - public void testValueOfWithNullLiteralInNumber() - { + @Test + void testValueOfWithNullLiteralInNumber() { CallerId callerId = new CallerId("Hans Wurst", null); assertEquals(callerId, CallerId.valueOf("\"Hans Wurst\" <>")); - //assertEquals(callerId, CallerId.valueOf("\"Hans Wurst\" <>")); - //assertEquals(callerId, CallerId.valueOf("Hans Wurst <>")); + // assertEquals(callerId, + // CallerId.valueOf("\"Hans Wurst\" <>")); + // assertEquals(callerId, CallerId.valueOf("Hans Wurst <>")); } - public void testValueOfWithNullLiteralInNameAndNumber() - { + @Test + void testValueOfWithNullLiteralInNameAndNumber() { CallerId callerId = new CallerId(null, null); assertEquals(callerId, CallerId.valueOf("\"\" <>")); - //assertEquals(callerId, CallerId.valueOf("<>")); - //assertEquals(callerId, CallerId.valueOf("\"\" <>")); - //assertEquals(callerId, CallerId.valueOf(" <>")); + // assertEquals(callerId, CallerId.valueOf("<>")); + // assertEquals(callerId, + // CallerId.valueOf("\"\" <>")); + // assertEquals(callerId, CallerId.valueOf(" <>")); assertEquals(callerId, CallerId.valueOf("")); - //assertEquals(callerId, CallerId.valueOf("\"\"")); + // assertEquals(callerId, CallerId.valueOf("\"\"")); } - public void testConstructorWithNullLiteral() - { + @Test + void testConstructorWithNullLiteral() { assertEquals(new CallerId(null, "1234"), new CallerId("", "1234")); } - public void testToString() - { + @Test + void testToString() { assertEquals("\"Hans Wurst\" <1234>", new CallerId("Hans Wurst", "1234").toString()); assertEquals("<1234>", new CallerId(null, "1234").toString()); assertEquals("\"Hans Wurst\"", new CallerId("Hans Wurst", null).toString()); diff --git a/src/test/java/org/asteriskjava/live/HangupCauseTest.java b/src/test/java/org/asteriskjava/live/HangupCauseTest.java index 5db65b39f..49e1b633f 100644 --- a/src/test/java/org/asteriskjava/live/HangupCauseTest.java +++ b/src/test/java/org/asteriskjava/live/HangupCauseTest.java @@ -1,11 +1,12 @@ package org.asteriskjava.live; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; -public class HangupCauseTest extends TestCase -{ - public void testGetByCode() - { - assertEquals("Valid enum for cause code 18", HangupCause.AST_CAUSE_NO_USER_RESPONSE, HangupCause.getByCode(18)); +import static org.junit.jupiter.api.Assertions.assertEquals; + +class HangupCauseTest { + @Test + void testGetByCode() { + assertEquals(HangupCause.AST_CAUSE_NO_USER_RESPONSE, HangupCause.getByCode(18), "Valid enum for cause code 18"); } } diff --git a/src/test/java/org/asteriskjava/live/QueueMemberStateTest.java b/src/test/java/org/asteriskjava/live/QueueMemberStateTest.java index 63c8e8d4a..537714c4a 100644 --- a/src/test/java/org/asteriskjava/live/QueueMemberStateTest.java +++ b/src/test/java/org/asteriskjava/live/QueueMemberStateTest.java @@ -1,17 +1,18 @@ package org.asteriskjava.live; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; -public class QueueMemberStateTest extends TestCase -{ - public void testValueOf() - { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class QueueMemberStateTest { + @Test + void testValueOf() { assertEquals(QueueMemberState.DEVICE_INUSE, QueueMemberState.valueOf("DEVICE_INUSE")); assertEquals(QueueMemberState.DEVICE_INUSE, QueueMemberState.valueOf(2)); } - public void testToString() - { + @Test + void testToString() { assertEquals("DEVICE_INUSE", QueueMemberState.DEVICE_INUSE.toString()); } } diff --git a/src/test/java/org/asteriskjava/live/internal/AsteriskAgentImplTest.java b/src/test/java/org/asteriskjava/live/internal/AsteriskAgentImplTest.java index fedca0738..6b27c8887 100644 --- a/src/test/java/org/asteriskjava/live/internal/AsteriskAgentImplTest.java +++ b/src/test/java/org/asteriskjava/live/internal/AsteriskAgentImplTest.java @@ -1,6 +1,6 @@ /* * This code is property of GONICUS GmbH - * + * * (c) 2007 * * SVN-Information @@ -17,65 +17,45 @@ */ package org.asteriskjava.live.internal; -import static org.junit.Assert.assertEquals; +import org.asteriskjava.live.AgentState; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; -import org.asteriskjava.live.AgentState; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** - * @author Patrick - * Breucking - * @since 0.1 + * @author Patrick Breucking * @version $Id$ - * + * @since 0.1 */ -public class AsteriskAgentImplTest -{ - +class AsteriskAgentImplTest { private AsteriskAgentImpl agent; private int numberOfChanges; - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception - { - AsteriskServerImpl server = new AsteriskServerImpl(); - agent = new AsteriskAgentImpl(server, "Testagent", "Agent/999", - AgentState.AGENT_IDLE); - numberOfChanges = 0; + @BeforeEach + void setUp() { + AsteriskServerImpl server = new AsteriskServerImpl(); + agent = new AsteriskAgentImpl(server, "Testagent", "Agent/999", AgentState.AGENT_IDLE); + numberOfChanges = 0; } - /** - * Test method for - * {@link org.asteriskjava.live.internal.AsteriskAgentImpl#updateState(org.asteriskjava.live.AgentState)}. - */ @Test - public void testUpdateStatus() - { - assertEquals(AgentState.AGENT_IDLE, agent.getState()); - agent.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent evt) - { - assertEquals("wrong propertyName", "state", evt - .getPropertyName()); - assertEquals("wrong oldValue", AgentState.AGENT_IDLE, evt - .getOldValue()); - assertEquals("wrong newValue", AgentState.AGENT_RINGING, evt - .getNewValue()); - assertEquals("wrong queue", agent, evt.getSource()); - numberOfChanges++; - } - - }); - agent.updateState(AgentState.AGENT_RINGING); - assertEquals("wrong number of propagated changes", 1, numberOfChanges); + void testUpdateStatus() { + assertEquals(AgentState.AGENT_IDLE, agent.getState()); + agent.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent evt) { + assertEquals("state", evt.getPropertyName(), "wrong propertyName"); + assertEquals(AgentState.AGENT_IDLE, evt.getOldValue(), "wrong oldValue"); + assertEquals(AgentState.AGENT_RINGING, evt.getNewValue(), "wrong newValue"); + assertEquals(agent, evt.getSource(), "wrong queue"); + numberOfChanges++; + } + + }); + agent.updateState(AgentState.AGENT_RINGING); + assertEquals(1, numberOfChanges, "wrong number of propagated changes"); } - } diff --git a/src/test/java/org/asteriskjava/live/internal/AsteriskChannelImplTest.java b/src/test/java/org/asteriskjava/live/internal/AsteriskChannelImplTest.java index 96398d9a0..897f312b6 100644 --- a/src/test/java/org/asteriskjava/live/internal/AsteriskChannelImplTest.java +++ b/src/test/java/org/asteriskjava/live/internal/AsteriskChannelImplTest.java @@ -1,42 +1,40 @@ package org.asteriskjava.live.internal; +import org.asteriskjava.live.ChannelState; +import org.asteriskjava.util.DateUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; -import junit.framework.TestCase; - -import org.asteriskjava.live.ChannelState; -import org.asteriskjava.util.DateUtil; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AsteriskChannelImplTest extends TestCase -{ +class AsteriskChannelImplTest { private AsteriskChannelImpl channel; private int numberOfChanges; - @Override - public void setUp() - { + @BeforeEach + void setUp() { AsteriskServerImpl server = new AsteriskServerImpl(); channel = new AsteriskChannelImpl(server, "SIP/1234", "0123456789.123", DateUtil.getDate()); channel.stateChanged(DateUtil.getDate(), ChannelState.DOWN); numberOfChanges = 0; } - public void testStateChange() - { - channel.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent evt) - { - assertEquals("wrong propertyName", "state", evt.getPropertyName()); - assertEquals("wrong oldValue", ChannelState.DOWN, evt.getOldValue()); - assertEquals("wrong newValue", ChannelState.DIALING, evt.getNewValue()); - assertEquals("wrong source", channel, evt.getSource()); + @Test + void testStateChange() { + channel.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent evt) { + assertEquals("state", evt.getPropertyName(), "wrong propertyName"); + assertEquals(ChannelState.DOWN, evt.getOldValue(), "wrong oldValue"); + assertEquals(ChannelState.DIALING, evt.getNewValue(), "wrong newValue"); + assertEquals(channel, evt.getSource(), "wrong source"); numberOfChanges++; } }); channel.stateChanged(DateUtil.getDate(), ChannelState.DIALING); - assertEquals("wrong number of propagated changes", 1, numberOfChanges); + assertEquals(1, numberOfChanges, "wrong number of propagated changes"); } } diff --git a/src/test/java/org/asteriskjava/live/internal/AsteriskQueueMemberImplTest.java b/src/test/java/org/asteriskjava/live/internal/AsteriskQueueMemberImplTest.java index 816cc63e9..0550ac5a5 100644 --- a/src/test/java/org/asteriskjava/live/internal/AsteriskQueueMemberImplTest.java +++ b/src/test/java/org/asteriskjava/live/internal/AsteriskQueueMemberImplTest.java @@ -16,49 +16,46 @@ */ package org.asteriskjava.live.internal; +import org.asteriskjava.live.QueueMemberState; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; -import junit.framework.TestCase; - -import org.asteriskjava.live.QueueMemberState; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** - * @author Patrick Breucking + * @author Patrick Breucking * @version $Id$ * @since 0.1 */ -public class AsteriskQueueMemberImplTest extends TestCase -{ +class AsteriskQueueMemberImplTest { private AsteriskQueueMemberImpl queueMember; private int numberOfChanges; private AsteriskServerImpl server; - //private QueueManager qManager; + // private QueueManager qManager; private AsteriskQueueImpl queue; - @Override - @Before - public void setUp() throws Exception - { + @BeforeEach + void setUp() { server = new AsteriskServerImpl(); // ChannelManager channelManager = new ChannelManager(server); // qManager = new QueueManager(server, channelManager); - queue = new AsteriskQueueImpl(server, "test", 25, "RoundRobin", 15, 5); - queueMember = new AsteriskQueueMemberImpl(server, queue, "Agent/777", - QueueMemberState.DEVICE_UNKNOWN, false, 10, "dynamic"); + queue = new AsteriskQueueImpl(server, "test", 25, "RoundRobin", 15, 5, + 0, 0, 1, 1, 1, 1.0); + queueMember = new AsteriskQueueMemberImpl(server, queue, "Agent/777", QueueMemberState.DEVICE_UNKNOWN, false, 10, + "dynamic", 3, 6000l); numberOfChanges = 0; } @Test - public void testQueueMemberEvents() throws Exception - { + void testQueueMemberEvents() { /* - * Test should generate a new member like queueMember = new - */ + * Test should generate a new member like queueMember = new + */ // queueMember = new AsteriskQueueMemberImpl(server, queue, "Agent/777", // QueueMemberState.DEVICE_UNKNOWN); // QueueParamsEvent qpe = new QueueParamsEvent(new Object()); @@ -80,17 +77,12 @@ public void testQueueMemberEvents() throws Exception // AsteriskQueueMember member = members.iterator().next(); // assertEquals("Agent/777", member.getLocation()); assertEquals(QueueMemberState.DEVICE_UNKNOWN, queueMember.getState()); - queueMember.addPropertyChangeListener(new PropertyChangeListener() - { - public void propertyChange(PropertyChangeEvent evt) - { - assertEquals("wrong propertyName", "state", evt - .getPropertyName()); - assertEquals("wrong oldValue", QueueMemberState.DEVICE_UNKNOWN, - evt.getOldValue()); - assertEquals("wrong newValue", QueueMemberState.DEVICE_BUSY, - evt.getNewValue()); - assertEquals("wrong queue member", queueMember, evt.getSource()); + queueMember.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent evt) { + assertEquals("state", evt.getPropertyName(), "wrong propertyName"); + assertEquals(QueueMemberState.DEVICE_UNKNOWN, evt.getOldValue(), "wrong oldValue"); + assertEquals(QueueMemberState.DEVICE_BUSY, evt.getNewValue(), "wrong newValue"); + assertEquals(queueMember, evt.getSource(), "wrong queue member"); numberOfChanges++; } @@ -99,13 +91,13 @@ public void propertyChange(PropertyChangeEvent evt) // queue.addAsteriskQueueListener(new AsteriskQueueListener() // { // - // public void onEntryLeave(AsteriskChannel channel) + // void onEntryLeave(AsteriskChannel channel) // { // // TODO Auto-generated method stub // // } // - // public void onMemberStateChange(AsteriskQueueMember member) + // void onMemberStateChange(AsteriskQueueMember member) // { // assertEquals("wrong newValue", QueueMemberState.DEVICE_BUSY, // member.getState()); @@ -115,7 +107,7 @@ public void propertyChange(PropertyChangeEvent evt) // // } // - // public void onNewEntry(AsteriskChannel channel) + // void onNewEntry(AsteriskChannel channel) // { // // TODO Auto-generated method stub // @@ -129,6 +121,6 @@ public void propertyChange(PropertyChangeEvent evt) // qmse.setStatus(3); // server.onManagerEvent(qmse); queueMember.stateChanged(QueueMemberState.DEVICE_BUSY); - assertEquals("wrong number of propagated changes", 1, numberOfChanges); + assertEquals(1, numberOfChanges, "wrong number of propagated changes"); } } diff --git a/src/test/java/org/asteriskjava/lock/LockerTest.java b/src/test/java/org/asteriskjava/lock/LockerTest.java new file mode 100644 index 000000000..c69b03036 --- /dev/null +++ b/src/test/java/org/asteriskjava/lock/LockerTest.java @@ -0,0 +1,117 @@ +package org.asteriskjava.lock; + +import org.asteriskjava.lock.Locker.LockCloser; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.TimeUnit; + +class LockerTest { + + private final Lockable sync = new Lockable(); + + @Test + void test1() { + Locker.disable(); + int seconds = 2; + + int a = 0; + long start = System.currentTimeMillis(); + while (System.currentTimeMillis() - start < seconds * 1000) { + try (LockCloser closer = sync.withLock()) { + a++; + } + } + System.out.println(a / seconds + " Locker per second"); + + Locker.enable(); + a = 0; + start = System.currentTimeMillis(); + while (System.currentTimeMillis() - start < seconds * 1000) { + try (LockCloser closer = sync.withLock()) { + a++; + } + } + System.out.println(a / seconds + " Locker With Diags per second"); + + a = 0; + start = System.currentTimeMillis(); + while (System.currentTimeMillis() - start < seconds * 1000) { + synchronized (sync) { + a++; + } + } + System.out.println(a / seconds + " Synchronized per second"); + + } + + volatile boolean stop = false; + int concurrentCounter1 = 0; + int concurrentCounter2 = 0; + int concurrentCounter3 = 0; + + @Test + void testConcurrency() throws InterruptedException { + Lockable s1 = new Lockable(); + Lockable s2 = new Lockable(); + Lockable s3 = new Lockable(); + + int seconds = 2; + + Locker.enable(); + stop = false; + Runnable runable2 = () -> { + while (!stop) { + try (LockCloser closer = s1.withLock()) { + concurrentCounter2++; + } + } + }; + + new Thread(runable2).start(); + new Thread(runable2).start(); + TimeUnit.SECONDS.sleep(seconds); + stop = true; + TimeUnit.SECONDS.sleep(1); + System.out.println(concurrentCounter2 / seconds + " Locker per second with 2 threads and diags"); + + Locker.disable(); + stop = false; + + Runnable runable = () -> { + while (!stop) { + try (LockCloser closer = s2.withLock()) { + concurrentCounter1++; + } + } + }; + new Thread(runable).start(); + new Thread(runable).start(); + TimeUnit.SECONDS.sleep(seconds); + stop = true; + TimeUnit.SECONDS.sleep(1); + System.out.println(concurrentCounter1 / seconds + " Locker per second with 2 threads"); + + Locker.dumpStats(); + stop = false; + + Runnable runable3 = () -> { + while (!stop) { + synchronized (s3) { + concurrentCounter3++; + } + } + }; + new Thread(runable3).start(); + new Thread(runable3).start(); + TimeUnit.SECONDS.sleep(seconds); + stop = true; + TimeUnit.SECONDS.sleep(1); + System.out.println(concurrentCounter3 / seconds + " synchronized per second with 2 threads"); + + System.out.println("\nIt seems wrong that 2 threads with diags is faster,\n" + + "but the reality is that with the added overhead of diags there is less lock contention so it runs faster.\n" + + "If more threads are added the two tests produce near identicaly through put as contention is high for both cases then.\n"); + + } + +} diff --git a/src/test/java/org/asteriskjava/manager/AbstractManagerEventListenerTest.java b/src/test/java/org/asteriskjava/manager/AbstractManagerEventListenerTest.java new file mode 100644 index 000000000..2a86c1072 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/AbstractManagerEventListenerTest.java @@ -0,0 +1,49 @@ +package org.asteriskjava.manager; + +import org.asteriskjava.manager.event.JoinEvent; +import org.asteriskjava.manager.event.LeaveEvent; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AbstractManagerEventListenerTest { + + @Test + void shouldHandleJoinEvent() { + //given + EventListener listener = new EventListener(); + + //when + listener.onManagerEvent(new JoinEvent(this)); + + //then + assertTrue(listener.joinEventHandled); + } + + @Test + void shouldHandleLeaveEvent() { + //given + EventListener listener = new EventListener(); + + //when + listener.onManagerEvent(new LeaveEvent(this)); + + //then + assertTrue(listener.leaveEventHandled); + } + + private static class EventListener extends AbstractManagerEventListener { + public boolean joinEventHandled; + public boolean leaveEventHandled; + + @Override + public void handleEvent(JoinEvent event) { + this.joinEventHandled = true; + } + + @Override + public void handleEvent(LeaveEvent event) { + this.leaveEventHandled = true; + } + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/AgentConnectEventTest.java b/src/test/java/org/asteriskjava/manager/event/AgentConnectEventTest.java new file mode 100644 index 000000000..16cab6772 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/AgentConnectEventTest.java @@ -0,0 +1,85 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class AgentConnectEventTest { + @Test + void shouldCreateEvent() { + //given + AgentConnectEvent agentConnectEvent = new AgentConnectEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("destexten", "600"); + attributes.put("destaccountcode", "441142993721"); + attributes.put("destchannelstatedesc", "Up"); + attributes.put("channelstate", "4"); + attributes.put("destuniqueid", ""); + attributes.put("calleridname", ""); + attributes.put("destconnectedlinename", ""); + attributes.put("destcalleridname", "202"); + attributes.put("priority", "4"); + attributes.put("destcalleridnum", "202"); + attributes.put("exten", "600"); + attributes.put("accountcode", ""); + attributes.put("connectedlinenum", "202"); + attributes.put("calleridnum", "07800656909"); + attributes.put("destpriority", "1"); + attributes.put("destcontext", ""); + attributes.put("channelstatedesc", "Ring"); + attributes.put("destchannel", ""); + attributes.put("connectedlinename", "202"); + attributes.put("destchannelstate", "6"); + attributes.put("destconnectedlinenum", ""); + attributes.put("interface", ""); + attributes.put("context", ""); + + //when + setAttributes(agentConnectEvent, attributes, new HashSet<>()); + + //then + assertThat(agentConnectEvent.getDestExten()).isEqualTo("600"); + assertThat(agentConnectEvent.getDestAccountCode()).isEqualTo("441142993721"); + assertThat(agentConnectEvent.getDestChannelStateDesc()).isEqualTo("Up"); + assertThat(agentConnectEvent.getChannelState()).isEqualTo(4); + assertThat(agentConnectEvent.getDestUniqueId()).isEqualTo(""); + assertThat(agentConnectEvent.getCallerIdName()).isEqualTo(""); + assertThat(agentConnectEvent.getDestConnectedLineName()).isEqualTo(""); + assertThat(agentConnectEvent.getDestCallerIdName()).isEqualTo("202"); + assertThat(agentConnectEvent.getPriority()).isEqualTo(4); + assertThat(agentConnectEvent.getDestCallerIdNum()).isEqualTo("202"); + assertThat(agentConnectEvent.getExten()).isEqualTo("600"); + assertThat(agentConnectEvent.getAccountcode()).isEqualTo(""); + assertThat(agentConnectEvent.getConnectedLineNum()).isEqualTo("202"); + assertThat(agentConnectEvent.getCallerIdNum()).isEqualTo("07800656909"); + assertThat(agentConnectEvent.getDestPriority()).isEqualTo("1"); + assertThat(agentConnectEvent.getDestContext()).isEqualTo(""); + assertThat(agentConnectEvent.getChannelStateDesc()).isEqualTo("Ring"); + assertThat(agentConnectEvent.getDestChannel()).isEqualTo(""); + assertThat(agentConnectEvent.getConnectedLineName()).isEqualTo("202"); + assertThat(agentConnectEvent.getDestChannelState()).isEqualTo("6"); + assertThat(agentConnectEvent.getDestConnectedLineNum()).isEqualTo(""); + assertThat(agentConnectEvent.getInterface()).isEqualTo(""); + assertThat(agentConnectEvent.getContext()).isEqualTo(""); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/AgiExecStartEventTest.java b/src/test/java/org/asteriskjava/manager/event/AgiExecStartEventTest.java new file mode 100644 index 000000000..53861dff8 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/AgiExecStartEventTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class AgiExecStartEventTest { + @Test + void shouldCreateEvent() { + //given + AgiExecStartEvent agiExecStartEvent = new AgiExecStartEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("linkedid", "1617757665.32"); + attributes.put("language", "en"); + + //when + setAttributes(agiExecStartEvent, attributes, new HashSet<>()); + + //then + assertThat(agiExecStartEvent.getLinkedid()).isEqualTo("1617757665.32"); + assertThat(agiExecStartEvent.getLanguage()).isEqualTo("en"); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/AsyncAgiEventTest.java b/src/test/java/org/asteriskjava/manager/event/AsyncAgiEventTest.java index 567bdcdd0..5a2fa9c0c 100644 --- a/src/test/java/org/asteriskjava/manager/event/AsyncAgiEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/AsyncAgiEventTest.java @@ -1,13 +1,14 @@ package org.asteriskjava.manager.event; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; import java.util.List; -public class AsyncAgiEventTest extends TestCase -{ - public void testDecodeEnv() - { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class AsyncAgiEventTest { + @Test + void testDecodeEnv() { AsyncAgiEvent event = new AsyncAgiEvent(this); List env; @@ -37,8 +38,8 @@ public void testDecodeEnv() assertEquals("agi_threadid: -1231783024", env.get(19)); } - public void testDecodeEnvWithMoreThanTwoDelimiters() - { + @Test + void testDecodeEnvWithMoreThanTwoDelimiters() { AsyncAgiEvent event = new AsyncAgiEvent(this); List env; diff --git a/src/test/java/org/asteriskjava/manager/event/AttendedTransferEventTest.java b/src/test/java/org/asteriskjava/manager/event/AttendedTransferEventTest.java new file mode 100644 index 000000000..c8c333418 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/AttendedTransferEventTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class AttendedTransferEventTest { + @Test + void shouldCreateEvent() { + //given + AttendedTransferEvent attendedTransferEvent = new AttendedTransferEvent(new Object()); + + Map attributes = new HashMap<>(); + attributes.put("transfertargetcalleridname", ""); + attributes.put("secondbridgevideosourcemode", "none"); + attributes.put("transfertargetlinkedid", "1668752056.12"); + attributes.put("transfertargetpriority", "1"); + attributes.put("transfertargetcalleridnum", "102"); + attributes.put("origbridgevideosourcemode", "none"); + attributes.put("transfertargetconnectedlinenum", "103"); + attributes.put("transfertargetchannel", "SIP/102-0000000d"); + attributes.put("transfertargetcontext", "phones"); + attributes.put("transfertargetconnectedlinename", "J.Doe"); + attributes.put("transfertargetexten", ""); + attributes.put("transfertargetchannelstate", "6"); + attributes.put("transfertargetlanguage", "en"); + attributes.put("transfertargetaccountcode", ""); + attributes.put("transfertargetchannelstatedesc", "Up"); + + //when + setAttributes(attendedTransferEvent, attributes, new HashSet<>()); + + //then + assertThat(attendedTransferEvent.getTransferTargetCallerIDName()).isNull(); + assertThat(attendedTransferEvent.getSecondBridgeVideoSourceMode()).isNull(); + assertThat(attendedTransferEvent.getTransferTargetLinkedID()).isEqualTo("1668752056.12"); + assertThat(attendedTransferEvent.getTransferTargetPriority()).isEqualTo("1"); + assertThat(attendedTransferEvent.getTransferTargetCallerIDNum()).isEqualTo("102"); + assertThat(attendedTransferEvent.getOrigBridgeVideoSourceMode()).isNull(); + assertThat(attendedTransferEvent.getTransferTargetConnectedLineNum()).isEqualTo("103"); + assertThat(attendedTransferEvent.getTransferTargetChannel()).isEqualTo("SIP/102-0000000d"); + assertThat(attendedTransferEvent.getTransferTargetContext()).isEqualTo("phones"); + assertThat(attendedTransferEvent.getTransferTargetConnectedLineName()).isEqualTo("J.Doe"); + assertThat(attendedTransferEvent.getTransferTargetExten()).isBlank(); + assertThat(attendedTransferEvent.getTransferTargetChannelState()).isEqualTo("6"); + assertThat(attendedTransferEvent.getTransferTargetLanguage()).isEqualTo("en"); + assertThat(attendedTransferEvent.getTransferTargetAccountCode()).isBlank(); + assertThat(attendedTransferEvent.getTransferTargetChannelStateDesc()).isEqualTo("Up"); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/BridgeCreateEventTest.java b/src/test/java/org/asteriskjava/manager/event/BridgeCreateEventTest.java new file mode 100644 index 000000000..4921541f3 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/BridgeCreateEventTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class BridgeCreateEventTest { + @Test + void shouldCreateEvent() { + //given + BridgeCreateEvent bridgeCreateEvent = new BridgeCreateEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("bridgevideosourcemode", "none"); + + //when + setAttributes(bridgeCreateEvent, attributes, new HashSet<>()); + + //then + assertThat(bridgeCreateEvent.getBridgevideosourcemode()).isNull(); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/BridgeEnterEventTest.java b/src/test/java/org/asteriskjava/manager/event/BridgeEnterEventTest.java new file mode 100644 index 000000000..75634cdc3 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/BridgeEnterEventTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class BridgeEnterEventTest { + @Test + void shouldCreateEvent() { + //given + BridgeEnterEvent bridgeEnterEvent = new BridgeEnterEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("swapuniqueid", "GW1-1517402850.50086"); + + //when + setAttributes(bridgeEnterEvent, attributes, new HashSet<>()); + + //then + assertThat(bridgeEnterEvent.getSwapuniqueid()).isEqualTo("GW1-1517402850.50086"); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/BridgeVideoSourceUpdateEventTest.java b/src/test/java/org/asteriskjava/manager/event/BridgeVideoSourceUpdateEventTest.java new file mode 100644 index 000000000..4331041a7 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/BridgeVideoSourceUpdateEventTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2023 Hector Espert + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class BridgeVideoSourceUpdateEventTest { + + @Test + void shouldCreateEvent() { + BridgeVideoSourceUpdateEvent bridgeVideoSourceUpdateEvent = new BridgeVideoSourceUpdateEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("bridgeuniqueid", "85f11e74-b0d9-4354-bc91-80782ee7a6a7"); + attributes.put("bridgepreviousvideosource", "e39cdee4-61a1-49b5-9656-96cef742806f"); + setAttributes(bridgeVideoSourceUpdateEvent, attributes, new HashSet<>()); + + assertThat(bridgeVideoSourceUpdateEvent.getBridgeUniqueId()) + .isEqualTo("85f11e74-b0d9-4354-bc91-80782ee7a6a7"); + assertThat(bridgeVideoSourceUpdateEvent.getBridgePreviousVideoSource()) + .isEqualTo("e39cdee4-61a1-49b5-9656-96cef742806f"); + } + +} \ No newline at end of file diff --git a/src/test/java/org/asteriskjava/manager/event/CdrEventTest.java b/src/test/java/org/asteriskjava/manager/event/CdrEventTest.java index 87a70df5d..66162e811 100644 --- a/src/test/java/org/asteriskjava/manager/event/CdrEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/CdrEventTest.java @@ -1,44 +1,45 @@ package org.asteriskjava.manager.event; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.util.TimeZone; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class CdrEventTest extends TestCase -{ +class CdrEventTest { CdrEvent cdrEvent; TimeZone defaultTimeZone; - - @Override - protected void setUp() throws Exception - { + + @BeforeEach + void setUp() { cdrEvent = new CdrEvent(this); cdrEvent.setStartTime("2006-05-19 11:54:48"); defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } - @Override - protected void tearDown() throws Exception - { + @AfterEach + void tearDown() { TimeZone.setDefault(defaultTimeZone); } - public void testGetStartTimeAsDate() - { + @Test + void testGetStartTimeAsDate() { assertEquals(1148039688000L, cdrEvent.getStartTimeAsDate().getTime()); } - public void testGetStartTimeAsDateWithTimeZone() - { + @Test + void testGetStartTimeAsDateWithTimeZone() { TimeZone tz = TimeZone.getTimeZone("GMT+2"); assertEquals(1148032488000L, cdrEvent.getStartTimeAsDate(tz).getTime()); } - public void testBug() - { + @Test + void testBug() { TimeZone.setDefault(TimeZone.getTimeZone("Europe/Monaco")); - + cdrEvent.setStartTime("2006-05-29 13:17:21"); assertEquals("Mon May 29 13:17:21 CEST 2006", cdrEvent.getStartTimeAsDate().toString()); } diff --git a/src/test/java/org/asteriskjava/manager/event/ChanSpyStopEventTest.java b/src/test/java/org/asteriskjava/manager/event/ChanSpyStopEventTest.java new file mode 100644 index 000000000..84046ce1c --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/ChanSpyStopEventTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.asteriskjava.manager.util.EventAttributesHelper; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class ChanSpyStopEventTest { + @Test + void shouldCreateEvent() { + //given + ChanSpyStopEvent chanSpyStopEvent = new ChanSpyStopEvent(new Object()); + Map attributes = new HashMap<>(); + attributes.put("spyeechannelstate", ""); + attributes.put("spyeeconnectedlinename", ""); + attributes.put("spyeelinkedid", "out-87066661337-009277"); + attributes.put("spyeelanguage", "en"); + attributes.put("spyeecontext", "cce"); + attributes.put("spyeeuniqueid", "out-87066661337-009277"); + attributes.put("spyeeconnectedlinenum", ""); + attributes.put("spyeecalleridnum", "87066661337"); + attributes.put("spyeraccountcode", ""); + attributes.put("spyeechannelstatedesc", "Up"); + attributes.put("spyeepriority", "1"); + attributes.put("spyeeaccountcode", ""); + attributes.put("spyeecalleridname", ""); + attributes.put("spyeeexten", "87066661337"); + + //when + EventAttributesHelper.setAttributes(chanSpyStopEvent, attributes, new HashSet<>()); + + //then + assertThat(chanSpyStopEvent.getSpyerAccountCode()).isEqualTo(""); + + assertThat(chanSpyStopEvent.getSpyeeChannelState()).isNull(); + assertThat(chanSpyStopEvent.getSpyeeConnectedLineName()).isNull(); + assertThat(chanSpyStopEvent.getSpyeeLinkedId()).isEqualTo("out-87066661337-009277"); + assertThat(chanSpyStopEvent.getSpyeeLanguage()).isEqualTo("en"); + assertThat(chanSpyStopEvent.getSpyeeUniqueId()).isEqualTo("out-87066661337-009277"); + assertThat(chanSpyStopEvent.getSpyeeConnectedLineNum()).isNull(); + assertThat(chanSpyStopEvent.getSpyeeCallerIdNum()).isEqualTo("87066661337"); + assertThat(chanSpyStopEvent.getSpyeeCallerIdName()).isNull(); + assertThat(chanSpyStopEvent.getSpyeeChannelStateDesc()).isEqualTo("Up"); + assertThat(chanSpyStopEvent.getSpyeePriority()).isEqualTo(1); + assertThat(chanSpyStopEvent.getSpyeeAccountCode()).isEqualTo(""); + assertThat(chanSpyStopEvent.getSpyeeCallerIdName()).isNull(); + assertThat(chanSpyStopEvent.getSpyeeExten()).isEqualTo("87066661337"); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/ChannelReloadEventTest.java b/src/test/java/org/asteriskjava/manager/event/ChannelReloadEventTest.java index 54841d1dc..1618cccac 100644 --- a/src/test/java/org/asteriskjava/manager/event/ChannelReloadEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/ChannelReloadEventTest.java @@ -1,34 +1,35 @@ package org.asteriskjava.manager.event; -import junit.framework.TestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class ChannelReloadEventTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class ChannelReloadEventTest { private ChannelReloadEvent event; - @Override - protected void setUp() throws Exception - { - super.setUp(); + @BeforeEach + void setUp() { this.event = new ChannelReloadEvent(this); } - public void testNullReloadReason() - { + @Test + void testNullReloadReason() { event.setReloadReason(null); assertNull(event.getReloadReasonCode()); assertNull(event.getReloadReasonDescription()); } - public void testGetReloadReasonCode() - { + @Test + void testGetReloadReasonCode() { event.setReloadReason("CLIRELOAD (Channel module reload by CLI command)"); assertEquals("CLIRELOAD", event.getReloadReasonCode()); assertEquals(ChannelReloadEvent.REASON_CLI_RELOAD, event.getReloadReasonCode()); } - public void testGetReloadReasonDescription() - { + @Test + void testGetReloadReasonDescription() { event.setReloadReason("CLIRELOAD (Channel module reload by CLI command)"); assertEquals("Channel module reload by CLI command", event.getReloadReasonDescription()); } diff --git a/src/test/java/org/asteriskjava/manager/event/ChannelTalkingStartEventTest.java b/src/test/java/org/asteriskjava/manager/event/ChannelTalkingStartEventTest.java new file mode 100644 index 000000000..b51997795 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/ChannelTalkingStartEventTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class ChannelTalkingStartEventTest { + @Test + void shouldCreateEvent() { + //given + ChannelTalkingStartEvent channelTalkingStartEvent = new ChannelTalkingStartEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("language", "en"); + attributes.put("accountcode", ""); + attributes.put("context", "phones"); + attributes.put("exten", "5"); + attributes.put("priority", "4"); + attributes.put("uniqueid", "1547252114.0"); + attributes.put("linkedid", "1547252114.0"); + + //when + setAttributes(channelTalkingStartEvent, attributes, new HashSet<>()); + + //then + assertThat(channelTalkingStartEvent.getLanguage()).isEqualTo("en"); + assertThat(channelTalkingStartEvent.getAccountCode()).isEqualTo(""); + assertThat(channelTalkingStartEvent.getContext()).isEqualTo("phones"); + assertThat(channelTalkingStartEvent.getExten()).isEqualTo("5"); + assertThat(channelTalkingStartEvent.getPriority()).isEqualTo(4); + assertThat(channelTalkingStartEvent.getUniqueId()).isEqualTo("1547252114.0"); + assertThat(channelTalkingStartEvent.getLinkedId()).isEqualTo("1547252114.0"); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/ChannelTalkingStopEventTest.java b/src/test/java/org/asteriskjava/manager/event/ChannelTalkingStopEventTest.java new file mode 100644 index 000000000..db0115041 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/ChannelTalkingStopEventTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class ChannelTalkingStopEventTest { + @Test + void shouldCreateEvent() { + //given + ChannelTalkingStopEvent channelTalkingStopEvent = new ChannelTalkingStopEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("language", "en"); + attributes.put("accountcode", ""); + attributes.put("context", "phones"); + attributes.put("exten", "5"); + attributes.put("priority", "4"); + attributes.put("uniqueid", "1547252114.0"); + attributes.put("linkedid", "1547252114.0"); + attributes.put("duration", "6030"); + + //when + setAttributes(channelTalkingStopEvent, attributes, new HashSet<>()); + + //then + assertThat(channelTalkingStopEvent.getLanguage()).isEqualTo("en"); + assertThat(channelTalkingStopEvent.getAccountCode()).isEqualTo(""); + assertThat(channelTalkingStopEvent.getContext()).isEqualTo("phones"); + assertThat(channelTalkingStopEvent.getExten()).isEqualTo("5"); + assertThat(channelTalkingStopEvent.getPriority()).isEqualTo(4); + assertThat(channelTalkingStopEvent.getUniqueId()).isEqualTo("1547252114.0"); + assertThat(channelTalkingStopEvent.getLinkedId()).isEqualTo("1547252114.0"); + assertThat(channelTalkingStopEvent.getDuration()).isEqualTo(6030); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/ConfbridgeJoinEventTest.java b/src/test/java/org/asteriskjava/manager/event/ConfbridgeJoinEventTest.java new file mode 100644 index 000000000..c2a3006a8 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/ConfbridgeJoinEventTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class ConfbridgeJoinEventTest { + @Test + void shouldCreateEvent() { + //given + ConfbridgeJoinEvent confbridgeJoinEvent = new ConfbridgeJoinEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("language", "en"); + attributes.put("linkedid", "1474881412.1"); + + //when + setAttributes(confbridgeJoinEvent, attributes, new HashSet<>()); + + //then + assertThat(confbridgeJoinEvent.getLanguage()).isEqualTo("en"); + assertThat(confbridgeJoinEvent.getLinkedId()).isEqualTo("1474881412.1"); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/ConfbridgeLeaveEventTest.java b/src/test/java/org/asteriskjava/manager/event/ConfbridgeLeaveEventTest.java new file mode 100644 index 000000000..5d07405cb --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/ConfbridgeLeaveEventTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class ConfbridgeLeaveEventTest { + @Test + void shouldCreateEvent() { + //given + ConfbridgeLeaveEvent confbridgeLeaveEvent = new ConfbridgeLeaveEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("language", "en"); + attributes.put("linkedid", "1475486824.3"); + + //when + setAttributes(confbridgeLeaveEvent, attributes, new HashSet<>()); + + //then + assertThat(confbridgeLeaveEvent.getLanguage()).isEqualTo("en"); + assertThat(confbridgeLeaveEvent.getLinkedId()).isEqualTo("1475486824.3"); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/HangupEventTest.java b/src/test/java/org/asteriskjava/manager/event/HangupEventTest.java new file mode 100644 index 000000000..d0929c63e --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/HangupEventTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class HangupEventTest { + @ParameterizedTest + @ValueSource(strings = {"False", "762377"}) + void shouldCreateEvent(String accountCode) { + //given + HangupEvent hangupEvent = new HangupEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("accountcode", accountCode); + + //when + setAttributes(hangupEvent, attributes, new HashSet<>()); + + //then + assertThat(hangupEvent.getAccountCode()).isEqualTo(accountCode); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/HangupRequestEventTest.java b/src/test/java/org/asteriskjava/manager/event/HangupRequestEventTest.java new file mode 100644 index 000000000..bad0c3377 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/HangupRequestEventTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class HangupRequestEventTest { + @Test + void shouldCreateEvent() { + //given + HangupRequestEvent hangupRequestEvent = new HangupRequestEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("cause", "1"); + + //when + setAttributes(hangupRequestEvent, attributes, new HashSet<>()); + + //then + assertThat(hangupRequestEvent.getCause()).isEqualTo(1); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/MusicOnHoldEventTest.java b/src/test/java/org/asteriskjava/manager/event/MusicOnHoldEventTest.java new file mode 100644 index 000000000..c4d64ee5a --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/event/MusicOnHoldEventTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asteriskjava.manager.event; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.HashSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.asteriskjava.manager.util.EventAttributesHelper.setAttributes; + +class MusicOnHoldEventTest { + @Test + void shouldCreateEvent() { + //given + MusicOnHoldEvent musicOnHoldEvent = new MusicOnHoldEvent(new Object()); + + HashMap attributes = new HashMap<>(); + attributes.put("class", "default"); + + //when + setAttributes(musicOnHoldEvent, attributes, new HashSet<>()); + + //then + assertThat(musicOnHoldEvent.getClassName()).isEqualTo("default"); + } +} diff --git a/src/test/java/org/asteriskjava/manager/event/NewStateEventTest.java b/src/test/java/org/asteriskjava/manager/event/NewStateEventTest.java index 46f8163fd..47e92601d 100644 --- a/src/test/java/org/asteriskjava/manager/event/NewStateEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/NewStateEventTest.java @@ -1,27 +1,28 @@ package org.asteriskjava.manager.event; -import junit.framework.TestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class NewStateEventTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.assertEquals; + +class NewStateEventTest { private NewStateEvent newStateEvent; - @Override - public void setUp() - { + @BeforeEach + void setUp() { newStateEvent = new NewStateEvent(this); } - public void testWithState() - { + @Test + void testWithState() { newStateEvent.setState("Ring"); - assertEquals(new Integer(4), newStateEvent.getChannelState()); + assertEquals(Integer.valueOf(4), newStateEvent.getChannelState()); assertEquals("Ring", newStateEvent.getChannelStateDesc()); } - public void testWithUnknownState() - { + @Test + void testWithUnknownState() { newStateEvent.setState("Unknown (4)"); - assertEquals(new Integer(4), newStateEvent.getChannelState()); + assertEquals(Integer.valueOf(4), newStateEvent.getChannelState()); } -} \ No newline at end of file +} diff --git a/src/test/java/org/asteriskjava/manager/event/RtcpReceivedEventTest.java b/src/test/java/org/asteriskjava/manager/event/RtcpReceivedEventTest.java index eb008d097..c7485ea6a 100644 --- a/src/test/java/org/asteriskjava/manager/event/RtcpReceivedEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/RtcpReceivedEventTest.java @@ -1,46 +1,47 @@ package org.asteriskjava.manager.event; -import junit.framework.TestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class RtcpReceivedEventTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.assertEquals; + +class RtcpReceivedEventTest { private RtcpReceivedEvent rtcpReceivedEvent; - @Override - public void setUp() - { + @BeforeEach + void setUp() { rtcpReceivedEvent = new RtcpReceivedEvent(this); } - public void testFrom() - { + @Test + void testFrom() { rtcpReceivedEvent.setFrom("192.168.0.1:1234"); - assertEquals("192.168.0.1", rtcpReceivedEvent.getFromAddress().getHostAddress()); - assertEquals(new Integer(1234), rtcpReceivedEvent.getFromPort()); + assertEquals(rtcpReceivedEvent.getFromAddress().getHostAddress(), "192.168.0.1"); + assertEquals(Integer.valueOf(1234), rtcpReceivedEvent.getFromPort()); } - public void testPt() - { + @Test + void testPt() { rtcpReceivedEvent.setPt("200(Sender Report)"); - assertEquals(new Long(200), rtcpReceivedEvent.getPt()); - assertEquals(new Long(RtcpReceivedEvent.PT_SENDER_REPORT), rtcpReceivedEvent.getPt()); + assertEquals(Long.valueOf(200), rtcpReceivedEvent.getPt()); + assertEquals(Long.valueOf(RtcpReceivedEvent.PT_SENDER_REPORT), rtcpReceivedEvent.getPt()); } - public void testDlSr() - { + @Test + void testDlSr() { rtcpReceivedEvent.setDlSr("1.2345(sec)"); - assertEquals(1.2345, rtcpReceivedEvent.getDlSr()); + assertEquals(1.2345, rtcpReceivedEvent.getDlSr(), 0.00001); } - public void testDlSrWithSpace() - { + @Test + void testDlSrWithSpace() { rtcpReceivedEvent.setDlSr("1.2345 (sec)"); // as used in RTCPSent - assertEquals(1.2345, rtcpReceivedEvent.getDlSr()); + assertEquals(1.2345, rtcpReceivedEvent.getDlSr(), 0.00001); } - public void testRtt() - { + @Test + void testRtt() { rtcpReceivedEvent.setRtt("12345(sec)"); - assertEquals(new Long(12345), rtcpReceivedEvent.getRtt()); + assertEquals(Double.valueOf(12345), rtcpReceivedEvent.getRtt()); } -} \ No newline at end of file +} diff --git a/src/test/java/org/asteriskjava/manager/event/SkypeBuddyStatusEventTest.java b/src/test/java/org/asteriskjava/manager/event/SkypeBuddyStatusEventTest.java index 1f45ca791..bf8bfc728 100644 --- a/src/test/java/org/asteriskjava/manager/event/SkypeBuddyStatusEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/SkypeBuddyStatusEventTest.java @@ -1,25 +1,26 @@ package org.asteriskjava.manager.event; -import junit.framework.TestCase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SkypeBuddyStatusEventTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SkypeBuddyStatusEventTest { private SkypeBuddyStatusEvent event; - @Override - public void setUp() - { + @BeforeEach + void setUp() { event = new SkypeBuddyStatusEvent(this); event.setBuddy("Skype/user@the.buddy"); } - public void testGetUser() throws Exception - { + @Test + void testGetUser() { assertEquals("user", event.getUser()); } - public void testGetBuddySkypename() throws Exception - { + @Test + void testGetBuddySkypename() { assertEquals("the.buddy", event.getBuddySkypename()); } } diff --git a/src/test/java/org/asteriskjava/manager/event/SkypeChatMessageEventTest.java b/src/test/java/org/asteriskjava/manager/event/SkypeChatMessageEventTest.java index f9b2b3b7b..e68a3f656 100644 --- a/src/test/java/org/asteriskjava/manager/event/SkypeChatMessageEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/SkypeChatMessageEventTest.java @@ -1,13 +1,14 @@ package org.asteriskjava.manager.event; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; -public class SkypeChatMessageEventTest extends TestCase -{ - public void testGetDecodedMessage() - { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SkypeChatMessageEventTest { + @Test + void testGetDecodedMessage() { final SkypeChatMessageEvent event = new SkypeChatMessageEvent(this); event.setMessage("aMO2w7bDtj8="); - assertEquals("Inocrrectly decoded message", "h\u00F6\u00F6\u00F6?", event.getDecodedMessage()); + assertEquals("h\u00F6\u00F6\u00F6?", event.getDecodedMessage(), "Inocrrectly decoded message"); } } diff --git a/src/test/java/org/asteriskjava/manager/event/T38FaxStatusEventTest.java b/src/test/java/org/asteriskjava/manager/event/T38FaxStatusEventTest.java index 0fa59ed8f..02af226bd 100644 --- a/src/test/java/org/asteriskjava/manager/event/T38FaxStatusEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/T38FaxStatusEventTest.java @@ -1,20 +1,18 @@ package org.asteriskjava.manager.event; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; -/** - * - */ -public class T38FaxStatusEventTest extends TestCase -{ - public void testStripUnit() - { +import static org.junit.jupiter.api.Assertions.assertEquals; + +class T38FaxStatusEventTest { + @Test + void testStripUnit() { T38FaxStatusEvent event = new T38FaxStatusEvent(this); assertEquals("0.022", event.stripUnit("0.022 sec.")); } - public void testParseProperties() - { + @Test + void testParseProperties() { T38FaxStatusEvent event = new T38FaxStatusEvent(this); event.setTotalLag("-9 ms"); event.setMaxLag("4 ms"); @@ -25,8 +23,8 @@ public void testParseProperties() assertEquals(-9, event.getTotalLagInMilliSeconds().intValue()); assertEquals(4, event.getMaxLagInMilliSeconds().intValue()); - assertEquals(0.022, event.getT38SessionDurationInSeconds()); - assertEquals(-1.8, event.getAverageLagInMilliSeconds()); + assertEquals(0.022, event.getT38SessionDurationInSeconds(), 0.00001); + assertEquals(-1.8, event.getAverageLagInMilliSeconds(), 0.00001); assertEquals(363, event.getAverageTxDataRateInBps().intValue()); assertEquals(0, event.getAverageRxDataRateInBps().intValue()); } diff --git a/src/test/java/org/asteriskjava/manager/internal/A.java b/src/test/java/org/asteriskjava/manager/internal/A.java index d657fe93c..748606381 100644 --- a/src/test/java/org/asteriskjava/manager/internal/A.java +++ b/src/test/java/org/asteriskjava/manager/internal/A.java @@ -18,12 +18,10 @@ import org.asteriskjava.manager.event.UserEvent; -public class A extends UserEvent -{ +public class A extends UserEvent { private static final long serialVersionUID = 3545240219457894199L; - public A(Object source) - { + public A(Object source) { super(source); } } diff --git a/src/test/java/org/asteriskjava/manager/internal/ActionBuilderImplTest.java b/src/test/java/org/asteriskjava/manager/internal/ActionBuilderImplTest.java index 9382dc85d..a36214a46 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ActionBuilderImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ActionBuilderImplTest.java @@ -16,26 +16,26 @@ */ package org.asteriskjava.manager.internal; +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.manager.action.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.util.LinkedHashMap; import java.util.Map; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.*; -import org.asteriskjava.AsteriskVersion; -import org.asteriskjava.manager.action.*; - -public class ActionBuilderImplTest extends TestCase -{ +class ActionBuilderImplTest { private ActionBuilderImpl actionBuilder; - @Override - public void setUp() - { + @BeforeEach + void setUp() { this.actionBuilder = new ActionBuilderImpl(); } - public void testBuildAction() - { + @Test + void testBuildAction() { MyAction myAction; String actual; @@ -46,15 +46,15 @@ public void testBuildAction() actual = actionBuilder.buildAction(myAction); - assertTrue("Action name missing", actual.indexOf("action: My\r\n") >= 0); - assertTrue("First property missing", actual.indexOf("firstproperty: first value\r\n") >= 0); - assertTrue("Second property missing", actual.indexOf("secondproperty: 2\r\n") >= 0); - assertTrue("Missing trailing CRNL CRNL", actual.endsWith("\r\n\r\n")); - assertEquals("Incorrect length", 61, actual.length()); + assertTrue(actual.indexOf("action: My\r\n") >= 0, "Action name missing"); + assertTrue(actual.indexOf("firstproperty: first value\r\n") >= 0, "First property missing"); + assertTrue(actual.indexOf("secondproperty: 2\r\n") >= 0, "Second property missing"); + assertTrue(actual.endsWith("\r\n\r\n"), "Missing trailing CRNL CRNL"); + assertEquals(61, actual.length(), "Incorrect length"); } - public void testBuildActionWithNullValue() - { + @Test + void testBuildActionWithNullValue() { MyAction myAction; String actual; @@ -63,14 +63,14 @@ public void testBuildActionWithNullValue() actual = actionBuilder.buildAction(myAction); - assertTrue("Action name missing", actual.indexOf("action: My\r\n") >= 0); - assertTrue("First property missing", actual.indexOf("firstproperty: first value\r\n") >= 0); - assertTrue("Missing trailing CRNL CRNL", actual.endsWith("\r\n\r\n")); - assertEquals("Incorrect length", 42, actual.length()); + assertTrue(actual.indexOf("action: My\r\n") >= 0, "Action name missing"); + assertTrue(actual.indexOf("firstproperty: first value\r\n") >= 0, "First property missing"); + assertTrue(actual.endsWith("\r\n\r\n"), "Missing trailing CRNL CRNL"); + assertEquals(42, actual.length(), "Incorrect length"); } - public void testBuildEventGeneratingAction() - { + @Test + void testBuildEventGeneratingAction() { AgentsAction action; String actual; @@ -78,13 +78,13 @@ public void testBuildEventGeneratingAction() actual = actionBuilder.buildAction(action); - assertTrue("Action name missing", actual.indexOf("action: Agents\r\n") >= 0); - assertTrue("Action contains actionCompleteEventClass property", actual.indexOf("actioncompleteeventclass:") == -1); - assertTrue("Missing trailing CRNL CRNL", actual.endsWith("\r\n\r\n")); + assertTrue(actual.indexOf("action: Agents\r\n") >= 0, "Action name missing"); + assertTrue(actual.indexOf("actioncompleteeventclass:") == -1, "Action contains actionCompleteEventClass property"); + assertTrue(actual.endsWith("\r\n\r\n"), "Missing trailing CRNL CRNL"); } - - public void testBuildUpdateConfigAction() - { + + @Test + void testBuildUpdateConfigAction() { UpdateConfigAction action; action = new UpdateConfigAction(); action.setSrcFilename("sourcefile.conf"); @@ -93,19 +93,19 @@ public void testBuildUpdateConfigAction() action.addCommand(UpdateConfigAction.ACTION_NEWCAT, "testcategory", null, null, null); String actual = actionBuilder.buildAction(action); - - assertTrue("Action name missing", actual.indexOf("action: UpdateConfig") >= 0); - assertTrue("Source filename missing", actual.indexOf("srcfilename: sourcefile.conf") >= 0); - assertTrue("Destination filename missing", actual.indexOf("dstfilename: destfile.conf") >= 0); - assertTrue("Correct reload setting missing", actual.indexOf("reload: Yes") >= 0); - - assertFalse("Action must have zero-padded 6 digit numbering", actual.indexOf("Action-0:") >= 0); - assertFalse("UpdateConfig actions must not have more than one 'action' header", actual.indexOf("action: Action") >= 0); - assertTrue("Action missing category testcategory - " + actual, actual.indexOf("Cat-000000: testcategory") >= 0); + + assertTrue(actual.indexOf("action: UpdateConfig") >= 0, "Action name missing"); + assertTrue(actual.indexOf("srcfilename: sourcefile.conf") >= 0, "Source filename missing"); + assertTrue(actual.indexOf("dstfilename: destfile.conf") >= 0, "Destination filename missing"); + assertTrue(actual.indexOf("reload: Yes") >= 0, "Correct reload setting missing"); + + assertFalse(actual.indexOf("Action-0:") >= 0, "Action must have zero-padded 6 digit numbering"); + assertFalse(actual.indexOf("action: Action") >= 0, "UpdateConfig actions must not have more than one 'action' header"); + assertTrue(actual.indexOf("Cat-000000: testcategory") >= 0, "Action missing category testcategory - " + actual); } - public void testBuildUserEventAction() - { + @Test + void testBuildUserEventAction() { UserEventAction action; action = new UserEventAction(); @@ -122,16 +122,16 @@ public void testBuildUserEventAction() event.setMapMember(mapMemberTest); String actual = actionBuilder.buildAction(action); - assertTrue("Action name missing", actual.indexOf("action: UserEvent\r\n") >= 0); - assertTrue("Event name missing", actual.indexOf("UserEvent: myuser\r\n") >= 0); - assertTrue("Regular member missing", actual.indexOf("stringmember: stringMemberValue\r\n") >= 0); - assertTrue("Map member missing", actual.indexOf("mapmember: Key1=Value1|Key2=Value2|Key3=Value3\r\n") >= 0); - assertTrue("Missing trailing CRNL CRNL", actual.endsWith("\r\n\r\n")); + assertTrue(actual.indexOf("action: UserEvent\r\n") >= 0, "Action name missing"); + assertTrue(actual.indexOf("UserEvent: myuser\r\n") >= 0, "Event name missing"); + assertTrue(actual.indexOf("stringmember: stringMemberValue\r\n") >= 0, "Regular member missing"); + assertTrue(actual.indexOf("mapmember: Key1=Value1|Key2=Value2|Key3=Value3\r\n") >= 0, "Map member missing"); + assertTrue(actual.endsWith("\r\n\r\n"), "Missing trailing CRNL CRNL"); } @SuppressWarnings("deprecation") - public void testBuildActionWithVariablesForAsterisk10() - { + @Test + void testBuildActionWithVariablesForAsterisk10() { OriginateAction originateAction; String actual; @@ -140,13 +140,12 @@ public void testBuildActionWithVariablesForAsterisk10() actual = actionBuilder.buildAction(originateAction); - assertTrue("Incorrect mapping of variable property for Asterisk 1.0", - actual.indexOf("variable: var1=value1|var2=value2\r\n") >= 0); + assertTrue(actual.indexOf("variable: var1=value1|var2=value2\r\n") >= 0, "Incorrect mapping of variable property for Asterisk 1.0"); } @SuppressWarnings("deprecation") - public void testBuildActionWithVariablesForAsterisk10WithNullValues() - { + @Test + void testBuildActionWithVariablesForAsterisk10WithNullValues() { OriginateAction originateAction; String actual; @@ -155,13 +154,12 @@ public void testBuildActionWithVariablesForAsterisk10WithNullValues() actual = actionBuilder.buildAction(originateAction); - assertTrue("Incorrect mapping of variable property for Asterisk 1.0", - actual.indexOf("variable: var1=value1|var2=|var3=value3\r\n") >= 0); + assertTrue(actual.indexOf("variable: var1=value1|var2=|var3=value3\r\n") >= 0, "Incorrect mapping of variable property for Asterisk 1.0"); } @SuppressWarnings("deprecation") - public void testBuildActionWithVariablesForAsterisk12() - { + @Test + void testBuildActionWithVariablesForAsterisk12() { OriginateAction originateAction; String actual; @@ -171,13 +169,12 @@ public void testBuildActionWithVariablesForAsterisk12() actionBuilder.setTargetVersion(AsteriskVersion.ASTERISK_1_2); actual = actionBuilder.buildAction(originateAction); - assertTrue("Incorrect mapping of variable property for Asterisk 1.2", - actual.indexOf("variable: var1=value1\r\nvariable: var2=value2\r\n") >= 0); + assertTrue(actual.indexOf("variable: var1=value1\r\nvariable: var2=value2\r\n") >= 0, "Incorrect mapping of variable property for Asterisk 1.2"); } @SuppressWarnings("deprecation") - public void testBuildActionWithVariablesForAsterisk12WithNullValues() - { + @Test + void testBuildActionWithVariablesForAsterisk12WithNullValues() { OriginateAction originateAction; String actual; @@ -187,12 +184,11 @@ public void testBuildActionWithVariablesForAsterisk12WithNullValues() actionBuilder.setTargetVersion(AsteriskVersion.ASTERISK_1_2); actual = actionBuilder.buildAction(originateAction); - assertTrue("Incorrect mapping of variable property for Asterisk 1.2", - actual.indexOf("variable: var1=value1\r\nvariable: var2=\r\nvariable: var3=value3\r\n") >= 0); + assertTrue(actual.indexOf("variable: var1=value1\r\nvariable: var2=\r\nvariable: var3=value3\r\n") >= 0, "Incorrect mapping of variable property for Asterisk 1.2"); } - public void testBuildActionWithVariableMapForAsterisk12() - { + @Test + void testBuildActionWithVariableMapForAsterisk12() { OriginateAction originateAction; Map map; String actual; @@ -208,12 +204,11 @@ public void testBuildActionWithVariableMapForAsterisk12() actionBuilder.setTargetVersion(AsteriskVersion.ASTERISK_1_2); actual = actionBuilder.buildAction(originateAction); - assertTrue("Incorrect mapping of variable property for Asterisk 1.2", - actual.indexOf("variable: var1=value1\r\nvariable: VAR2=value2\r\n") >= 0); + assertTrue(actual.indexOf("variable: var1=value1\r\nvariable: VAR2=value2\r\n") >= 0, "Incorrect mapping of variable property for Asterisk 1.2"); } - public void testBuildActionForSipNotifyAction() - { + @Test + void testBuildActionForSipNotifyAction() { SipNotifyAction action; String actual; @@ -224,100 +219,86 @@ public void testBuildActionForSipNotifyAction() actionBuilder.setTargetVersion(AsteriskVersion.ASTERISK_1_6); actual = actionBuilder.buildAction(action); - assertTrue("Incorrect mapping of variable property", - actual.indexOf("variable: var1=value1\r\nvariable: var2=value2\r\n") >= 0); + assertTrue(actual.indexOf("variable: var1=value1\r\nvariable: var2=value2\r\n") >= 0, "Incorrect mapping of variable property"); } - public void testBuildActionWithAnnotatedGetter() - { + @Test + void testBuildActionWithAnnotatedGetter() { AnnotatedAction action = new AnnotatedAction("value1", "value2", "value3"); String actual = actionBuilder.buildAction(action); - assertTrue("Incorrect mapping of property with annotated getter", - actual.indexOf("property-1: value1\r\n") >= 0); + assertTrue(actual.indexOf("property-1: value1\r\n") >= 0, "Incorrect mapping of property with annotated getter"); } - public void testDetermineSetterName() - { - assertEquals("setProperty1", actionBuilder.determineSetterName("getProperty1")); - assertEquals("setProperty1", actionBuilder.determineSetterName("isProperty1")); + @Test + void testDetermineSetterName() { + assertEquals("setProperty1", ActionBuilderImpl.determineSetterName("getProperty1")); + assertEquals("setProperty1", ActionBuilderImpl.determineSetterName("isProperty1")); } - public void testBuildActionWithAnnotatedSetter() - { + @Test + void testBuildActionWithAnnotatedSetter() { AnnotatedAction action = new AnnotatedAction("value1", "value2", "value3"); String actual = actionBuilder.buildAction(action); - assertTrue("Incorrect mapping of property with annotated setter", - actual.indexOf("property-2: value2\r\n") >= 0); + assertTrue(actual.indexOf("property-2: value2\r\n") >= 0, "Incorrect mapping of property with annotated setter"); } - public void testDetermineFieldName() - { - assertEquals("property1", actionBuilder.determineFieldName("getProperty1")); - assertEquals("property1", actionBuilder.determineFieldName("isProperty1")); - assertEquals("property1", actionBuilder.determineFieldName("setProperty1")); + @Test + void testDetermineFieldName() { + assertEquals("property1", ActionBuilderImpl.determineFieldName("getProperty1")); + assertEquals("property1", ActionBuilderImpl.determineFieldName("isProperty1")); + assertEquals("property1", ActionBuilderImpl.determineFieldName("setProperty1")); } - public void testBuildActionWithAnnotatedField() - { + @Test + void testBuildActionWithAnnotatedField() { AnnotatedAction action = new AnnotatedAction("value1", "value2", "value3"); String actual = actionBuilder.buildAction(action); - assertTrue("Incorrect mapping of property with annotated field", - actual.indexOf("property-3: value3\r\n") >= 0); + assertTrue(actual.indexOf("property-3: value3\r\n") >= 0, "Incorrect mapping of property with annotated field"); } - class MyAction extends AbstractManagerAction - { + class MyAction extends AbstractManagerAction { private static final long serialVersionUID = 3257568425345102641L; private String firstProperty; private Integer secondProperty; private String nonPublicProperty; @Override - public String getAction() - { + public String getAction() { return "My"; } - public String getFirstProperty() - { + public String getFirstProperty() { return firstProperty; } - public void setFirstProperty(String firstProperty) - { + public void setFirstProperty(String firstProperty) { this.firstProperty = firstProperty; } - public Integer getSecondProperty() - { + public Integer getSecondProperty() { return secondProperty; } - public void setSecondProperty(Integer secondProperty) - { + public void setSecondProperty(Integer secondProperty) { this.secondProperty = secondProperty; } - protected String getNonPublicProperty() - { + protected String getNonPublicProperty() { return nonPublicProperty; } - protected void setNonPublicProperty(String privateProperty) - { + protected void setNonPublicProperty(String privateProperty) { this.nonPublicProperty = privateProperty; } - public String get() - { + public String get() { return "This method must not be considered a getter"; } - public String getIndexedProperty(int i) - { + public String getIndexedProperty(int i) { return "This method must not be considered a getter relevant for building the action"; } } diff --git a/src/test/java/org/asteriskjava/manager/internal/AnnotatedAction.java b/src/test/java/org/asteriskjava/manager/internal/AnnotatedAction.java index 7aacff3f3..c68cd2e9c 100644 --- a/src/test/java/org/asteriskjava/manager/internal/AnnotatedAction.java +++ b/src/test/java/org/asteriskjava/manager/internal/AnnotatedAction.java @@ -16,11 +16,10 @@ */ package org.asteriskjava.manager.internal; -import org.asteriskjava.manager.action.AbstractManagerAction; import org.asteriskjava.manager.AsteriskMapping; +import org.asteriskjava.manager.action.AbstractManagerAction; -public class AnnotatedAction extends AbstractManagerAction -{ +public class AnnotatedAction extends AbstractManagerAction { private static final long serialVersionUID = 1L; private String property1; private String property2; @@ -28,52 +27,43 @@ public class AnnotatedAction extends AbstractManagerAction @AsteriskMapping("property-3") // annotated field private String property3; - public AnnotatedAction() - { + public AnnotatedAction() { } - public AnnotatedAction(String property1, String property2, String property3) - { + public AnnotatedAction(String property1, String property2, String property3) { this.property1 = property1; this.property2 = property2; this.property3 = property3; } @Override - public String getAction() - { + public String getAction() { return "Custom"; } @AsteriskMapping("property-1") // annotated getter - public String getProperty1() - { + public String getProperty1() { return property1; } - public void setProperty1(String property1) - { + public void setProperty1(String property1) { this.property1 = property1; } - public String getProperty2() - { + public String getProperty2() { return property2; } @AsteriskMapping("property-2") // annotated setter - public void setProperty2(String property2) - { + public void setProperty2(String property2) { this.property2 = property2; } - public String getProperty3() - { + public String getProperty3() { return property3; } - public void setProperty3(String property3) - { + public void setProperty3(String property3) { this.property3 = property3; } -} \ No newline at end of file +} diff --git a/src/test/java/org/asteriskjava/manager/internal/BEvent.java b/src/test/java/org/asteriskjava/manager/internal/BEvent.java index 51c34c70d..a3895ac00 100644 --- a/src/test/java/org/asteriskjava/manager/internal/BEvent.java +++ b/src/test/java/org/asteriskjava/manager/internal/BEvent.java @@ -18,12 +18,10 @@ import org.asteriskjava.manager.event.UserEvent; -public class BEvent extends UserEvent -{ +public class BEvent extends UserEvent { private static final long serialVersionUID = 3545240219457894199L; - public BEvent(Object source) - { + public BEvent(Object source) { super(source); } } diff --git a/src/test/java/org/asteriskjava/manager/internal/EEvent.java b/src/test/java/org/asteriskjava/manager/internal/EEvent.java new file mode 100644 index 000000000..30ca8790c --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/internal/EEvent.java @@ -0,0 +1,46 @@ +/* + * Copyright 2004-2006 Stefan Reuter + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.internal; + +import org.asteriskjava.manager.event.ManagerEvent; + +public class EEvent + extends ManagerEvent { + + private static final long serialVersionUID = 3545240219457894199L; + + private Boolean line; + + public EEvent(Object source) { + super(source); + } + + public Boolean getLineAsBoolean() { + return line; + } + + public void setLine(Boolean line) { + this.line = line; + if (line == null) { + super.setLine(null); + } else if (line) { + super.setLine(1); + } else { + super.setLine(0); + } + } +} diff --git a/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java b/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java index df98dce0b..19782a6d3 100644 --- a/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java @@ -16,65 +16,66 @@ */ package org.asteriskjava.manager.internal; -import junit.framework.TestCase; import org.asteriskjava.manager.event.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashMap; import java.util.Map; -public class EventBuilderImplTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.*; + +class EventBuilderImplTest { private EventBuilder eventBuilder; private Map properties; - @Override - public void setUp() - { + @BeforeEach + void setUp() { this.eventBuilder = new EventBuilderImpl(); this.properties = new HashMap(); } - public void testRegisterEvent() - { + @Test + void testRegisterEvent() { eventBuilder.registerEventClass(NewChannelEvent.class); } - public void testRegisterUserEventWithA() - { + @Test + void testRegisterUserEventWithA() { ManagerEvent event; eventBuilder.registerEventClass(A.class); properties.put("event", "UserEventA"); event = eventBuilder.buildEvent(this, properties); - assertTrue("Wrong type", event instanceof A); + assertTrue(event instanceof A, "Wrong type"); } - public void testRegisterUserEventWithBEvent() - { + @Test + void testRegisterUserEventWithBEvent() { ManagerEvent event; eventBuilder.registerEventClass(BEvent.class); properties.put("event", "UserEventB"); event = eventBuilder.buildEvent(this, properties); - assertTrue("Wrong type", event instanceof BEvent); + assertTrue(event instanceof BEvent, "Wrong type"); } - public void testRegisterUserEventWithUserEventC() - { + @Test + void testRegisterUserEventWithUserEventC() { ManagerEvent event; eventBuilder.registerEventClass(UserEventC.class); properties.put("event", "UserEventC"); event = eventBuilder.buildEvent(this, properties); - assertTrue("Wrong type", event instanceof UserEventC); + assertTrue(event instanceof UserEventC, "Wrong type"); } - public void testRegisterUserEventWithUserEventCAndAsterisk14() - { + @Test + void testRegisterUserEventWithUserEventCAndAsterisk14() { ManagerEvent event; eventBuilder.registerEventClass(UserEventC.class); @@ -82,41 +83,54 @@ public void testRegisterUserEventWithUserEventCAndAsterisk14() properties.put("userevent", "C"); event = eventBuilder.buildEvent(this, properties); - assertTrue("Wrong type", event instanceof UserEventC); + assertTrue(event instanceof UserEventC, "Wrong type"); } - public void testRegisterUserEventWithUserEventDEvent() - { + @Test + void testRegisterUserEventWithUserEventDEvent() { ManagerEvent event; eventBuilder.registerEventClass(UserEventDEvent.class); properties.put("event", "UserEventD"); event = eventBuilder.buildEvent(this, properties); - assertTrue("Wrong type", event instanceof UserEventDEvent); + assertTrue(event instanceof UserEventDEvent, "Wrong type"); } - public void testRegisterEventWithAbstractEvent() - { - try - { + @Test + void testBuildEventWithOverrideSetter() { + ManagerEvent event; + + eventBuilder.registerEventClass(EEvent.class); + properties.put("event", "e"); + properties.put("line", "true"); + properties.put("exten", "1abz"); + event = eventBuilder.buildEvent(this, properties); + + assertTrue(event instanceof EEvent, "Wrong type"); + assertEquals("1abz", event.getExten()); + assertEquals(Integer.valueOf(1), event.getLine()); + assertTrue(((EEvent) event).getLineAsBoolean()); + } + + @Test + void testRegisterEventWithAbstractEvent() { + try { eventBuilder.registerEventClass(AbstractChannelEvent.class); fail("registerEvent() must not accept abstract classes"); - } - catch (IllegalArgumentException ex) - { + } catch (IllegalArgumentException ex) { } } /* - * public void testGetSetters() { Map setters; EventBuilderImpl eventBuilder = - * getEventBuilder(); setters = + * void testGetSetters() { Map setters; EventBuilderImpl eventBuilder + * = getEventBuilder(); setters = * eventBuilder.getSetters(NewChannelEvent.class); assertTrue("Setter not * found", setters.containsKey("callerid")); } */ - public void testBuildEventWithMixedCaseSetter() - { + @Test + void testBuildEventWithMixedCaseSetter() { String callerid = "1234"; NewChannelEvent event; @@ -125,13 +139,13 @@ public void testBuildEventWithMixedCaseSetter() event = (NewChannelEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", NewChannelEvent.class, event.getClass()); - assertEquals("String property not set correctly", callerid, event.getCallerIdNum()); - assertEquals("Source not set correctly", this, event.getSource()); + assertEquals(NewChannelEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals(callerid, event.getCallerIdNum(), "String property not set correctly"); + assertEquals(this, event.getSource(), "Source not set correctly"); } - public void testBuildEventWithIntegerProperty() - { + @Test + void testBuildEventWithIntegerProperty() { String channel = "SIP/1234"; Integer priority = 1; NewExtenEvent event; @@ -142,13 +156,13 @@ public void testBuildEventWithIntegerProperty() event = (NewExtenEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", NewExtenEvent.class, event.getClass()); - assertEquals("String property not set correctly", channel, event.getChannel()); - assertEquals("Integer property not set correctly", priority, event.getPriority()); + assertEquals(NewExtenEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals(channel, event.getChannel(), "String property not set correctly"); + assertEquals(priority, event.getPriority(), "Integer property not set correctly"); } - public void testBuildEventWithBooleanProperty() - { + @Test + void testBuildEventWithBooleanProperty() { ShutdownEvent event; eventBuilder.registerEventClass(ShutdownEvent.class); @@ -157,12 +171,12 @@ public void testBuildEventWithBooleanProperty() event = (ShutdownEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", ShutdownEvent.class, event.getClass()); - assertEquals("Boolean property not set correctly", Boolean.TRUE, event.getRestart()); + assertEquals(ShutdownEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals(Boolean.TRUE, event.getRestart(), "Boolean property not set correctly"); } - public void testBuildEventWithBooleanPropertyOfValueYes() - { + @Test + void testBuildEventWithBooleanPropertyOfValueYes() { ShutdownEvent event; eventBuilder.registerEventClass(ShutdownEvent.class); @@ -171,12 +185,12 @@ public void testBuildEventWithBooleanPropertyOfValueYes() event = (ShutdownEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", ShutdownEvent.class, event.getClass()); - assertEquals("Boolean property not set correctly", Boolean.TRUE, event.getRestart()); + assertEquals(ShutdownEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals(Boolean.TRUE, event.getRestart(), "Boolean property not set correctly"); } - public void testBuildEventWithBooleanPropertyOfValueNo() - { + @Test + void testBuildEventWithBooleanPropertyOfValueNo() { ShutdownEvent event; eventBuilder.registerEventClass(ShutdownEvent.class); @@ -185,12 +199,12 @@ public void testBuildEventWithBooleanPropertyOfValueNo() event = (ShutdownEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", ShutdownEvent.class, event.getClass()); - assertEquals("Boolean property not set correctly", Boolean.FALSE, event.getRestart()); + assertEquals(ShutdownEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals(Boolean.FALSE, event.getRestart(), "Boolean property not set correctly"); } - public void testBuildEventWithUnregisteredEvent() - { + @Test + void testBuildEventWithUnregisteredEvent() { ManagerEvent event; properties.put("event", "Nonexisting"); @@ -199,8 +213,8 @@ public void testBuildEventWithUnregisteredEvent() assertNull(event); } - public void testBuildEventWithEmptyAttributes() - { + @Test + void testBuildEventWithEmptyAttributes() { ManagerEvent event; event = eventBuilder.buildEvent(this, properties); @@ -208,8 +222,8 @@ public void testBuildEventWithEmptyAttributes() assertNull(event); } - public void testBuildEventWithResponseEvent() - { + @Test + void testBuildEventWithResponseEvent() { ManagerEvent event; properties.put("event", "StatusComplete"); @@ -217,12 +231,12 @@ public void testBuildEventWithResponseEvent() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", StatusCompleteEvent.class, event.getClass()); - assertEquals("ActionId not set correctly", "origId", ((ResponseEvent) event).getActionId()); + assertEquals(StatusCompleteEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals("origId", ((ResponseEvent) event).getActionId(), "ActionId not set correctly"); } - public void testBuildEventWithSourceProperty() - { + @Test + void testBuildEventWithSourceProperty() { ManagerEvent event; properties.put("event", "Cdr"); @@ -230,11 +244,23 @@ public void testBuildEventWithSourceProperty() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Src property not set correctly", "source value", ((CdrEvent) event).getSrc()); + assertEquals("source value", ((CdrEvent) event).getSrc(), "Src property not set correctly"); + } + + @Test + void testBuildEventWithClassProperty() { + ManagerEvent event; + + properties.put("event", "MusicOnHold"); + properties.put("class", "default"); + event = eventBuilder.buildEvent(this, properties); + + assertNotNull(event); + assertEquals("default", ((MusicOnHoldEvent) event).getClassName(), "ClassName property not set correctly"); } - public void testBuildEventWithSpecialCharacterProperty() - { + @Test + void testBuildEventWithSpecialCharacterProperty() { ManagerEvent event; properties.put("event", "Hangup"); @@ -242,11 +268,11 @@ public void testBuildEventWithSpecialCharacterProperty() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("CauseTxt property not set correctly", "some text", ((HangupEvent) event).getCauseTxt()); + assertEquals("some text", ((HangupEvent) event).getCauseTxt(), "CauseTxt property not set correctly"); } - public void testBuildEventWithCidCallingPres() - { + @Test + void testBuildEventWithCidCallingPres() { ManagerEvent event; properties.put("event", "Newcallerid"); @@ -254,14 +280,12 @@ public void testBuildEventWithCidCallingPres() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("CidCallingPres property not set correctly", Integer.valueOf(123), - ((NewCallerIdEvent) event).getCidCallingPres()); - assertEquals("CidCallingPresTxt property not set correctly", "nice description", - ((NewCallerIdEvent) event).getCidCallingPresTxt()); + assertEquals(Integer.valueOf(123), ((NewCallerIdEvent) event).getCidCallingPres(), "CidCallingPres property not set correctly"); + assertEquals("nice description", ((NewCallerIdEvent) event).getCidCallingPresTxt(), "CidCallingPresTxt property not set correctly"); } - public void testBuildEventWithCidCallingPresAndEmptyTxt() - { + @Test + void testBuildEventWithCidCallingPresAndEmptyTxt() { ManagerEvent event; properties.put("event", "Newcallerid"); @@ -269,14 +293,12 @@ public void testBuildEventWithCidCallingPresAndEmptyTxt() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("CidCallingPres property not set correctly", Integer.valueOf(123), - ((NewCallerIdEvent) event).getCidCallingPres()); - assertNull("CidCallingPresTxt property not set correctly (must be null)", - ((NewCallerIdEvent) event).getCidCallingPresTxt()); + assertEquals(Integer.valueOf(123), ((NewCallerIdEvent) event).getCidCallingPres(), "CidCallingPres property not set correctly"); + assertNull(((NewCallerIdEvent) event).getCidCallingPresTxt(), "CidCallingPresTxt property not set correctly (must be null)"); } - public void testBuildEventWithCidCallingPresAndMissingTxt() - { + @Test + void testBuildEventWithCidCallingPresAndMissingTxt() { ManagerEvent event; properties.put("event", "Newcallerid"); @@ -284,14 +306,12 @@ public void testBuildEventWithCidCallingPresAndMissingTxt() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("CidCallingPres property not set correctly", Integer.valueOf(123), - ((NewCallerIdEvent) event).getCidCallingPres()); - assertNull("CidCallingPresTxt property not set correctly (must be null)", - ((NewCallerIdEvent) event).getCidCallingPresTxt()); + assertEquals(Integer.valueOf(123), ((NewCallerIdEvent) event).getCidCallingPres(), "CidCallingPres property not set correctly"); + assertNull(((NewCallerIdEvent) event).getCidCallingPresTxt(), "CidCallingPresTxt property not set correctly (must be null)"); } - public void testBuildEventWithInvalidCidCallingPres() - { + @Test + void testBuildEventWithInvalidCidCallingPres() { ManagerEvent event; properties.put("event", "Newcallerid"); @@ -299,14 +319,12 @@ public void testBuildEventWithInvalidCidCallingPres() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertNull("CidCallingPres property not set correctly (must be null)", - ((NewCallerIdEvent) event).getCidCallingPres()); - assertNull("CidCallingPresTxt property not set correctly (must be null)", - ((NewCallerIdEvent) event).getCidCallingPresTxt()); + assertNull(((NewCallerIdEvent) event).getCidCallingPres(), "CidCallingPres property not set correctly (must be null)"); + assertNull(((NewCallerIdEvent) event).getCidCallingPresTxt(), "CidCallingPresTxt property not set correctly (must be null)"); } - public void testBuildEventWithReason() - { + @Test + void testBuildEventWithReason() { ManagerEvent event; properties.put("event", "LogChannel"); @@ -314,14 +332,12 @@ public void testBuildEventWithReason() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Reason property not set correctly", Integer.valueOf(123), - ((LogChannelEvent) event).getReason()); - assertEquals("ReasonTxt property not set correctly", "a reason", - ((LogChannelEvent) event).getReasonTxt()); + assertEquals(Integer.valueOf(123), ((LogChannelEvent) event).getReason(), "Reason property not set correctly"); + assertEquals("a reason", ((LogChannelEvent) event).getReasonTxt(), "ReasonTxt property not set correctly"); } - public void testBuildEventWithTimestamp() - { + @Test + void testBuildEventWithTimestamp() { ManagerEvent event; properties.put("event", "NewChannel"); @@ -329,11 +345,11 @@ public void testBuildEventWithTimestamp() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Timestamp property not set correctly", 1159310429.569108D, event.getTimestamp()); + assertEquals(1159310429.569108D, event.getTimestamp(), 0.0001, "Timestamp property not set correctly"); } - public void testBuildEventWithLong() - { + @Test + void testBuildEventWithLong() { ManagerEvent event; properties.put("event", "MeetmeLeave"); @@ -341,12 +357,11 @@ public void testBuildEventWithLong() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Duration property not set correctly", new Long(569108), - ((MeetMeLeaveEvent) event).getDuration()); + assertEquals(Long.valueOf(569108), ((MeetMeLeaveEvent) event).getDuration(), "Duration property not set correctly"); } - public void testBuildEventWithDouble() - { + @Test + void testBuildEventWithDouble() { ManagerEvent event; properties.put("event", "RTPReceiverStat"); @@ -354,12 +369,11 @@ public void testBuildEventWithDouble() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Transit property not set correctly", 12.3456, - ((RtpReceiverStatEvent) event).getTransit()); + assertEquals(12.3456, ((RtpReceiverStatEvent) event).getTransit(), 0.0001, "Transit property not set correctly"); } - public void testBuildEventWithNullLiteral() - { + @Test + void testBuildEventWithNullLiteral() { CdrEvent event; properties.put("event", "Cdr"); @@ -367,12 +381,12 @@ public void testBuildEventWithNullLiteral() event = (CdrEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", CdrEvent.class, event.getClass()); - assertNull("Property with value \"\" is not null", event.getChannel()); + assertEquals(CdrEvent.class, event.getClass(), "Returned event is of wrong type"); + assertNull(event.getChannel(), "Property with value \"\" is not null"); } - public void testBuildEventWithDashInPropertyName() - { + @Test + void testBuildEventWithDashInPropertyName() { TransferEvent event; properties.put("event", "Transfer"); @@ -380,12 +394,12 @@ public void testBuildEventWithDashInPropertyName() event = (TransferEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", TransferEvent.class, event.getClass()); - assertEquals("Property SIP-Callid is not set correctly", "12345", event.getSipCallId()); + assertEquals(TransferEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals("12345", event.getSipCallId(), "Property SIP-Callid is not set correctly"); } - public void testBuildEventForRtpReceiverStatEventAJ162() - { + @Test + void testBuildEventForRtpReceiverStatEventAJ162() { RtpReceiverStatEvent event; properties.put("event", "RtpReceiverStat"); @@ -394,12 +408,12 @@ public void testBuildEventForRtpReceiverStatEventAJ162() event = (RtpReceiverStatEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", RtpReceiverStatEvent.class, event.getClass()); - assertEquals("Property SSRC is not set correctly", 3776236237l, (long) event.getSsrc()); + assertEquals(RtpReceiverStatEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals(3776236237l, (long) event.getSsrc(), "Property SSRC is not set correctly"); } - public void testBuildEventForRtpReceiverStatEventAJ139() - { + @Test + void testBuildEventForRtpReceiverStatEventAJ139() { RtpReceiverStatEvent event; properties.put("event", "RtpReceiverStat"); @@ -407,12 +421,12 @@ public void testBuildEventForRtpReceiverStatEventAJ139() event = (RtpReceiverStatEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", RtpReceiverStatEvent.class, event.getClass()); - assertEquals("Property receivedPacket is not set correctly", 0, (long) event.getReceivedPackets()); + assertEquals(RtpReceiverStatEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals(0, (long) event.getReceivedPackets(), "Property receivedPacket is not set correctly"); } - public void testBuildEventWithMapProperty() - { + @Test + void testBuildEventWithMapProperty() { AgentCalledEvent event; properties.put("event", "AgentCalled"); @@ -420,14 +434,14 @@ public void testBuildEventWithMapProperty() event = (AgentCalledEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", AgentCalledEvent.class, event.getClass()); - assertEquals("Property variables[var1] is not set correctly", "val1", event.getVariables().get("var1")); - assertEquals("Property variables[var2] is not set correctly", "val2", event.getVariables().get("var2")); - assertEquals("Invalid size of variables property", 2, event.getVariables().size()); + assertEquals(AgentCalledEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals("val1", event.getVariables().get("var1"), "Property variables[var1] is not set correctly"); + assertEquals("val2", event.getVariables().get("var2"), "Property variables[var2] is not set correctly"); + assertEquals(2, event.getVariables().size(), "Invalid size of variables property"); } - public void testBuildEventWithMapPropertyAndOnlyOneEntry() - { + @Test + void testBuildEventWithMapPropertyAndOnlyOneEntry() { AgentCalledEvent event; properties.put("event", "AgentCalled"); @@ -435,13 +449,13 @@ public void testBuildEventWithMapPropertyAndOnlyOneEntry() event = (AgentCalledEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", AgentCalledEvent.class, event.getClass()); - assertEquals("Property variables[var1] is not set correctly", "val1", event.getVariables().get("var1")); - assertEquals("Invalid size of variables property", 1, event.getVariables().size()); + assertEquals(AgentCalledEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals("val1", event.getVariables().get("var1"), "Property variables[var1] is not set correctly"); + assertEquals(1, event.getVariables().size(), "Invalid size of variables property"); } - public void testBuildEventWithSpace() - { + @Test + void testBuildEventWithSpace() { T38FaxStatusEvent event; properties.put("event", "T38FaxStatus"); @@ -449,7 +463,49 @@ public void testBuildEventWithSpace() event = (T38FaxStatusEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", T38FaxStatusEvent.class, event.getClass()); - assertEquals("Property 'T38 Session Duration' is not set correctly", "120", event.getT38SessionDuration()); + assertEquals(T38FaxStatusEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals("120", event.getT38SessionDuration(), "Property 'T38 Session Duration' is not set correctly"); + } + + @Test + void testBuildEventWithPeerEntryEventList() { + PeersEvent event; + + properties.put("event", Arrays.asList("PeerEntry", "PeerEntry", "PeerEntry", "PeerlistComplete")); + properties.put("actionid", Arrays.asList("1378144905_4#123", "1378144905_4#123", "1378144905_4#123")); + properties.put("objectname", Arrays.asList("a101", "a102", "a103")); + properties.put("status", Arrays.asList("OK", "UNKNOWN", "LAGGED")); + properties.put("listitems", "3"); + event = (PeersEvent) eventBuilder.buildEvent(this, properties); + + assertNotNull(event); + assertEquals(PeersEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals("123", event.getActionId(), "ActionId is invalid"); + assertEquals("a101", event.getChildEvents().get(0).getObjectName(), "Property events[objectname] is not set correctly"); + assertEquals("OK", event.getChildEvents().get(0).getStatus(), "Property events[status] is not set correctly"); + assertEquals("a102", event.getChildEvents().get(1).getObjectName(), "Property events[objectname] is not set correctly"); + assertNull(event.getChildEvents().get(1).getStatus(), "UNKNOWN literal returns NULL status"); + assertEquals("a103", event.getChildEvents().get(2).getObjectName(), "Property events[objectname] is not set correctly"); + assertEquals("LAGGED", event.getChildEvents().get(2).getStatus(), "Property events[status] is not set correctly"); + assertEquals(3, event.getChildEvents().size(), "Invalid size of peers property"); + } + + @Test + void testBuildEventWithOnePeerEntryEventList() { + PeersEvent event; + + properties.put("event", Arrays.asList("PeerEntry", "PeerlistComplete")); + properties.put("actionid", "1378144905_4#123"); + properties.put("objectname", "a101"); + properties.put("status", "OK"); + properties.put("listitems", "1"); + event = (PeersEvent) eventBuilder.buildEvent(this, properties); + + assertNotNull(event); + assertEquals(PeersEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals("123", event.getActionId(), "ActionId is invalid"); + assertEquals("a101", event.getChildEvents().get(0).getObjectName(), "Property events[objectname] is not set correctly"); + assertEquals("OK", event.getChildEvents().get(0).getStatus(), "Property events[status] is not set correctly"); + assertEquals(1, event.getChildEvents().size(), "Invalid size of peers property"); } } diff --git a/src/test/java/org/asteriskjava/manager/internal/ManagerConnectionImplTest.java b/src/test/java/org/asteriskjava/manager/internal/ManagerConnectionImplTest.java index a39d71845..2565925a9 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ManagerConnectionImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ManagerConnectionImplTest.java @@ -16,23 +16,13 @@ */ package org.asteriskjava.manager.internal; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.manager.AuthenticationFailedException; import org.asteriskjava.manager.ManagerConnectionState; import org.asteriskjava.manager.ManagerEventListener; import org.asteriskjava.manager.TimeoutException; import org.asteriskjava.manager.action.CommandAction; +import org.asteriskjava.manager.action.CoreSettingsAction; import org.asteriskjava.manager.action.PingAction; import org.asteriskjava.manager.action.StatusAction; import org.asteriskjava.manager.event.ConnectEvent; @@ -41,55 +31,60 @@ import org.asteriskjava.manager.event.NewChannelEvent; import org.asteriskjava.manager.response.ManagerResponse; import org.asteriskjava.util.SocketConnectionFacade; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; -public class ManagerConnectionImplTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class ManagerConnectionImplTest { protected SocketConnectionFacade mockSocket; protected ManagerWriterMock mockWriter; protected ManagerReaderMock mockReader; protected MockedManagerConnectionImpl mc; - @Override - protected void setUp() throws Exception - { + @BeforeEach + void setUp() { mockWriter = new ManagerWriterMock(); mockWriter.setExpectedUsername("username"); // md5 sum of 12345password mockWriter.setExpectedKey("40b1b887502902a8ce61a16e44630f7c"); mockReader = new ManagerReaderMock(); - mockSocket = createMock(SocketConnectionFacade.class); + mockSocket = mock(SocketConnectionFacade.class); mc = new MockedManagerConnectionImpl(mockReader, mockWriter, mockSocket); mockWriter.setDispatcher(mc); } - public void testDefaultConstructor() - { - assertEquals("Invalid default hostname", "localhost", mc.getHostname()); - assertEquals("Invalid default port", 5038, mc.getPort()); + @Test + void testDefaultConstructor() { + assertEquals("localhost", mc.getHostname(), "Invalid default hostname"); + assertEquals(5038, mc.getPort(), "Invalid default port"); } - public void testRegisterUserEventClass() - { + @Test + void testRegisterUserEventClass() { ManagerReader managerReader; - managerReader = createMock(ManagerReader.class); + managerReader = mock(ManagerReader.class); managerReader.registerEventClass(MyUserEvent.class); - replay(managerReader); mc = new MockedManagerConnectionImpl(managerReader, mockWriter, mockSocket); mc.registerUserEventClass(MyUserEvent.class); - assertEquals("unexpected call to createSocket", 0, mc.createSocketCalls); - assertEquals("unexpected call to createWriter", 0, mc.createWriterCalls); - assertEquals("createReader not called 1 time", 1, mc.createReaderCalls); - - verify(managerReader); + assertEquals(0, mc.createSocketCalls, "unexpected call to createSocket"); + assertEquals(0, mc.createWriterCalls, "unexpected call to createWriter"); + assertEquals(1, mc.createReaderCalls, "createReader not called 1 time"); } - public void testLogin() throws Exception - { + @Test + void testLogin() throws Exception { MockedManagerEventListener listener; long startTime; long endTime; @@ -97,62 +92,56 @@ public void testLogin() throws Exception listener = new MockedManagerEventListener(); - replay(mockSocket); - mc.setUsername("username"); mc.setPassword("password"); mc.addEventListener(listener); mc.setDefaultResponseTimeout(5000); - + startTime = System.currentTimeMillis(); mc.login(); endTime = System.currentTimeMillis(); duration = endTime - startTime; - assertEquals("createSocket not called 1 time", 1, mc.createSocketCalls); - assertEquals("createWriter not called 1 time", 1, mc.createWriterCalls); - assertEquals("createReader not called 1 time", 1, mc.createReaderCalls); + assertEquals(1, mc.createSocketCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createWriterCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createReaderCalls, "createSocket not called 1 time"); - assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); - assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); - assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); - assertEquals("setSocket() not called 1 time", 1, mockReader.setSocketCalls); + assertEquals(1, mockWriter.challengeActionsSent, "challenge action not sent 1 time"); + assertEquals(1, mockWriter.loginActionsSent, "login action not sent 1 time"); + assertEquals(0, mockWriter.otherActionsSent, "unexpected other actions sent"); + assertEquals(1, mockReader.setSocketCalls, "setSocket() not called 1 time"); // Some time for the reader thread to be started. Otherwise run() might // not yet have been // called. - try - { + try { Thread.sleep(100); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { // ugly hack to make this work when the thread is interrupted coz a - // response has been received but the ManagerConnection was not yet + // response has been received but the ManagerConnection was not yet // sleeping Thread.sleep(100); } - assertEquals("run() not called 1 time", 1, mockReader.runCalls); - assertEquals("unexpected call to die()", 0, mockReader.dieCalls); + assertEquals(1, mockReader.runCalls, "run() not called 1 time"); + assertEquals(0, mockReader.dieCalls, "unexpected call to die()"); - assertEquals("state is not CONNECTED", ManagerConnectionState.CONNECTED, mc.getState()); + assertEquals(ManagerConnectionState.CONNECTED, mc.getState(), "state is not CONNECTED"); - assertEquals("must have handled exactly one events", 1, listener.eventsHandled.size()); -/* - assertTrue( - "first event handled must be a ProtocolIdentifierReceivedEvent", - listener.eventsHandled.get(0) instanceof ProtocolIdentifierReceivedEvent); -*/ - assertTrue("event handled must be a ConnectEvent", - listener.eventsHandled.get(0) instanceof ConnectEvent); - - verify(mockSocket); - assertTrue("login() took longer than 2 second, probably a notify error (duration was " + duration + " is msec)", duration <= 2000); + assertEquals(1, listener.eventsHandled.size(), "must have handled exactly one events"); + /* + * assertTrue( + * "first event handled must be a ProtocolIdentifierReceivedEvent", + * listener.eventsHandled.get(0) instanceof + * ProtocolIdentifierReceivedEvent); + */ + assertTrue(listener.eventsHandled.get(0) instanceof ConnectEvent, "event handled must be a ConnectEvent"); + + assertTrue(duration <= 2000, + "login() took longer than 2 second, probably a notify error (duration was " + duration + " is msec)"); } - public void testLoginIncorrectKey() throws Exception - { + @Test + void testLoginIncorrectKey() throws Exception { mockSocket.close(); - replay(mockSocket); mockWriter.setExpectedUsername("username"); // md5 sum of 12345password @@ -161,156 +150,128 @@ public void testLoginIncorrectKey() throws Exception mc.setUsername("username"); mc.setPassword("wrong password"); - try - { + try { mc.login(); fail("No AuthenticationFailedException thrown"); - } - catch (AuthenticationFailedException e) - { + } catch (AuthenticationFailedException e) { } - assertEquals("createSocket not called 1 time", 1, mc.createSocketCalls); - assertEquals("createWriter not called 1 time", 1, mc.createWriterCalls); - assertEquals("createReader not called 1 time", 1, mc.createReaderCalls); + assertEquals(1, mc.createSocketCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createWriterCalls, "createWriter not called 1 time"); + assertEquals(1, mc.createReaderCalls, "createReader not called 1 time"); - assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); - assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); - assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); - assertEquals("setSocket() not called 1 time", 1, mockReader.setSocketCalls); + assertEquals(1, mockWriter.challengeActionsSent, "challenge action not sent 1 time"); + assertEquals(1, mockWriter.loginActionsSent, "login action not sent 1 time"); + assertEquals(0, mockWriter.otherActionsSent, "unexpected other actions sent"); + assertEquals(1, mockReader.setSocketCalls, "setSocket() not called 1 time"); // Some time for the reader thread to be started. Otherwise run() might // not yet have been // called. - try - { + try { Thread.sleep(100); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { // ugly hack to make this work when the thread is interrupted coz a - // response has been received but the ManagerConnection was not yet + // response has been received but the ManagerConnection was not yet // sleeping Thread.sleep(100); } - assertEquals("run() not called 1 time", 1, mockReader.runCalls); - assertEquals("unexpected call to die()", 0, mockReader.dieCalls); - - verify(mockSocket); + assertEquals(1, mockReader.runCalls, "run() not called 1 time"); + assertEquals(0, mockReader.dieCalls, "unexpected call to die()"); } - public void testLoginIOExceptionOnConnect() throws Exception - { - replay(mockSocket); - + @Test + void testLoginIOExceptionOnConnect() throws Exception { mc.setThrowIOExceptionOnFirstSocketCreate(true); - try - { + try { mc.login(); fail("No IOException thrown"); + } catch (IOException e) { } - catch (IOException e) - { - } - - assertEquals("createSocket not called 1 time", 1, mc.createSocketCalls); - assertEquals("createWriter not called 1 time", 1, mc.createWriterCalls); - assertEquals("createReader not called 1 time", 1, mc.createReaderCalls); - assertEquals("unexpected challenge action sent", 0, mockWriter.challengeActionsSent); - assertEquals("unexpected login action sent", 0, mockWriter.loginActionsSent); - assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + assertEquals(1, mc.createSocketCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createWriterCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createReaderCalls, "createSocket not called 1 time"); - assertEquals("unexpected call to setSocket()", 0, mockReader.setSocketCalls); - assertEquals("unexpected call to run()", 0, mockReader.runCalls); - assertEquals("unexpected call to die()", 0, mockReader.dieCalls); + assertEquals(0, mockWriter.challengeActionsSent, "unexpected challenge action sent"); + assertEquals(0, mockWriter.loginActionsSent, "unexpected login action sent"); + assertEquals(0, mockWriter.otherActionsSent, "unexpected other actions sent"); - verify(mockSocket); + assertEquals(0, mockReader.setSocketCalls, "unexpected call to setSocket()"); + assertEquals(0, mockReader.runCalls, "unexpected call to run()"); + assertEquals(0, mockReader.dieCalls, "unexpected call to die()"); } - public void testLoginTimeoutOnConnect() throws Exception - { + @Test + void testLoginTimeoutOnConnect() throws Exception { mc.setDefaultResponseTimeout(50); mockSocket.close(); - replay(mockSocket); // provoke timeout mockWriter.setSendProtocolIdentifierReceivedEvent(false); - try - { + try { mc.login(); fail("No TimeoutException on login()"); - } - catch (TimeoutException e) - { + } catch (TimeoutException e) { assertEquals("Timeout waiting for protocol identifier", e.getMessage()); } - assertEquals("createSocket not called 1 time", 1, mc.createSocketCalls); - assertEquals("createWriter not called 1 time", 1, mc.createWriterCalls); - assertEquals("createReader not called 1 time", 1, mc.createReaderCalls); + assertEquals(1, mc.createSocketCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createWriterCalls, "createWriter not called 1 time"); + assertEquals(1, mc.createReaderCalls, "createReader not called 1 time"); - assertEquals("unexpected challenge action sent", 0, mockWriter.challengeActionsSent); - assertEquals("unexpected login action sent", 0, mockWriter.loginActionsSent); - assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + assertEquals(0, mockWriter.challengeActionsSent, "unexpected challenge action sent"); + assertEquals(0, mockWriter.loginActionsSent, "unexpected login action sent"); + assertEquals(0, mockWriter.otherActionsSent, "unexpected other actions sent"); - assertEquals("setSocket() not called 1 time", 1, mockReader.setSocketCalls); + assertEquals(1, mockReader.setSocketCalls, "setSocket() not called 1 time"); // Some time for the reader thread to be started. Otherwise run() might // not yet have been // called. Thread.sleep(10); - assertEquals("run() not called 1 time", 1, mockReader.runCalls); - assertEquals("unexpected call to die()", 0, mockReader.dieCalls); - - verify(mockSocket); + assertEquals(1, mockReader.runCalls, "run() not called 1 time"); + assertEquals(0, mockReader.dieCalls, "unexpected call to die()"); } - public void testLoginTimeoutOnChallengeAction() throws Exception - { + @Test + void testLoginTimeoutOnChallengeAction() throws Exception { mc.setDefaultResponseTimeout(200); mockSocket.close(); - replay(mockSocket); // provoke timeout mockWriter.setSendResponse(false); - try - { + try { mc.login(); fail("No TimeoutException on login()"); - } - catch (AuthenticationFailedException e) - { + } catch (AuthenticationFailedException e) { assertEquals("Unable to send challenge action", e.getMessage()); assertEquals("Timeout waiting for response to Challenge", e.getCause().getMessage()); assertTrue(e.getCause() instanceof TimeoutException); } - assertEquals("createSocket not called 1 time", 1, mc.createSocketCalls); - assertEquals("createWriter not called 1 time", 1, mc.createWriterCalls); - assertEquals("createReader not called 1 time", 1, mc.createReaderCalls); + assertEquals(1, mc.createSocketCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createWriterCalls, "createWriter not called 1 time"); + assertEquals(1, mc.createReaderCalls, "createReader not called 1 time"); - assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); - assertEquals("unexpected login action sent", 0, mockWriter.loginActionsSent); - assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + assertEquals(1, mockWriter.challengeActionsSent, "challenge action not sent 1 time"); + assertEquals(0, mockWriter.loginActionsSent, "unexpected login action sent"); + assertEquals(0, mockWriter.otherActionsSent, "unexpected other actions sent"); - assertEquals("setSocket() not called 1 time", 1, mockReader.setSocketCalls); + assertEquals(1, mockReader.setSocketCalls, "setSocket() not called 1 time"); // Some time for the reader thread to be started. Otherwise run() might // not yet have been // called. Thread.sleep(10); - assertEquals("run() not called 1 time", 1, mockReader.runCalls); - assertEquals("unexpected call to die()", 0, mockReader.dieCalls); - - verify(mockSocket); + assertEquals(1, mockReader.runCalls, "run() not called 1 time"); + assertEquals(0, mockReader.dieCalls, "unexpected call to die()"); } - public void testLogoffWhenConnected() throws Exception - { + @Test + void testLogoffWhenConnected() throws Exception { mockSocket.close(); - replay(mockSocket); // fake connect mc.connect(); @@ -318,61 +279,47 @@ public void testLogoffWhenConnected() throws Exception mc.logoff(); - assertEquals("logoff action not sent 1 time", 1, - mockWriter.logoffActionsSent); - verify(mockSocket); + assertEquals(1, mockWriter.logoffActionsSent, "logoff action not sent 1 time"); } - public void testLogoffWhenNotConnected() throws Exception - { - replay(mockSocket); - - try - { + @Test + void testLogoffWhenNotConnected() { + try { mc.logoff(); fail("Expected IllegalStateException when calling logoff when not connected"); - } - catch (IllegalStateException e) - { + } catch (IllegalStateException e) { // fine } - assertEquals("unexpected logoff action sent", 0, mockWriter.logoffActionsSent); - verify(mockSocket); + assertEquals(0, mockWriter.logoffActionsSent, "unexpected logoff action sent"); } - public void testSendActionWithNullAction() throws Exception - { + @Test + void testSendActionWithNullAction() throws Exception { // fake connect mc.connect(); - try - { + try { mc.sendAction(null); fail("No IllgealArgumentException thrown"); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { } } - public void testSendActionWhenNotConnected() throws Exception - { + @Test + void testSendActionWhenNotConnected() throws Exception { StatusAction statusAction; statusAction = new StatusAction(); - try - { + try { mc.sendAction(statusAction); fail("No IllegalStateException thrown"); - } - catch (IllegalStateException e) - { + } catch (IllegalStateException e) { } } - public void testSendAction() throws Exception - { + @Test + void testSendAction() throws Exception { StatusAction statusAction; ManagerResponse response; @@ -384,15 +331,15 @@ public void testSendAction() throws Exception mc.setState(ManagerConnectionState.CONNECTED); response = mc.sendAction(statusAction); - assertEquals("incorrect actionId in action", "123", statusAction.getActionId()); - assertEquals("incorrect actionId in response", "123", response.getActionId()); - assertEquals("incorrect response", "Success", response.getResponse()); + assertEquals("123", statusAction.getActionId(), "incorrect actionId in action"); + assertEquals("123", response.getActionId(), "incorrect actionId in response"); + assertEquals("Success", response.getResponse(), "incorrect response"); - assertEquals("other actions not sent 1 time", 1, mockWriter.otherActionsSent); + assertEquals(1, mockWriter.otherActionsSent, "other actions not sent 1 time"); } - public void testSendActionTimeout() throws Exception - { + @Test + void testSendActionTimeout() throws Exception { StatusAction statusAction; statusAction = new StatusAction(); @@ -405,20 +352,17 @@ public void testSendActionTimeout() throws Exception // provoke timeout mockWriter.setSendResponse(false); - try - { + try { mc.sendAction(statusAction); fail("No TimeoutException thrown"); - } - catch (TimeoutException e) - { + } catch (TimeoutException e) { } - assertEquals("other actions not sent 1 time", 1, mockWriter.otherActionsSent); + assertEquals(1, mockWriter.otherActionsSent, "other actions not sent 1 time"); } - public void testDispatchResponseUnexpectedResponse() - { + @Test + void testDispatchResponseUnexpectedResponse() { ManagerResponse response; response = new ManagerResponse(); @@ -427,11 +371,11 @@ public void testDispatchResponseUnexpectedResponse() response.setResponse("Success"); // expected result is ignoring the response and logging - mc.dispatchResponse(response); + mc.dispatchResponse(response, null); } - public void testDispatchResponseMissingInternalActionId() - { + @Test + void testDispatchResponseMissingInternalActionId() { ManagerResponse response; response = new ManagerResponse(); @@ -439,11 +383,11 @@ public void testDispatchResponseMissingInternalActionId() response.setResponse("Success"); // expected result is ignoring the response and logging - mc.dispatchResponse(response); + mc.dispatchResponse(response, null); } - public void testDispatchResponseNullActionId() - { + @Test + void testDispatchResponseNullActionId() { ManagerResponse response; response = new ManagerResponse(); @@ -451,20 +395,19 @@ public void testDispatchResponseNullActionId() response.setResponse("Success"); // expected result is ignoring the response and logging - mc.dispatchResponse(response); + mc.dispatchResponse(response, null); } - public void testDispatchResponseNullResponse() - { + @Test + void testDispatchResponseNullResponse() { // expected result is ignoring and logging - mc.dispatchResponse(null); + mc.dispatchResponse(null, null); } - public void testReconnect() throws Exception - { + @Test + void testReconnect() throws Exception { DisconnectEvent disconnectEvent; - replay(mockSocket); disconnectEvent = new DisconnectEvent(this); // fake successful login @@ -473,29 +416,26 @@ public void testReconnect() throws Exception mc.setUsername("username"); mc.setPassword("password"); - mc.dispatchEvent(disconnectEvent); - + mc.dispatchEvent(disconnectEvent, null); + // wait for reconnect thread to do its work Thread.sleep(1000); - assertEquals("createSocket not called 1 time", 1, mc.createSocketCalls); - assertEquals("createWriter not called 1 time", 1, mc.createWriterCalls); - assertEquals("createReader not called 1 time", 1, mc.createReaderCalls); + assertEquals(1, mc.createSocketCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createWriterCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createReaderCalls, "createSocket not called 1 time"); - assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); - assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); - assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + assertEquals(1, mockWriter.challengeActionsSent, "challenge action not sent 1 time"); + assertEquals(1, mockWriter.loginActionsSent, "login action not sent 1 time"); + assertEquals(0, mockWriter.otherActionsSent, "unexpected other actions sent"); - assertEquals("state is not CONNECTED", ManagerConnectionState.CONNECTED, mc.getState()); - - verify(mockSocket); + assertEquals(ManagerConnectionState.CONNECTED, mc.getState(), "state is not CONNECTED"); } - public void testReconnectWithIOException() throws Exception - { + @Test + void testReconnectWithIOException() throws Exception { DisconnectEvent disconnectEvent; - replay(mockSocket); disconnectEvent = new DisconnectEvent(this); // fake successful login @@ -506,31 +446,27 @@ public void testReconnectWithIOException() throws Exception mc.setUsername("username"); mc.setPassword("password"); - mc.dispatchEvent(disconnectEvent); + mc.dispatchEvent(disconnectEvent, null); // wait for reconnect thread to do its work Thread.sleep(1000); + assertEquals(2, mc.createSocketCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createWriterCalls, "createSocket not called 1 time"); + assertEquals(1, mc.createReaderCalls, "createSocket not called 1 time"); - assertEquals("createSocket not called 1 time", 2, mc.createSocketCalls); - assertEquals("createWriter not called 1 time", 1, mc.createWriterCalls); - assertEquals("createReader not called 1 time", 1, mc.createReaderCalls); - - assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); - assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); - assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + assertEquals(1, mockWriter.challengeActionsSent, "challenge action not sent 1 time"); + assertEquals(1, mockWriter.loginActionsSent, "login action not sent 1 time"); + assertEquals(0, mockWriter.otherActionsSent, "unexpected other actions sent"); - assertEquals("state is not CONNECTED", ManagerConnectionState.CONNECTED, mc.getState()); + assertEquals(ManagerConnectionState.CONNECTED, mc.getState(), "state is not CONNECTED"); - verify(mockSocket); } - - public void testReconnectWithTimeoutException() throws Exception - { + @Test + void testReconnectWithTimeoutException() throws Exception { DisconnectEvent disconnectEvent; mockSocket.close(); - replay(mockSocket); disconnectEvent = new DisconnectEvent(this); // fake successful login @@ -541,80 +477,65 @@ public void testReconnectWithTimeoutException() throws Exception mc.setUsername("username"); mc.setPassword("password"); - mc.dispatchEvent(disconnectEvent); + mc.dispatchEvent(disconnectEvent, null); // wait for reconnect thread to do its work Thread.sleep(1000); - assertEquals("createSocket not called 2 time", 2, mc.createSocketCalls); - assertEquals("createWriter not called 1 time", 1, mc.createWriterCalls); - assertEquals("createReader not called 1 time", 1, mc.createReaderCalls); - - assertEquals("challenge action not sent 1 time", 1, mockWriter.challengeActionsSent); - assertEquals("login action not sent 1 time", 1, mockWriter.loginActionsSent); - assertEquals("unexpected other actions sent", 0, mockWriter.otherActionsSent); + assertEquals(2, mc.createSocketCalls, "createSocket not called 2 time"); + assertEquals(1, mc.createWriterCalls, "createWriter not called 1 time"); + assertEquals(1, mc.createReaderCalls, "createWriter not called 1 time"); - assertEquals("state is not CONNECTED", ManagerConnectionState.CONNECTED, mc.getState()); + assertEquals(1, mockWriter.challengeActionsSent, "challenge action not sent 1 time"); + assertEquals(1, mockWriter.loginActionsSent, "login action not sent 1 time"); + assertEquals(0, mockWriter.otherActionsSent, "unexpected other actions sent"); - verify(mockSocket); + assertEquals(ManagerConnectionState.CONNECTED, mc.getState(), "state is not CONNECTED"); } @SuppressWarnings("unchecked") - public void testDispatchEventWithMultipleEventHandlers() - { + @Test + void testDispatchEventWithMultipleEventHandlers() { final int count = 20; ManagerEvent event; final List list; // verify that event handlers are called in the correct order event = new NewChannelEvent(this); - list = createMock(List.class); - for (int i = 0; i < count; i++) - { + list = mock(List.class); + for (int i = 0; i < count; i++) { final int index = i; - expect(list.add(index)).andReturn(true); - mc.addEventListener(new ManagerEventListener() - { - public void onManagerEvent(ManagerEvent event) - { + when(list.add(index)).thenReturn(true); + mc.addEventListener(new ManagerEventListener() { + public void onManagerEvent(ManagerEvent event) { list.add(index); } }); } - replay(list); - mc.dispatchEvent(event); - verify(list); + mc.dispatchEvent(event, null); } - public void testIsShowVersionCommandAction() - { - assertTrue(mc.isShowVersionCommandAction(new CommandAction("show version"))); + @Test + void testIsShowVersionCommandAction() { + assertTrue(mc.isShowVersionCommandAction(new CoreSettingsAction())); assertTrue(mc.isShowVersionCommandAction(new CommandAction("core show version"))); - assertTrue(mc.isShowVersionCommandAction(new CommandAction("core show version foo bar"))); - assertFalse(mc.isShowVersionCommandAction(new CommandAction("foo show version"))); assertFalse(mc.isShowVersionCommandAction(new PingAction())); } - private class MockedManagerEventListener implements ManagerEventListener - { + private class MockedManagerEventListener implements ManagerEventListener { List eventsHandled; - public MockedManagerEventListener() - { + public MockedManagerEventListener() { this.eventsHandled = new ArrayList(); } - public void onManagerEvent(ManagerEvent event) - { + public void onManagerEvent(ManagerEvent event) { eventsHandled.add(event); } } - private class MockedManagerConnectionImpl - extends - ManagerConnectionImpl - { + private class MockedManagerConnectionImpl extends ManagerConnectionImpl { ManagerReader mockReader; ManagerWriter mockWriter; SocketConnectionFacade mockSocket; @@ -625,88 +546,75 @@ private class MockedManagerConnectionImpl public int createReaderCalls = 0; public int createWriterCalls = 0; public int createSocketCalls = 0; - + public int loginCalls = 0; - public MockedManagerConnectionImpl(ManagerReader mockReader, - ManagerWriter mockWriter, SocketConnectionFacade mockSocket) - { + public MockedManagerConnectionImpl(ManagerReader mockReader, ManagerWriter mockWriter, + SocketConnectionFacade mockSocket) { super(); this.mockReader = mockReader; this.mockWriter = mockWriter; this.mockSocket = mockSocket; } - public void setThrowTimeoutExceptionOnFirstLogin(boolean b) - { + void setThrowTimeoutExceptionOnFirstLogin(boolean b) { this.throwTimeoutExceptionOnFirstLogin = b; } - public void setThrowIOExceptionOnFirstSocketCreate(boolean b) - { + void setThrowIOExceptionOnFirstSocketCreate(boolean b) { this.throwIOExceptionOnFirstSocketCreate = b; } @Override - public String getUsername() - { + public String getUsername() { return username; } @Override - public String getPassword() - { + public String getPassword() { return password; } - public void setState(ManagerConnectionState state) - { + void setState(ManagerConnectionState state) { this.state = state; } @Override - protected ManagerReader createReader(Dispatcher d, Object source) - { + protected ManagerReader createReader(Dispatcher d, Object source) { createReaderCalls++; return mockReader; } @Override - protected ManagerWriter createWriter() - { + protected ManagerWriter createWriter() { createWriterCalls++; return mockWriter; } @Override - protected SocketConnectionFacade createSocket() throws IOException - { + protected SocketConnectionFacade createSocket() throws IOException { createSocketCalls++; - if (throwIOExceptionOnFirstSocketCreate && createSocketCalls == 1) - { + if (throwIOExceptionOnFirstSocketCreate && createSocketCalls == 1) { throw new IOException(); } return mockSocket; } - + @Override - protected void doLogin(long timeout, String events) throws IOException, - AuthenticationFailedException, TimeoutException - { + protected synchronized void doLogin(long timeout, String events) + throws IOException, AuthenticationFailedException, TimeoutException { loginCalls++; - if (throwTimeoutExceptionOnFirstLogin && loginCalls == 1) - { + if (throwTimeoutExceptionOnFirstLogin && loginCalls == 1) { disconnect(); throw new TimeoutException("Provoked timeout"); } super.doLogin(timeout, events); } - + @Override - protected AsteriskVersion determineVersion() - { + protected AsteriskVersion determineVersion() { return null; } } diff --git a/src/test/java/org/asteriskjava/manager/internal/ManagerReaderImplTest.java b/src/test/java/org/asteriskjava/manager/internal/ManagerReaderImplTest.java index 3ec86f1ac..22bbb9f23 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ManagerReaderImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ManagerReaderImplTest.java @@ -16,360 +16,256 @@ */ package org.asteriskjava.manager.internal; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; +import org.asteriskjava.manager.event.*; +import org.asteriskjava.manager.response.CommandResponse; +import org.asteriskjava.manager.response.ManagerResponse; +import org.asteriskjava.util.DateUtil; +import org.asteriskjava.util.SocketConnectionFacade; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; -import junit.framework.TestCase; - -import org.asteriskjava.manager.event.*; -import org.asteriskjava.manager.response.CommandResponse; -import org.asteriskjava.manager.response.ManagerResponse; -import org.asteriskjava.util.DateUtil; -import org.asteriskjava.util.SocketConnectionFacade; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class ManagerReaderImplTest extends TestCase -{ +class ManagerReaderImplTest { private Date now; private MockedDispatcher dispatcher; private SocketConnectionFacade socketConnectionFacade; private ManagerReader managerReader; - @Override - protected void setUp() - { + @BeforeEach + void setUp() { now = new Date(); DateUtil.overrideCurrentDate(now); dispatcher = new MockedDispatcher(); managerReader = new ManagerReaderImpl(dispatcher, this); - socketConnectionFacade = createMock(SocketConnectionFacade.class); + socketConnectionFacade = mock(SocketConnectionFacade.class); } - @Override - protected void tearDown() - { + @AfterEach + void tearDown() { DateUtil.overrideCurrentDate(null); } - public void testRunWithoutSocket() throws Exception - { - try - { + @Test + void testRunWithoutSocket() { + try { managerReader.run(); fail("Must throw IllegalStateException"); - } - catch (IllegalStateException e) - { - assertTrue("Exception must be of type IllegalStateException", - e instanceof IllegalStateException); + } catch (IllegalStateException e) { + assertTrue(e instanceof IllegalStateException, "Exception must be of type IllegalStateException"); } } - public void testRunReceivingProtocolIdentifier() throws Exception - { - expect(socketConnectionFacade.readLine()).andReturn("Asterisk Call Manager/1.0"); - expect(socketConnectionFacade.readLine()).andReturn(null); - - replay(socketConnectionFacade); + @Test + void testRunReceivingProtocolIdentifier() throws Exception { + when(socketConnectionFacade.readLine()) + .thenReturn("Asterisk Call Manager/1.0") + .thenReturn(null); managerReader.setSocket(socketConnectionFacade); managerReader.run(); - verify(socketConnectionFacade); - - assertEquals("not exactly two events dispatched", 2, - dispatcher.dispatchedEvents.size()); + assertEquals(2, dispatcher.dispatchedEvents.size(), "not exactly two events dispatched"); - assertEquals("first event must be a ProtocolIdentifierReceivedEvent", - ProtocolIdentifierReceivedEvent.class, - dispatcher.dispatchedEvents.get(0).getClass()); + assertEquals(ProtocolIdentifierReceivedEvent.class, dispatcher.dispatchedEvents.get(0).getClass(), "first event must be a ProtocolIdentifierReceivedEvent"); - assertEquals("ProtocolIdentifierReceivedEvent contains incorrect protocol identifier", - "Asterisk Call Manager/1.0", - ((ProtocolIdentifierReceivedEvent) dispatcher.dispatchedEvents.get(0)).getProtocolIdentifier()); + assertEquals("Asterisk Call Manager/1.0", ((ProtocolIdentifierReceivedEvent) dispatcher.dispatchedEvents.get(0)).getProtocolIdentifier(), "ProtocolIdentifierReceivedEvent contains incorrect protocol identifier"); - assertEquals("ProtocolIdentifierReceivedEvent contains incorrect dateReceived", now, - dispatcher.dispatchedEvents.get(0).getDateReceived()); + assertEquals(now, dispatcher.dispatchedEvents.get(0).getDateReceived(), "ProtocolIdentifierReceivedEvent contains incorrect dateReceived"); + assertEquals(DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass(), "second event must be a DisconnectEvent"); - assertEquals("second event must be a DisconnectEvent", - DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass()); - - assertEquals("DisconnectEvent contains incorrect dateReceived", now, - dispatcher.dispatchedEvents.get(1).getDateReceived()); + assertEquals(now, dispatcher.dispatchedEvents.get(1).getDateReceived(), "DisconnectEvent contains incorrect dateReceived"); } - public void testRunReceivingEvent() throws Exception - { - expect(socketConnectionFacade.readLine()).andReturn("Event: StatusComplete"); - expect(socketConnectionFacade.readLine()).andReturn(""); - expect(socketConnectionFacade.readLine()).andReturn(null); - - replay(socketConnectionFacade); + @Test + void testRunReceivingEvent() throws Exception { + when(socketConnectionFacade.readLine()) + .thenReturn("Event: StatusComplete") + .thenReturn("") + .thenReturn(null); managerReader.setSocket(socketConnectionFacade); managerReader.run(); - verify(socketConnectionFacade); - - assertEquals("not exactly two events dispatched", 2, - dispatcher.dispatchedEvents.size()); + assertEquals(2, dispatcher.dispatchedEvents.size(), "not exactly two events dispatched"); - assertEquals("first event must be a StatusCompleteEvent", - StatusCompleteEvent.class, dispatcher.dispatchedEvents.get(0).getClass()); - - assertEquals("second event must be a DisconnectEvent", - DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass()); + assertEquals(StatusCompleteEvent.class, dispatcher.dispatchedEvents.get(0).getClass(), "first event must be a StatusCompleteEvent"); + assertEquals(DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass(), "second event must be a DisconnectEvent"); } - public void testRunReceivingEventWithMapProperty() throws Exception - { - expect(socketConnectionFacade.readLine()).andReturn("Event: AgentCalled"); - expect(socketConnectionFacade.readLine()).andReturn("Variable: var1=val1"); - expect(socketConnectionFacade.readLine()).andReturn("Variable: var2=val2"); - expect(socketConnectionFacade.readLine()).andReturn(""); - expect(socketConnectionFacade.readLine()).andReturn(null); - - replay(socketConnectionFacade); + @Test + void testRunReceivingEventWithMapProperty() throws Exception { + when(socketConnectionFacade.readLine()) + .thenReturn("Event: AgentCalled") + .thenReturn("Variable: var1=val1") + .thenReturn("Variable: var2=val2") + .thenReturn("") + .thenReturn(null); managerReader.setSocket(socketConnectionFacade); managerReader.run(); - verify(socketConnectionFacade); - - assertEquals("not exactly two events dispatched", 2, - dispatcher.dispatchedEvents.size()); + assertEquals(2, dispatcher.dispatchedEvents.size(), "not exactly two events dispatched"); - assertEquals("first event must be a AgentCalledEvent", - AgentCalledEvent.class, dispatcher.dispatchedEvents.get(0).getClass()); + assertEquals(AgentCalledEvent.class, dispatcher.dispatchedEvents.get(0).getClass(), "first event must be a AgentCalledEvent"); AgentCalledEvent event = (AgentCalledEvent) dispatcher.dispatchedEvents.get(0); - assertEquals("Returned event is of wrong type", AgentCalledEvent.class, event.getClass()); - assertEquals("Property variables[var1] is not set correctly", "val1", event.getVariables().get("var1")); - assertEquals("Property variables[var2] is not set correctly", "val2", event.getVariables().get("var2")); - assertEquals("Invalid size of variables property", 2, event.getVariables().size()); + assertEquals(AgentCalledEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals("val1", event.getVariables().get("var1"), "Property variables[var1] is not set correctly"); + assertEquals("val2", event.getVariables().get("var2"), "Property variables[var2] is not set correctly"); + assertEquals(2, event.getVariables().size(), "Invalid size of variables property"); - assertEquals("second event must be an DisconnectEvent", - DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass()); + assertEquals(DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass(), "second event must be an DisconnectEvent"); } - public void testRunReceivingEventWithMapPropertyAndOnlyOneEntry() throws Exception - { - expect(socketConnectionFacade.readLine()).andReturn("Event: AgentCalled"); - expect(socketConnectionFacade.readLine()).andReturn("Variable: var1=val1"); - expect(socketConnectionFacade.readLine()).andReturn(""); - expect(socketConnectionFacade.readLine()).andReturn(null); - - replay(socketConnectionFacade); + @Test + void testRunReceivingEventWithMapPropertyAndOnlyOneEntry() throws Exception { + when(socketConnectionFacade.readLine()) + .thenReturn("Event: AgentCalled") + .thenReturn("Variable: var1=val1") + .thenReturn("") + .thenReturn(null); managerReader.setSocket(socketConnectionFacade); managerReader.run(); - verify(socketConnectionFacade); - - assertEquals("not exactly two events dispatched", 2, - dispatcher.dispatchedEvents.size()); + assertEquals(2, dispatcher.dispatchedEvents.size(), "not exactly two events dispatched"); - assertEquals("first event must be a AgentCalledEvent", - AgentCalledEvent.class, dispatcher.dispatchedEvents.get(0).getClass()); + assertEquals(AgentCalledEvent.class, dispatcher.dispatchedEvents.get(0).getClass(), "first event must be a AgentCalledEvent"); AgentCalledEvent event = (AgentCalledEvent) dispatcher.dispatchedEvents.get(0); - assertEquals("Returned event is of wrong type", AgentCalledEvent.class, event.getClass()); - assertEquals("Property variables[var1] is not set correctly", "val1", event.getVariables().get("var1")); - assertEquals("Invalid size of variables property", 1, event.getVariables().size()); + assertEquals(AgentCalledEvent.class, event.getClass(), "Returned event is of wrong type"); + assertEquals("val1", event.getVariables().get("var1"), "Property variables[var1] is not set correctly"); + assertEquals(1, event.getVariables().size(), "Invalid size of variables property"); - assertEquals("second event must be an DisconnectEvent", - DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass()); - } - - public void testWorkaroundForAsteriskBug13319() throws Exception - { - expect(socketConnectionFacade.readLine()).andReturn("Event: RTCPReceived"); - expect(socketConnectionFacade.readLine()).andReturn("From 192.168.0.1:1234"); - expect(socketConnectionFacade.readLine()).andReturn("HighestSequence: 999"); - expect(socketConnectionFacade.readLine()).andReturn(""); - expect(socketConnectionFacade.readLine()).andReturn(null); - - replay(socketConnectionFacade); - - managerReader.setSocket(socketConnectionFacade); - managerReader.run(); - - verify(socketConnectionFacade); - - assertEquals("not exactly two events dispatched", 2, - dispatcher.dispatchedEvents.size()); - - assertEquals("first event must be a RtcpReceivedEvent", - RtcpReceivedEvent.class, dispatcher.dispatchedEvents.get(0).getClass()); - - RtcpReceivedEvent rtcpReceivedEvent = (RtcpReceivedEvent) dispatcher.dispatchedEvents.get(0); - assertEquals("Invalid from address on RtcpReceivedEvent", "192.168.0.1", rtcpReceivedEvent.getFromAddress().getHostAddress()); - assertEquals("Invalid from port on RtcpReceivedEvent", new Integer(1234), rtcpReceivedEvent.getFromPort()); - assertEquals("Invalid highest sequence on RtcpReceivedEvent", new Long(999), rtcpReceivedEvent.getHighestSequence()); - - assertEquals("second event must be a DisconnectEvent", - DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass()); + assertEquals(DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass(), "second event must be an DisconnectEvent"); } // todo fix testRunReceivingUserEvent - public void XtestRunReceivingUserEvent() throws Exception - { + void XtestRunReceivingUserEvent() throws Exception { managerReader.registerEventClass(MyUserEvent.class); - expect(socketConnectionFacade.readLine()).andReturn("Event: MyUser"); - expect(socketConnectionFacade.readLine()).andReturn(""); - expect(socketConnectionFacade.readLine()).andReturn(null); - - replay(socketConnectionFacade); + when(socketConnectionFacade.readLine()) + .thenReturn("Event: MyUser") + .thenReturn("") + .thenReturn(null); managerReader.setSocket(socketConnectionFacade); managerReader.run(); - verify(socketConnectionFacade); + assertEquals(2, dispatcher.dispatchedEvents.size(), "not exactly two events dispatched"); - assertEquals("not exactly two events dispatched", 2, - dispatcher.dispatchedEvents.size()); + assertEquals(MyUserEvent.class, dispatcher.dispatchedEvents.get(0).getClass(), "first event must be a MyUserEvent"); - assertEquals("first event must be a MyUserEvent", MyUserEvent.class, - dispatcher.dispatchedEvents.get(0).getClass()); + assertEquals(DisconnectEvent.class, dispatcher.dispatchedEvents.get(1).getClass(), "second event must be a DisconnectEvent"); - assertEquals("second event must be a DisconnectEvent", - DisconnectEvent.class, dispatcher.dispatchedEvents.get(1) - .getClass()); } - public void testRunReceivingResponse() throws Exception - { - expect(socketConnectionFacade.readLine()).andReturn("Response: Success"); - expect(socketConnectionFacade.readLine()).andReturn("Message: Authentication accepted"); - expect(socketConnectionFacade.readLine()).andReturn(""); - expect(socketConnectionFacade.readLine()).andReturn(null); - - replay(socketConnectionFacade); + @Test + void testRunReceivingResponse() throws Exception { + when(socketConnectionFacade.readLine()) + .thenReturn("Response: Success") + .thenReturn("Message: Authentication accepted") + .thenReturn("") + .thenReturn(null); managerReader.setSocket(socketConnectionFacade); managerReader.run(); - verify(socketConnectionFacade); - - assertEquals("not exactly one response dispatched", 1, - dispatcher.dispatchedResponses.size()); + assertEquals(1, dispatcher.dispatchedResponses.size(), "not exactly one response dispatched"); - assertEquals("first response must be a ManagerResponse", - ManagerResponse.class, dispatcher.dispatchedResponses.get(0).getClass()); + assertEquals(ManagerResponse.class, dispatcher.dispatchedResponses.get(0).getClass(), "first response must be a ManagerResponse"); + assertEquals("Success", dispatcher.dispatchedResponses.get(0).getResponse(), "ManagerResponse contains incorrect response"); - assertEquals("ManagerResponse contains incorrect response", "Success", - dispatcher.dispatchedResponses.get(0).getResponse()); + assertEquals("Authentication accepted", dispatcher.dispatchedResponses.get(0).getMessage(), "ManagerResponse contains incorrect message"); - assertEquals("ManagerResponse contains incorrect message", - "Authentication accepted", - dispatcher.dispatchedResponses.get(0).getMessage()); + assertEquals("Authentication accepted", dispatcher.dispatchedResponses.get(0).getAttribute("MESSAGE"), "ManagerResponse contains incorrect message (via getAttribute)"); - assertEquals("ManagerResponse contains incorrect message (via getAttribute)", - "Authentication accepted", - dispatcher.dispatchedResponses.get(0).getAttribute("MESSAGE")); + assertEquals(now, dispatcher.dispatchedResponses.get(0).getDateReceived(), "ManagerResponse contains incorrect dateReceived"); - assertEquals("ManagerResponse contains incorrect dateReceived", now, - dispatcher.dispatchedResponses.get(0).getDateReceived()); + assertEquals(1, dispatcher.dispatchedEvents.size(), "not exactly one events dispatched"); - assertEquals("not exactly one events dispatched", 1, - dispatcher.dispatchedEvents.size()); - - assertEquals("first event must be a DisconnectEvent", - DisconnectEvent.class, dispatcher.dispatchedEvents.get(0).getClass()); + assertEquals(DisconnectEvent.class, dispatcher.dispatchedEvents.get(0).getClass(), "first event must be a DisconnectEvent"); } - public void testRunReceivingCommandResponse() throws Exception - { + @Test + void testRunReceivingCommandResponse() throws Exception { List result = new ArrayList(); - expect(socketConnectionFacade.readLine()).andReturn("Response: Follows"); - expect(socketConnectionFacade.readLine()).andReturn("ActionID: 678#12345"); - expect(socketConnectionFacade.readLine()).andReturn("Line1\nLine2\n--END COMMAND--"); - expect(socketConnectionFacade.readLine()).andReturn(""); - expect(socketConnectionFacade.readLine()).andReturn(null); + when(socketConnectionFacade.readLine()) + .thenReturn("Response: Follows") + .thenReturn("ActionID: 678#12345") + .thenReturn("Line1\nLine2\n--END COMMAND--") + .thenReturn("") + .thenReturn(null); result.add("Line1"); result.add("Line2"); - replay(socketConnectionFacade); - managerReader.setSocket(socketConnectionFacade); managerReader.expectResponseClass("678", CommandResponse.class); managerReader.run(); - verify(socketConnectionFacade); + assertEquals(1, dispatcher.dispatchedResponses.size(), "not exactly one response dispatched"); - assertEquals("not exactly one response dispatched", 1, - dispatcher.dispatchedResponses.size()); + assertEquals(CommandResponse.class, dispatcher.dispatchedResponses.get(0).getClass(), "first response must be a CommandResponse"); - assertEquals("first response must be a CommandResponse", - CommandResponse.class, dispatcher.dispatchedResponses.get(0).getClass()); + assertEquals("Follows", dispatcher.dispatchedResponses.get(0).getResponse(), "CommandResponse contains incorrect response"); - assertEquals("CommandResponse contains incorrect response", "Follows", - dispatcher.dispatchedResponses.get(0).getResponse()); + assertEquals("678#12345", dispatcher.dispatchedResponses.get(0).getActionId(), "CommandResponse contains incorrect actionId"); - assertEquals("CommandResponse contains incorrect actionId", "678#12345", - dispatcher.dispatchedResponses.get(0).getActionId()); + assertEquals("678#12345", dispatcher.dispatchedResponses.get(0).getAttribute("actionId"), "CommandResponse contains incorrect actionId (via getAttribute)"); - assertEquals("CommandResponse contains incorrect actionId (via getAttribute)", "678#12345", - dispatcher.dispatchedResponses.get(0).getAttribute("actionId")); + assertEquals(result, ((CommandResponse) dispatcher.dispatchedResponses.get(0)).getResult(), "CommandResponse contains incorrect result"); - assertEquals("CommandResponse contains incorrect result", result, - ((CommandResponse) dispatcher.dispatchedResponses.get(0)).getResult()); - - assertEquals("CommandResponse contains incorrect dateReceived", now, - dispatcher.dispatchedResponses.get(0).getDateReceived()); + assertEquals(now, dispatcher.dispatchedResponses.get(0).getDateReceived(), "CommandResponse contains incorrect dateReceived"); } - public void testRunCatchingIOException() throws Exception - { - expect(socketConnectionFacade.readLine()).andThrow(new IOException("Something happened to the network...")); - - replay(socketConnectionFacade); + @Test + void testRunCatchingIOException() throws Exception { + when(socketConnectionFacade.readLine()).thenThrow(new IOException("Something happened to the network...")); managerReader.setSocket(socketConnectionFacade); managerReader.run(); - verify(socketConnectionFacade); - - assertEquals("must not dispatch a response", 0, - dispatcher.dispatchedResponses.size()); + assertEquals(0, dispatcher.dispatchedResponses.size(), "must not dispatch a response"); - assertEquals("not exactly one events dispatched", 1, - dispatcher.dispatchedEvents.size()); + assertEquals(1, dispatcher.dispatchedEvents.size(), "not exactly one events dispatched"); - assertEquals("first event must be a DisconnectEvent", - DisconnectEvent.class, dispatcher.dispatchedEvents.get(0) - .getClass()); + assertEquals(DisconnectEvent.class, dispatcher.dispatchedEvents.get(0).getClass(), "first event must be a DisconnectEvent"); } - private class MockedDispatcher implements Dispatcher - { + private class MockedDispatcher implements Dispatcher { List dispatchedEvents; List dispatchedResponses; - public MockedDispatcher() - { + public MockedDispatcher() { this.dispatchedEvents = new ArrayList(); this.dispatchedResponses = new ArrayList(); } - public void dispatchResponse(ManagerResponse response) - { + @Override + public void dispatchResponse(ManagerResponse response, Integer requiredHandlingTime) { dispatchedResponses.add(response); } - public void dispatchEvent(ManagerEvent event) - { + @Override + public void dispatchEvent(ManagerEvent event, Integer requiredHandlingTime) { dispatchedEvents.add(event); } + + @Override + public void stop() { + // NO_OP + } } } diff --git a/src/test/java/org/asteriskjava/manager/internal/ManagerReaderMock.java b/src/test/java/org/asteriskjava/manager/internal/ManagerReaderMock.java index 4cb4763a8..e4bc3332b 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ManagerReaderMock.java +++ b/src/test/java/org/asteriskjava/manager/internal/ManagerReaderMock.java @@ -16,56 +16,51 @@ */ package org.asteriskjava.manager.internal; -import java.io.IOException; - -import org.asteriskjava.manager.internal.ManagerReader; -import org.asteriskjava.manager.response.ManagerResponse; import org.asteriskjava.manager.event.ManagerEvent; +import org.asteriskjava.manager.response.ManagerResponse; import org.asteriskjava.util.SocketConnectionFacade; -public class ManagerReaderMock implements ManagerReader -{ +import java.io.IOException; + +public class ManagerReaderMock implements ManagerReader { public int setSocketCalls = 0; public int dieCalls = 0; public int runCalls = 0; - public ManagerReaderMock() - { + public ManagerReaderMock() { } - public void registerEventClass(Class event) - { + public void registerEventClass(Class event) { throw new UnsupportedOperationException(); } - public void setSocket(SocketConnectionFacade socket) - { + public void setSocket(SocketConnectionFacade socket) { setSocketCalls++; } - public void expectResponseClass(String actionId, Class responseClass) - { - + public void expectResponseClass(String actionId, Class responseClass) { + } - public void die() - { + public void die() { dieCalls++; } - public boolean isDead() - { + public boolean isDead() { return false; } - - public void run() - { + + public void run() { runCalls++; } - public IOException getTerminationException() - { + public IOException getTerminationException() { return null; } + + @Override + public void deregisterEventClass(Class eventClass) { + + } } diff --git a/src/test/java/org/asteriskjava/manager/internal/ManagerWriterImplTest.java b/src/test/java/org/asteriskjava/manager/internal/ManagerWriterImplTest.java index 0e3bb0d42..b988375b0 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ManagerWriterImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ManagerWriterImplTest.java @@ -16,47 +16,42 @@ */ package org.asteriskjava.manager.internal; -import junit.framework.TestCase; -import static org.easymock.EasyMock.*; - import org.asteriskjava.manager.action.StatusAction; -import org.asteriskjava.manager.internal.ManagerWriterImpl; import org.asteriskjava.util.SocketConnectionFacade; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; -public class ManagerWriterImplTest extends TestCase -{ +class ManagerWriterImplTest { private ManagerWriter managerWriter; - - @Override - public void setUp() - { + + @BeforeEach + void setUp() { managerWriter = new ManagerWriterImpl(); } - - public void testSendActionWithoutSocket() throws Exception - { - try - { + + @Test + void testSendActionWithoutSocket() throws Exception { + try { managerWriter.sendAction(new StatusAction(), null); fail("Must throw IllegalStateException"); - } - catch (IllegalStateException e) - { - assertTrue("Exception must be of type IllegalStateException", e instanceof IllegalStateException); + } catch (IllegalStateException e) { + assertTrue(e instanceof IllegalStateException, "Exception must be of type IllegalStateException"); } } - public void testSendAction() throws Exception - { + @Test + void testSendAction() throws Exception { SocketConnectionFacade socketConnectionFacade; - socketConnectionFacade = createMock(SocketConnectionFacade.class); + socketConnectionFacade = mock(SocketConnectionFacade.class); socketConnectionFacade.write("action: Status\r\n\r\n"); socketConnectionFacade.flush(); - replay(socketConnectionFacade); managerWriter.setSocket(socketConnectionFacade); managerWriter.sendAction(new StatusAction(), null); - verify(socketConnectionFacade); } } diff --git a/src/test/java/org/asteriskjava/manager/internal/ManagerWriterMock.java b/src/test/java/org/asteriskjava/manager/internal/ManagerWriterMock.java index fa8383ce6..6dedf480c 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ManagerWriterMock.java +++ b/src/test/java/org/asteriskjava/manager/internal/ManagerWriterMock.java @@ -16,8 +16,6 @@ */ package org.asteriskjava.manager.internal; -import java.io.IOException; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.manager.action.ChallengeAction; import org.asteriskjava.manager.action.LoginAction; @@ -30,8 +28,9 @@ import org.asteriskjava.util.DateUtil; import org.asteriskjava.util.SocketConnectionFacade; -public class ManagerWriterMock implements ManagerWriter -{ +import java.io.IOException; + +public class ManagerWriterMock implements ManagerWriter { private static final String CHALLENGE = "12345"; private static final long CONNECT_LATENCY = 50; private static final long RESPONSE_LATENCY = 20; @@ -48,82 +47,64 @@ public class ManagerWriterMock implements ManagerWriter public int logoffActionsSent = 0; public int otherActionsSent = 0; - public ManagerWriterMock() - { + public ManagerWriterMock() { } - public void setTargetVersion(AsteriskVersion version) - { + public void setTargetVersion(AsteriskVersion version) { } - public void setDispatcher(Dispatcher dispatcher) - { + public void setDispatcher(Dispatcher dispatcher) { this.dispatcher = dispatcher; } - public void setExpectedKey(String key) - { + public void setExpectedKey(String key) { this.expectedKey = key; } - public void setExpectedUsername(String username) - { + public void setExpectedUsername(String username) { this.expectedUsername = username; } - public void setSendResponse(boolean sendResponse) - { + public void setSendResponse(boolean sendResponse) { this.sendResponse = sendResponse; } - public void setSendProtocolIdentifierReceivedEvent(boolean sendConnectEvent) - { + public void setSendProtocolIdentifierReceivedEvent(boolean sendConnectEvent) { this.sendProtocolIdentifierReceivedEvent = sendConnectEvent; } - public void setSocket(SocketConnectionFacade socket) - { - if (sendProtocolIdentifierReceivedEvent) - { - Thread future = new Thread(new Runnable() - { - public void run() - { - try - { + public void setSocket(SocketConnectionFacade socket) { + if (sendProtocolIdentifierReceivedEvent) { + Thread future = new Thread(new Runnable() { + public void run() { + try { Thread.sleep(CONNECT_LATENCY); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent; protocolIdentifierReceivedEvent = new ProtocolIdentifierReceivedEvent(this); protocolIdentifierReceivedEvent.setProtocolIdentifier("Asterisk Call Manager/1.0"); protocolIdentifierReceivedEvent.setDateReceived(DateUtil.getDate()); - dispatcher.dispatchEvent(protocolIdentifierReceivedEvent); + dispatcher.dispatchEvent(protocolIdentifierReceivedEvent, null); } }); future.start(); } } - public void sendAction(ManagerAction action, String internalActionId) throws IOException - { - if (action instanceof ChallengeAction) - { + public void sendAction(ManagerAction action, String internalActionId) throws IOException { + if (action instanceof ChallengeAction) { ChallengeAction challengeAction = (ChallengeAction) action; String authType = challengeAction.getAuthType(); - if (!authType.equals("MD5")) - { + if (!authType.equals("MD5")) { throw new RuntimeException("Expected authType 'MD5' got '" + authType + "'"); } challengeActionsSent++; - if (sendResponse) - { + if (sendResponse) { ChallengeResponse challengeResponse; challengeResponse = new ChallengeResponse(); @@ -131,41 +112,33 @@ public void sendAction(ManagerAction action, String internalActionId) throws IOE challengeResponse.setChallenge(CHALLENGE); dispatchLater(challengeResponse); } - } - else if (action instanceof LoginAction) - { + } else if (action instanceof LoginAction) { LoginAction loginAction = (LoginAction) action; String username = loginAction.getUsername(); String key = loginAction.getKey(); String authType = loginAction.getAuthType(); - if (!"MD5".equals(authType)) - { + if (!"MD5".equals(authType)) { throw new RuntimeException("Expected authType 'MD5' got '" + authType + "'"); } - if (!expectedUsername.equals(username)) - { + if (!expectedUsername.equals(username)) { throw new RuntimeException("Expected username '" + expectedUsername + "' got '" + username + "'"); } loginActionsSent++; - if (sendResponse) - { + if (sendResponse) { ManagerResponse loginResponse; // let testReconnectWithKeepAliveAfterAuthenticationFailure // succeed after // 3 unsuccessful attempts - if (key.equals(expectedKey) || loginActionsSent > 2) - { + if (key.equals(expectedKey) || loginActionsSent > 2) { loginResponse = new ManagerResponse(); loginResponse.setResponse("Success"); - } - else - { + } else { loginResponse = new ManagerError(); loginResponse.setResponse("Error"); loginResponse.setMessage("Authentication failed"); @@ -173,13 +146,10 @@ else if (action instanceof LoginAction) loginResponse.setActionId(ManagerUtil.addInternalActionId(action.getActionId(), internalActionId)); dispatchLater(loginResponse); } - } - else if (action instanceof LogoffAction) - { + } else if (action instanceof LogoffAction) { logoffActionsSent++; - if (sendResponse) - { + if (sendResponse) { ManagerResponse response; response = new ManagerResponse(); @@ -187,13 +157,10 @@ else if (action instanceof LogoffAction) response.setResponse("Success"); dispatchLater(response); } - } - else - { + } else { otherActionsSent++; - if (sendResponse) - { + if (sendResponse) { ManagerResponse response; response = new ManagerResponse(); @@ -204,21 +171,15 @@ else if (action instanceof LogoffAction) } } - private void dispatchLater(final ManagerResponse response) - { - Thread future = new Thread(new Runnable() - { - public void run() - { - try - { + private void dispatchLater(final ManagerResponse response) { + Thread future = new Thread(new Runnable() { + public void run() { + try { Thread.sleep(RESPONSE_LATENCY); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } - dispatcher.dispatchResponse(response); + dispatcher.dispatchResponse(response, null); } }); future.start(); diff --git a/src/test/java/org/asteriskjava/manager/internal/MyUserEvent.java b/src/test/java/org/asteriskjava/manager/internal/MyUserEvent.java index 9199151ba..86f785fee 100644 --- a/src/test/java/org/asteriskjava/manager/internal/MyUserEvent.java +++ b/src/test/java/org/asteriskjava/manager/internal/MyUserEvent.java @@ -17,49 +17,44 @@ package org.asteriskjava.manager.internal; import org.asteriskjava.manager.event.UserEvent; + import java.util.Map; -public class MyUserEvent extends UserEvent -{ +public class MyUserEvent extends UserEvent { private static final long serialVersionUID = 3689913989471418169L; private String stringMember; - private Map mapMember; - - public MyUserEvent(Object source) - { + private Map mapMember; + + public MyUserEvent(Object source) { super(source); } /** * @return the mapMember */ - public Map getMapMember() - { + public Map getMapMember() { return mapMember; } /** * @param mapMember the mapMember to set */ - public void setMapMember(Map mapMember) - { + public void setMapMember(Map mapMember) { this.mapMember = mapMember; } /** * @return the stringMember */ - public String getStringMember() - { + public String getStringMember() { return stringMember; } /** * @param stringMember the stringMember to set */ - public void setStringMember(String stringMember) - { + public void setStringMember(String stringMember) { this.stringMember = stringMember; } } diff --git a/src/test/java/org/asteriskjava/manager/internal/ResponseBuilderImplTest.java b/src/test/java/org/asteriskjava/manager/internal/ResponseBuilderImplTest.java index 10f1bae16..65cd4d8d1 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ResponseBuilderImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ResponseBuilderImplTest.java @@ -16,60 +16,61 @@ */ package org.asteriskjava.manager.internal; -import junit.framework.TestCase; import org.asteriskjava.manager.response.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -public class ResponseBuilderImplTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ResponseBuilderImplTest { private ResponseBuilderImpl responseBuilder; private Map attributes; - @Override - public void setUp() - { + @BeforeEach + void setUp() { this.responseBuilder = new ResponseBuilderImpl(); this.attributes = new HashMap(); } - public void testBuildResponse() - { + @Test + void testBuildResponse() { ManagerResponse response; attributes.put("response", "Success"); response = responseBuilder.buildResponse(ManagerResponse.class, attributes); - assertEquals("Response of wrong type", ManagerResponse.class, response.getClass()); - assertEquals("Response not set correctly", "Success", response.getResponse()); + assertEquals(ManagerResponse.class, response.getClass(), "Response of wrong type"); + assertEquals("Success", response.getResponse(), "Response not set correctly"); } - public void testBuildResponseWithoutResponseClass() - { + @Test + void testBuildResponseWithoutResponseClass() { ManagerResponse response; attributes.put("response", "Success"); response = responseBuilder.buildResponse(null, attributes); - assertEquals("Response of wrong type", ManagerResponse.class, response.getClass()); - assertEquals("Response not set correctly", "Success", response.getResponse()); + assertEquals(ManagerResponse.class, response.getClass(), "Response of wrong type"); + assertEquals("Success", response.getResponse(), "Response not set correctly"); } - public void testBuildError() - { + @Test + void testBuildError() { ManagerResponse response; attributes.put("response", "Error"); attributes.put("message", "Missing action in request"); response = responseBuilder.buildResponse(ManagerResponse.class, attributes); - assertEquals("Response of wrong type", ManagerError.class, response.getClass()); - assertEquals("Message not set correctly", "Missing action in request", response.getMessage()); + assertEquals(ManagerError.class, response.getClass(), "Response of wrong type"); + assertEquals("Missing action in request", response.getMessage(), "Message not set correctly"); } - public void testBuildErrorWithActionId() - { + @Test + void testBuildErrorWithActionId() { ManagerResponse response; attributes.put("response", "Error"); @@ -77,23 +78,23 @@ public void testBuildErrorWithActionId() attributes.put("message", "Missing action in request"); response = responseBuilder.buildResponse(ManagerResponse.class, attributes); - assertEquals("ActionId not set correctly", "1234", response.getActionId()); + assertEquals("1234", response.getActionId(), "ActionId not set correctly"); } - public void testBuildChallengeResponse() - { + @Test + void testBuildChallengeResponse() { ManagerResponse response; attributes.put("response", "Success"); attributes.put("challenge", "131494410"); response = responseBuilder.buildResponse(ChallengeResponse.class, attributes); - assertEquals("Response of wrong type", ChallengeResponse.class, response.getClass()); - assertEquals("Challenge not set correctly", "131494410", ((ChallengeResponse) response).getChallenge()); + assertEquals(ChallengeResponse.class, response.getClass(), "Response of wrong type"); + assertEquals("131494410", ((ChallengeResponse) response).getChallenge(), "Challenge not set correctly"); } - public void testBuildMailboxStatusResponse() - { + @Test + void testBuildMailboxStatusResponse() { ManagerResponse response; attributes.put("response", "Success"); @@ -102,15 +103,15 @@ public void testBuildMailboxStatusResponse() attributes.put("waiting", "1"); response = responseBuilder.buildResponse(MailboxStatusResponse.class, attributes); - assertEquals("Response of wrong type", MailboxStatusResponse.class, response.getClass()); + assertEquals(MailboxStatusResponse.class, response.getClass(), "Response of wrong type"); MailboxStatusResponse mailboxStatusResponse = (MailboxStatusResponse) response; - assertEquals("Mailbox not set correctly", "123", mailboxStatusResponse.getMailbox()); - assertEquals("Waiting not set correctly", Boolean.TRUE, mailboxStatusResponse.getWaiting()); + assertEquals("123", mailboxStatusResponse.getMailbox(), "Mailbox not set correctly"); + assertEquals(Boolean.TRUE, mailboxStatusResponse.getWaiting(), "Waiting not set correctly"); } - public void testBuildMailboxStatusResponseWithNoWaiting() - { + @Test + void testBuildMailboxStatusResponseWithNoWaiting() { ManagerResponse response; attributes.put("response", "Success"); @@ -119,15 +120,15 @@ public void testBuildMailboxStatusResponseWithNoWaiting() attributes.put("waiting", "0"); response = responseBuilder.buildResponse(MailboxStatusResponse.class, attributes); - assertEquals("Response of wrong type", MailboxStatusResponse.class, response.getClass()); + assertEquals(MailboxStatusResponse.class, response.getClass(), "Response of wrong type"); MailboxStatusResponse mailboxStatusResponse = (MailboxStatusResponse) response; - assertEquals("Mailbox not set correctly", "123,user2", mailboxStatusResponse.getMailbox()); - assertEquals("Waiting not set correctly", Boolean.FALSE, mailboxStatusResponse.getWaiting()); + assertEquals("123,user2", mailboxStatusResponse.getMailbox(), "Mailbox not set correctly"); + assertEquals(Boolean.FALSE, mailboxStatusResponse.getWaiting(), "Waiting not set correctly"); } - public void testBuildMailboxCountResponse() - { + @Test + void testBuildMailboxCountResponse() { ManagerResponse response; attributes.put("response", "Success"); @@ -137,16 +138,16 @@ public void testBuildMailboxCountResponse() attributes.put("oldmessages", "5"); response = responseBuilder.buildResponse(MailboxCountResponse.class, attributes); - assertEquals("Response of wrong type", MailboxCountResponse.class, response.getClass()); + assertEquals(MailboxCountResponse.class, response.getClass(), "Response of wrong type"); MailboxCountResponse mailboxCountResponse = (MailboxCountResponse) response; - assertEquals("Mailbox not set correctly", "123@myctx", mailboxCountResponse.getMailbox()); - assertEquals("New messages not set correctly", Integer.valueOf(2), mailboxCountResponse.getNewMessages()); - assertEquals("Old messages set correctly", Integer.valueOf(5), mailboxCountResponse.getOldMessages()); + assertEquals("123@myctx", mailboxCountResponse.getMailbox(), "Mailbox not set correctly"); + assertEquals(Integer.valueOf(2), mailboxCountResponse.getNewMessages(), "New messages not set correctly"); + assertEquals(Integer.valueOf(5), mailboxCountResponse.getOldMessages(), "Old messages set correctly"); } - public void testBuildExtensionStateResponse() - { + @Test + void testBuildExtensionStateResponse() { ManagerResponse response; attributes.put("response", "Success"); @@ -157,12 +158,12 @@ public void testBuildExtensionStateResponse() attributes.put("status", "-1"); response = responseBuilder.buildResponse(ExtensionStateResponse.class, attributes); - assertEquals("Response of wrong type", ExtensionStateResponse.class, response.getClass()); + assertEquals(ExtensionStateResponse.class, response.getClass(), "Response of wrong type"); ExtensionStateResponse extensionStateResponse = (ExtensionStateResponse) response; - assertEquals("Exten not set correctly", "1", extensionStateResponse.getExten()); - assertEquals("Context not set correctly", "default", extensionStateResponse.getContext()); - assertEquals("Hint not set correctly", "", extensionStateResponse.getHint()); - assertEquals("Status not set correctly", Integer.valueOf(-1), extensionStateResponse.getStatus()); + assertEquals("1", extensionStateResponse.getExten(), "Exten not set correctly"); + assertEquals("default", extensionStateResponse.getContext(), "Context not set correctly"); + assertEquals("", extensionStateResponse.getHint(), "Hint not set correctly"); + assertEquals(Integer.valueOf(-1), extensionStateResponse.getStatus(), "Status not set correctly"); } } diff --git a/src/test/java/org/asteriskjava/manager/internal/UserEventC.java b/src/test/java/org/asteriskjava/manager/internal/UserEventC.java index 389ca1318..89716a2ce 100644 --- a/src/test/java/org/asteriskjava/manager/internal/UserEventC.java +++ b/src/test/java/org/asteriskjava/manager/internal/UserEventC.java @@ -18,12 +18,10 @@ import org.asteriskjava.manager.event.UserEvent; -public class UserEventC extends UserEvent -{ +public class UserEventC extends UserEvent { private static final long serialVersionUID = 3545240219457894199L; - public UserEventC(Object source) - { + public UserEventC(Object source) { super(source); } } diff --git a/src/test/java/org/asteriskjava/manager/internal/UserEventDEvent.java b/src/test/java/org/asteriskjava/manager/internal/UserEventDEvent.java index 0e4324b79..4bf60f1d0 100644 --- a/src/test/java/org/asteriskjava/manager/internal/UserEventDEvent.java +++ b/src/test/java/org/asteriskjava/manager/internal/UserEventDEvent.java @@ -18,12 +18,10 @@ import org.asteriskjava.manager.event.UserEvent; -public class UserEventDEvent extends UserEvent -{ +public class UserEventDEvent extends UserEvent { private static final long serialVersionUID = 3545240219457894199L; - public UserEventDEvent(Object source) - { + public UserEventDEvent(Object source) { super(source); } } diff --git a/src/test/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparatorTest.java b/src/test/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparatorTest.java new file mode 100644 index 000000000..f31ea51c6 --- /dev/null +++ b/src/test/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparatorTest.java @@ -0,0 +1,253 @@ +/* + * Copyright 2018 Marcin Turek + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.asteriskjava.manager.internal.backwardsCompatibility.bridge; + +import org.asteriskjava.manager.event.BridgeEnterEvent; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BridgeEnterEventComparatorTest { + private BridgeEnterEventComparator bridgeEnterEventComparator = new BridgeEnterEventComparator(); + + @Test + void withoutPrefix_shouldId2BeGreater() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590350.29"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(-1, compareResult); + } + + @Test + void withoutPrefix_shouldId1BeGreater() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590350.29"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(1, compareResult); + } + + @Test + void withoutPrefix_shouldId2BeGreaterForSameSerials() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590350.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(-1, compareResult); + } + + @Test + void withoutPrefix_shouldId1BeGreaterForSameSerials() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590350.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(1, compareResult); + } + + @Test + void withoutPrefix_shouldId2BeGreaterForSameEpoch() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.29"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(-1, compareResult); + } + + @Test + void withoutPrefix_shouldId1BeGreaterForSameEpoch() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.29"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(1, compareResult); + } + + @Test + void withoutPrefix_shouldIdsBeEqual() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(0, compareResult); + } + + @Test + void withPrefix_shouldId2BeGreater() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590350.29"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590353.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(-1, compareResult); + } + + @Test + void withPrefix_shouldId1BeGreater() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590353.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590350.29"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(1, compareResult); + } + + @Test + void withPrefix_shouldId2BeGreaterForSameSerials() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590350.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590353.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(-1, compareResult); + } + + @Test + void withPrefix_shouldId1BeGreaterForSameSerials() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590353.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590350.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(1, compareResult); + } + + @Test + void withPrefix_shouldId2BeGreaterForSameEpoch() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590350.29"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590350.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(-1, compareResult); + } + + @Test + void withPrefix_shouldId1BeGreaterForSameEpoch() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590350.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590350.29"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(1, compareResult); + } + + @Test + void withPrefix_shouldIdsBeEqual() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590353.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590353.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(0, compareResult); + } + + @Test + void shouldBothIdsDoesNotMatchPattern() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_id_1"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_id_2"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(0, compareResult); + } + + @Test + void shouldId1DoesNotMatchPattern() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_id_1"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590353.30"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(-1, compareResult); + } + + @Test + void shouldId2DoesNotMatchPattern() { + // given + BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590353.30"); + BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_id_2"); + + // when + int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); + + // then + assertEquals(1, compareResult); + } + + private static BridgeEnterEvent createBridgeEnterEvent(String uniqueId) { + BridgeEnterEvent bridgeEnterEvent = new BridgeEnterEvent(new Object()); + bridgeEnterEvent.setUniqueId(uniqueId); + return bridgeEnterEvent; + } +} diff --git a/src/test/java/org/asteriskjava/manager/response/CoreStatusResponseTest.java b/src/test/java/org/asteriskjava/manager/response/CoreStatusResponseTest.java index 373e11da4..763268942 100644 --- a/src/test/java/org/asteriskjava/manager/response/CoreStatusResponseTest.java +++ b/src/test/java/org/asteriskjava/manager/response/CoreStatusResponseTest.java @@ -1,41 +1,42 @@ package org.asteriskjava.manager.response; -import junit.framework.TestCase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.TimeZone; -public class CoreStatusResponseTest extends TestCase -{ +import static org.junit.jupiter.api.Assertions.*; + +class CoreStatusResponseTest { private TimeZone tz = TimeZone.getTimeZone("Europe/Berlin"); private CoreStatusResponse response; private TimeZone defaultTimeZone; - @Override - protected void setUp() throws Exception - { + @BeforeEach + void setUp() { this.response = new CoreStatusResponse(); defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(tz); } - @Override - protected void tearDown() throws Exception - { + @AfterEach + void tearDown() { TimeZone.setDefault(defaultTimeZone); } - public void testGetCoreStartupTimeAsDate() - { - assertNotNull("TimeZone not found", tz); + @Test + void testGetCoreStartupTimeAsDate() { + assertNotNull(tz, "TimeZone not found"); response.setCoreStartupDate("2009-05-27"); response.setCoreStartupTime("02:49:15"); assertEquals("Wed May 27 02:49:15 CEST 2009", response.getCoreStartupDateTimeAsDate(tz).toString()); } - public void testGetCoreStartupTimeAsDateIfDateIsNull() - { - assertNotNull("TimeZone not found", tz); + @Test + void testGetCoreStartupTimeAsDateIfDateIsNull() { + assertNotNull(tz, "TimeZone not found"); response.setCoreStartupDate(null); // before Asterisk 1.6.2 response.setCoreStartupTime("02:49:15"); diff --git a/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java b/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java index da7f25a0e..d886a45f3 100644 --- a/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java +++ b/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java @@ -1,32 +1,84 @@ +/* + * Copyright 2004-2022 Asterisk-Java contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.asteriskjava.manager.response; -import junit.framework.TestCase; +import org.asteriskjava.manager.util.EventAttributesHelper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SipShowPeerResponseTest extends TestCase -{ +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SipShowPeerResponseTest { private SipShowPeerResponse response; - - @Override - public void setUp() - { + + @BeforeEach + void setUp() { response = new SipShowPeerResponse(); } - - public void testSetQualifyFreq() - { + + @Test + void shouldCreateResponse() { + //given + SipShowPeerResponse sipShowPeerResponse = new SipShowPeerResponse(); + Map attributes = new HashMap<>(); + attributes.put("named pickupgroup", ""); + attributes.put("sip-rtcp-mux", "N"); + attributes.put("description", ""); + attributes.put("subscribecontext", ""); + attributes.put("named callgroup", ""); + + //when + EventAttributesHelper.setAttributes(sipShowPeerResponse, attributes, new HashSet<>()); + + //then + assertThat(sipShowPeerResponse.getNamedPickupgroup()).isBlank(); + assertThat(sipShowPeerResponse.getSipRtcpMux()).isEqualTo("N"); + assertThat(sipShowPeerResponse.getDescription()).isBlank(); + assertThat(sipShowPeerResponse.getSubscribecontext()).isBlank(); + assertThat(sipShowPeerResponse.getNamedCallgroup()).isBlank(); + } + + @Test + void testSetQualifyFreq() { response.setQualifyFreq("6000 ms"); - assertEquals("Incorrect qualifyFreq", 6000, (int) response.getQualifyFreq()); + assertEquals(6000, (int) response.getQualifyFreq(), "Incorrect qualifyFreq"); } - public void testSetQualifyFreqWithWorkaround() - { + @Test + void testSetQualifyFreqWithWorkaround() { response.setQualifyFreq(": 6000 ms\n"); - assertEquals("Incorrect qualifyFreq", 6000, (int) response.getQualifyFreq()); + assertEquals(6000, (int) response.getQualifyFreq(), "Incorrect qualifyFreq"); } - public void testSetQualifyFreqWithWorkaroundAndChanVariable() - { + @Test + void testSetQualifyFreqWithWorkaroundAndChanVariable() { response.setQualifyFreq(": 60000 ms\nChanVariable:\n PHBX_ID,191"); - assertEquals("Incorrect qualifyFreq", 60000, (int) response.getQualifyFreq()); + assertEquals(60000, (int) response.getQualifyFreq(), "Incorrect qualifyFreq"); + } + + @Test + void testSetMohsuggest() { + response.setMohsuggest("default"); + assertEquals("default", response.getMohsuggest(), "Incorrect mohsuggest"); } + + } diff --git a/src/test/java/org/asteriskjava/pbx/internal/core/ListenerManagerTest.java b/src/test/java/org/asteriskjava/pbx/internal/core/ListenerManagerTest.java new file mode 100644 index 000000000..33d55902a --- /dev/null +++ b/src/test/java/org/asteriskjava/pbx/internal/core/ListenerManagerTest.java @@ -0,0 +1,62 @@ +package org.asteriskjava.pbx.internal.core; + +import org.asteriskjava.pbx.ListenerPriority; +import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.VarSetEvent; +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ListenerManagerTest { + volatile boolean managereventRecevied = false; + + @Test + void listenerTest() throws InterruptedException { + List> listeners = new LinkedList<>(); + + ListenerManager queue = new ListenerManager(); + + for (int i = 0; i < 1000; i++) { + FilteredManagerListener listener = getListener(); + listeners.add(listener); + queue.addListener(listener); + } + Collections.shuffle(listeners); + for (FilteredManagerListener listener : listeners) { + assertTrue(queue.removeListener(listener)); + } + + assertTrue(queue.size() == 0); + + } + + private FilteredManagerListener getListener() { + return new FilteredManagerListener() { + + @Override + public Set> requiredEvents() { + Set> events = new HashSet<>(); + events.add(VarSetEvent.class); + return events; + } + + @Override + public void onManagerEvent(ManagerEvent event) { + managereventRecevied = true; + } + + @Override + public ListenerPriority getPriority() { + return ListenerPriority.NORMAL; + } + + @Override + public String getName() { + return "test"; + } + }; + } + +} diff --git a/src/test/java/org/asteriskjava/util/AstUtilTest.java b/src/test/java/org/asteriskjava/util/AstUtilTest.java index bbf965f84..86f1bf075 100644 --- a/src/test/java/org/asteriskjava/util/AstUtilTest.java +++ b/src/test/java/org/asteriskjava/util/AstUtilTest.java @@ -1,21 +1,22 @@ package org.asteriskjava.util; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; -public class AstUtilTest extends TestCase -{ - public void testIsTrue() - { - assertTrue("on must be true", AstUtil.isTrue("on")); - assertTrue("ON must be true", AstUtil.isTrue("ON")); - assertTrue("Enabled must be true", AstUtil.isTrue("Enabled")); - assertTrue("true must be true", AstUtil.isTrue("true")); - assertFalse("false must be false", AstUtil.isTrue("false")); - assertFalse("null must be false", AstUtil.isTrue(null)); +import static org.junit.jupiter.api.Assertions.*; + +class AstUtilTest { + @Test + void testIsTrue() { + assertTrue(AstUtil.isTrue("on"), "on must be true"); + assertTrue(AstUtil.isTrue("ON"), "ON must be true"); + assertTrue(AstUtil.isTrue("Enabled"), "Enabled must be true"); + assertTrue(AstUtil.isTrue("true"), "true must be true"); + assertFalse(AstUtil.isTrue("false"), "false must be false"); + assertFalse(AstUtil.isTrue(null), "null must be false"); } - public void testParseCallerIdName() - { + @Test + void testParseCallerIdName() { assertEquals("Hans Wurst", AstUtil.parseCallerId("\"Hans Wurst\"<1234>")[0]); assertEquals("Hans Wurst", AstUtil.parseCallerId("\"Hans Wurst\" <1234>")[0]); assertEquals("Hans Wurst", AstUtil.parseCallerId("\" Hans Wurst \" <1234>")[0]); @@ -35,8 +36,8 @@ public void testParseCallerIdName() assertEquals(null, AstUtil.parseCallerId(" ")[0]); } - public void testParseCallerIdNumber() - { + @Test + void testParseCallerIdNumber() { assertEquals("1234", AstUtil.parseCallerId("\"Hans Wurst\"<1234>")[1]); assertEquals("1234", AstUtil.parseCallerId("\"Hans Wurst\" <1234>")[1]); assertEquals("1234", AstUtil.parseCallerId("Hans Wurst < 1234 > ")[1]); @@ -49,22 +50,32 @@ public void testParseCallerIdNumber() assertEquals(null, AstUtil.parseCallerId(" ")[1]); } - public void testAJ120() - { + @Test + void testAJ120() { String s = "\"3496853210\" <3496853210>"; assertEquals("3496853210", AstUtil.parseCallerId(s)[0]); assertEquals("3496853210", AstUtil.parseCallerId(s)[1]); } - public void testIsNull() - { - assertTrue("null must be null", AstUtil.isNull(null)); - assertTrue("unknown must be null", AstUtil.isNull("unknown")); - assertTrue(" must be null", AstUtil.isNull("")); + @Test + void testIsNull() { + assertTrue(AstUtil.isNull(null), "null must be null"); + assertTrue(AstUtil.isNull("unknown"), "unknown must be null"); + assertTrue(AstUtil.isNull(""), " must be null"); + } + + @Test + void testIsNullForIpAddressInPeerEntryEvent() { + assertTrue(AstUtil.isNull("-none-"), "\"-none-\" must be considered null"); } - public void testIsNullForIpAddressInPeerEntryEvent() - { - assertTrue("\"-none-\" must be considered null", AstUtil.isNull("-none-")); + @Test + void testIsEqual() { + assertTrue(AstUtil.isEqual(null, null)); + assertTrue(AstUtil.isEqual("", "")); + assertFalse(AstUtil.isEqual(null, "")); + assertFalse(AstUtil.isEqual("", null)); + assertFalse(AstUtil.isEqual("", "1")); + } } diff --git a/src/test/java/org/asteriskjava/util/DateUtilTest.java b/src/test/java/org/asteriskjava/util/DateUtilTest.java index 6078fbcb8..38eb8650f 100644 --- a/src/test/java/org/asteriskjava/util/DateUtilTest.java +++ b/src/test/java/org/asteriskjava/util/DateUtilTest.java @@ -1,37 +1,38 @@ package org.asteriskjava.util; -import java.util.TimeZone; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import java.util.Date; +import java.util.TimeZone; -import junit.framework.TestCase; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class DateUtilTest extends TestCase -{ +class DateUtilTest { TimeZone defaultTimeZone; final String dateString = "2006-05-19 11:54:48"; - @Override - protected void setUp() throws Exception - { + @BeforeEach + void setUp() { defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } - @Override - protected void tearDown() throws Exception - { + @AfterEach + void tearDown() { TimeZone.setDefault(defaultTimeZone); } - public void testGetStartTimeAsDate() - { + @Test + void testGetStartTimeAsDate() { final Date result = DateUtil.parseDateTime(dateString); assertEquals(1148039688000L, result.getTime()); assertEquals("Fri May 19 11:54:48 GMT 2006", result.toString()); } - public void testGetStartTimeAsDateWithTimeZone() - { + @Test + void testGetStartTimeAsDateWithTimeZone() { final TimeZone tz = TimeZone.getTimeZone("GMT+2"); final Date result = DateUtil.parseDateTime(dateString, tz); assertEquals(1148032488000L, result.getTime()); diff --git a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerDeterministicTest.java b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerDeterministicTest.java new file mode 100644 index 000000000..1c218228d --- /dev/null +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerDeterministicTest.java @@ -0,0 +1,83 @@ +package org.asteriskjava.util.internal.streamreader; + +import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.NoSuchElementException; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class FastScannerDeterministicTest { + @Test + void testCrNlScanner() throws Exception { + testScanner(10000, SocketConnectionFacadeImpl.NL_PATTERN); + } + + @Test + void testNlScanner() throws Exception { + testScanner(10000, SocketConnectionFacadeImpl.CRNL_PATTERN); + } + + private void testScanner(int testLines, Pattern pattern) throws Exception { + + final byte[] bytes = buildTestData(testLines, pattern).getBytes(); + + InputStream inputStream = new ByteArrayInputStream(bytes); + + InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + + // factory will return the correct reader for the pattern + try (FastScanner scanner = FastScannerFactory.getReader(reader, pattern)) { + System.out.println("\nTesting scanner class: " + scanner.getClass()); + int ctr = 0; + @SuppressWarnings("unused") + String t; + while ((t = scanner.next()) != null) { + // System.out.println("L: " + t + " " + t.length()); + ctr++; + } + assertEquals((testLines), ctr, "Counter expected : " + (testLines) + " got " + ctr); + + } catch (NoSuchElementException e) { + } + + System.out.println("Done\n"); + } + + @Test + void testBR2Accuraccy3() throws Exception { + URL resource = this.getClass().getClassLoader().getResource("NlStreamReaderFast273316816601633219.txt"); + final byte[] bytes = Files.readAllBytes(Paths.get(resource.toURI())); + + InputStream inputStream = new ByteArrayInputStream(bytes); + + InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + + try (FastScannerNl scanner = new FastScannerNl(reader);) { + String t; + while ((t = scanner.next()) != null) { + System.out.println("L: " + t + " " + t.length()); + } + + } catch (NoSuchElementException e) { + } + } + + String buildTestData(int lines, Pattern terminator) { + StringBuilder builder = new StringBuilder(lines * 30); + int ctr = 0; + while (ctr < lines) { + ctr++; + builder.append("Hallo hello: one line with text! " + ctr + terminator.pattern()); + } + return builder.toString(); + } +} diff --git a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerRandomTest.java b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerRandomTest.java new file mode 100644 index 000000000..328414419 --- /dev/null +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerRandomTest.java @@ -0,0 +1,114 @@ +package org.asteriskjava.util.internal.streamreader; + +import org.asteriskjava.manager.internal.ManagerUtil; +import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.NoSuchElementException; +import java.util.Random; +import java.util.Scanner; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.fail; + +class FastScannerRandomTest { + @Test + void compareOutputOfNlFastScannerToScanner() throws Exception { + setupTest(SocketConnectionFacadeImpl.NL_PATTERN, "NL"); + } + + @Test + void compareOutputOfCrNlFastScannerToScanner() throws Exception { + setupTest(SocketConnectionFacadeImpl.CRNL_PATTERN, "CR NL"); + } + + void setupTest(final Pattern pattern, String caption) { + + final AtomicInteger ctr = new AtomicInteger(); + + int tests = 50; + + for (int i = 0; i < tests; i++) { + + try { + String testData = generateTestData(1_000_000); + compare(testData, pattern); + System.out.println(caption + " Completed " + (ctr.incrementAndGet()) * 1 + "MB"); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + } + + void compare(String testData, Pattern pattern) throws IOException { + + InputStream inputStream1 = new ByteArrayInputStream(testData.getBytes()); + InputStreamReader reader1 = new InputStreamReader(inputStream1, StandardCharsets.UTF_8); + + InputStream inputStream2 = new ByteArrayInputStream(testData.getBytes()); + InputStreamReader reader2 = new InputStreamReader(inputStream2, StandardCharsets.UTF_8); + + FastScanner fast = FastScannerFactory.getReader(reader2, pattern); + + String scannerResult = ""; + String fastResult = ""; + + int ctr = 0; + Scanner scanner = new Scanner(reader1); + + scanner.useDelimiter(pattern); + + try { + while ((scannerResult = scanner.next()) != null) { + ctr++; + fastResult = fast.next(); + + if (!fastResult.equals(scannerResult)) { + + System.out.println("Expected " + ManagerUtil.toHexString(scannerResult.getBytes())); + System.out.println("Got " + ManagerUtil.toHexString(fastResult.getBytes())); + System.out.println("Error " + ctr); + System.out.println(""); + + throw new RuntimeException("Mismatched output"); + } + } + } catch (NoSuchElementException e) { + if (fast.next() != null) { + throw new RuntimeException("Expected null, not something else"); + } + // Scanner normally throws this exception at the end of the stream + } finally { + scanner.close(); + fast.close(); + } + } + + public static String generateTestData(int byteSize) { + Random rand = new Random(); + String bodyData = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(),.<>[] {};':\""; + bodyData += bodyData.toUpperCase(); + + String[] terminators = new String[]{"\n", "\r", "\r\n", "\n\r"}; + + StringBuilder builder = new StringBuilder(byteSize * 2); + for (int i = 0; i < byteSize; i++) { + if (Math.random() * 100 > 98) { + // 2 % chance of a line ending + builder.append(terminators[rand.nextInt(terminators.length)]); + } else { + int position = rand.nextInt(bodyData.length()); + builder.append(bodyData.substring(position, position + 1)); + } + } + + return builder.toString(); + } +} diff --git a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTest.java b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTest.java new file mode 100644 index 000000000..d58fd7ba6 --- /dev/null +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTest.java @@ -0,0 +1,90 @@ +package org.asteriskjava.util.internal.streamreader; + +import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.NoSuchElementException; +import java.util.Scanner; +import java.util.regex.Pattern; + +class FastScannerSpeedTest { + @Test + void testScannerSpeed() throws Exception { + final byte[] bytes = FastScannerRandomTest.generateTestData(10_000_000).getBytes(); + + for (int i = 10; i-- > 0; ) { + System.out.print("Scanner " + i + ":\t"); + + InputStream inputStream = new ByteArrayInputStream(bytes); + + InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + + long start = System.currentTimeMillis(); + int ctr = 0; + try (Scanner scanner = new Scanner(reader);) { + + scanner.useDelimiter(Pattern.compile("\r\n")); + + @SuppressWarnings("unused") + String t; + while ((t = scanner.next()) != null) { + // System.out.println(t); + ctr++; + } + System.out.print(ctr + "\t"); + } catch (NoSuchElementException e) { + System.out.print(ctr + "\t"); + } + System.out.println((System.currentTimeMillis() - start) + " ms"); + } + } + + @Test + void test1() throws Exception { + System.out.println("\nTesting fast CrNlStream"); + fastScannerSpeedTest(SocketConnectionFacadeImpl.CRNL_PATTERN); + } + + @Test + void test2() throws Exception { + /* + * the random test data generates quite a lot of /n which means we will + * get a LOT more lines when checking for /n + */ + System.out.println("\nTesting fast NlStream"); + fastScannerSpeedTest(SocketConnectionFacadeImpl.NL_PATTERN); + } + + private void fastScannerSpeedTest(Pattern pattern) throws Exception { + final byte[] bytes = FastScannerRandomTest.generateTestData(10_000_000).getBytes(); + + for (int i = 10; i-- > 0; ) { + System.out.print("Fast " + i + ":\t"); + + InputStream inputStream = new ByteArrayInputStream(bytes); + + InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + FastScanner scanner = FastScannerFactory.getReader(reader, pattern); + + long start = System.currentTimeMillis(); + try { + int ctr = 0; + @SuppressWarnings("unused") + String t; + while ((t = scanner.next()) != null) { + // System.out.println(t); + ctr++; + } + System.out.print(ctr + "\t"); + + } catch (NoSuchElementException e) { + } + System.out.println((System.currentTimeMillis() - start) + " ms"); + } + } + +} diff --git a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTestOnSocket.java b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTestOnSocket.java new file mode 100644 index 000000000..fe5179e46 --- /dev/null +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTestOnSocket.java @@ -0,0 +1,105 @@ +package org.asteriskjava.util.internal.streamreader; + +import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.Socket; +import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; +import java.util.NoSuchElementException; +import java.util.Scanner; +import java.util.regex.Pattern; + +class FastScannerSpeedTestOnSocket { + @Test + void testScannerSpeed() throws Exception { + try { + for (int i = 10; i-- > 0; ) { + + Socket echoSocket = new Socket("127.0.0.1", FastScannerTestSocketSource.portNumber); + + InputStreamReader reader = getReader(echoSocket); + System.out.print("Scanner " + i + ":\t"); + + long start = System.currentTimeMillis(); + int ctr = 0; + try (Scanner scanner = new Scanner(reader);) { + + scanner.useDelimiter(Pattern.compile("\r\n")); + + @SuppressWarnings("unused") + String t; + while ((t = scanner.next()) != null) { + // System.out.println(t); + ctr++; + } + System.out.print(ctr + "\t"); + } catch (NoSuchElementException e) { + System.out.print(ctr + "\t"); + } + System.out.println((System.currentTimeMillis() - start) + " ms"); + } + } catch (Exception e) { + System.out.println( + "If you want to run FastScannerSpeedTestOnSocket, you'll need to run FastScannerTestSocketSource first"); + } + } + + private InputStreamReader getReader(Socket echoSocket) throws UnknownHostException, IOException, InterruptedException { + + InputStream inputStream = echoSocket.getInputStream(); + + InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + return reader; + } + + @Test + void test1() throws Exception { + System.out.println("\nTesting fast CrNlStream"); + fastScannerSpeedTest(SocketConnectionFacadeImpl.CRNL_PATTERN); + } + + @Test + void test2() throws Exception { + /* + * the random test data generates quite a lot of /n which means we will + * get a LOT more lines when checking for /n + */ + System.out.println("\nTesting fast NlStream"); + fastScannerSpeedTest(SocketConnectionFacadeImpl.NL_PATTERN); + } + + private void fastScannerSpeedTest(Pattern pattern) throws Exception { + try { + for (int i = 10; i-- > 0; ) { + Socket echoSocket = new Socket("127.0.0.1", FastScannerTestSocketSource.portNumber); + + InputStreamReader reader = getReader(echoSocket); + System.out.print("Fast " + i + ":\t"); + FastScanner scanner = FastScannerFactory.getReader(reader, pattern); + + long start = System.currentTimeMillis(); + try { + int ctr = 0; + @SuppressWarnings("unused") + String t; + while ((t = scanner.next()) != null) { + // System.out.println(t); + ctr++; + } + System.out.print(ctr + "\t"); + + } catch (NoSuchElementException e) { + } + System.out.println((System.currentTimeMillis() - start) + " ms"); + } + } catch (Exception e) { + System.out.println( + "If you want to run FastScannerSpeedTestOnSocket, you'll need to run FastScannerTestSocketSource first"); + } + } + +} diff --git a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerTestSocketSource.java b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerTestSocketSource.java new file mode 100644 index 000000000..fbd18cdc5 --- /dev/null +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerTestSocketSource.java @@ -0,0 +1,28 @@ +package org.asteriskjava.util.internal.streamreader; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; + +public class FastScannerTestSocketSource { + final static byte[] bytes = FastScannerRandomTest.generateTestData(100_000_000).getBytes(); + public static int portNumber = 2048; + + public static void main(String[] args) throws IOException { + + while (true) { + + listen(); + } + + } + + static void listen() throws IOException { + System.out.println("Waiting for connect on " + portNumber); + + try (ServerSocket serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept();) { + clientSocket.getOutputStream().write(bytes); + } + } + +} diff --git a/src/test/resources/NlStreamReaderFast273316816601633219.txt b/src/test/resources/NlStreamReaderFast273316816601633219.txt new file mode 100644 index 000000000..91b41b092 --- /dev/null +++ b/src/test/resources/NlStreamReaderFast273316816601633219.txt @@ -0,0 +1,31 @@ +agi_network: yes +agi_network_script: route?targ=7601&ctx=Pre-Handset +agi_request: agi://10.10.0.41/route?targ=7601&ctx=Pre-Handset +agi_channel: Local/7610@default-2df1,1 +agi_language: en +agi_type: Local +agi_uniqueid: 1530169476.16133 +agi_callerid: unknown +agi_calleridname: unknown +agi_callingpres: 0 +agi_callingani2: 0 +agi_callington: 0 +agi_callingtns: 0 +agi_dnid: unknown +agi_rdnis: unknown +agi_context: routesv2-handset +agi_extension: 7601 +agi_priority: 1 +agi_enhanced: 0.0 +agi_accountcode: + +200 result=0 +200 result=1 () +200 result=0 +200 result=1 +200 result=0 +200 result=0 +200 result=0 +200 result=0 +200 result=1 () +200 result=1

        "); writer.append(uniqueId.substring(0, uniqueId.lastIndexOf('.') + 1)); writer.append(""); @@ -127,34 +115,28 @@ public void write() writer.append("
        "); - line.append(getLocalName(event.getClass())); + line.append(event.getClass().getSimpleName()); line.append("
        "); line.append(event.getDateReceived()); line.append("
        ").append(text).append("