diff --git a/.dart_tool/.gitignore b/.dart_tool/.gitignore deleted file mode 100644 index b5a718a86..000000000 --- a/.dart_tool/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/package_config.json diff --git a/.editorconfig b/.editorconfig index f02d2801a..1dfca740e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,5 +1,8 @@ [*.{java,html}] charset = utf-8 -indent_style = tab +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..1be06ba3d --- /dev/null +++ b/.github/release-drafter-master.yml @@ -0,0 +1,27 @@ +filter-by-commitish: true +commitish: master +template: | + ## What's Changed + + $CHANGES +categories: + - title: '๐Ÿ’ฅ Breaking API Changes' + label: 'kind/breaking' + - title: '๐Ÿš€ Features & Enhancements' + labels: + - 'kind/enhancement' + - 'kind/feature' + - title: '๐Ÿ› Bug Fixes' + label: 'kind/bug' + - title: '๐Ÿงน Refactor' + label: 'kind/refactor' + - title: '๐Ÿ“ Documentation' + label: 'kind/documentation' + - title: '๐Ÿ“ฆ Dependency Updates' + 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..8b7c4a4bd --- /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@v6.0.1 + with: + fetch-depth: 0 + + - name: Setup Java ${{ matrix.java }} + uses: actions/setup-java@v5.1.0 + with: + distribution: temurin + java-version: ${{ matrix.java }} + + - name: Build + run: ./mvnw clean package diff --git a/.github/workflows/nexus.yml b/.github/workflows/nexus.yml deleted file mode 100644 index 3cd1e8344..000000000 --- a/.github/workflows/nexus.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: Release - -# Run workflow on tags -on: - push: - tags: - - '*' - -jobs: - release: - runs-on: ubuntu-18.04 - steps: - - name: Check out Git repository - uses: actions/checkout@v2 - - - name: Install Java and Maven - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - - name: Release Maven package - uses: samuelmeuli/action-maven-publish@v1 - with: - gpg_private_key: ${{ secrets.gpg_private_key }} - gpg_passphrase: ${{ secrets.gpg_passphrase }} - nexus_username: ${{ secrets.nexus_username }} - nexus_password: ${{ secrets.nexus_password }} - diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml new file mode 100644 index 000000000..78a0ff648 --- /dev/null +++ b/.github/workflows/release-drafter.yml @@ -0,0 +1,21 @@ +name: Release Drafter + +on: + push: + branches: + - master + +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@v6.1.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..0ac02607b --- /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@v6.0.1 + + - name: Set up Java + uses: actions/setup-java@v5.1.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@v6.0.1 + 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.0.0 + 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/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 000000000..bf82ff01c Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..dc3affce3 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# 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 +# +# https://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. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 366fe82b8..000000000 --- a/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: java - -jdk: -- oraclejdk7 -- oraclejdk8 -- openjdk7 - -script: -- ./gradlew test - -install: -- /bin/true - 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 7ff4fdacb..7baf1f8e2 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,49 @@ -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). -You can find the Java docs for the lastest version here: -[JavaDoc](https://javadoc.io/doc/org.asteriskjava/asterisk-java/2.0.2) +You can find the Java docs for the latest version here: +[Javadoc](https://javadoc.io/doc/org.asteriskjava/asterisk-java/latest) -FastAGI -------- -FastAGI lets you create a service that manages a call in a similar way to what a webserver handles a 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. +### FastAGI -The FastAGI implementation supports all commands currently available from Asterisk. +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. -Manager API ------------ -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). -If you like, the Manager API allows you start and manipulate calls. -A complete list of the available events and actions is available in the javadocs. +The FastAGI implementation supports all commands currently available from +Asterisk. -Activities ----------- -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. +### Manager API -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. +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). + +### Activities + +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. + +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. [Getting Started](https://github.com/asterisk-java/asterisk-java/wiki/Getting-Started) @@ -35,76 +53,86 @@ Activities provide a simple and consistent method of interaction with Asterisk w [Examples](https://github.com/asterisk-java/asterisk-java/wiki/Examples) +--- + +## Getting Asterisk-Java -GETTING ASTERISK-JAVA ---------------------- +Asterisk-Java is available +[on GitHub](https://github.com/asterisk-java/asterisk-java/releases). -Asterisk-Java is available from [here](https://github.com/asterisk-java/asterisk-java/releases) +### Maven -Maven Dependency ----------------- +Asterisk-Java 3.x (Java 1.8 and Asterisk Version 10 thru 23) (master) -Asterisk-Java 3.x (Java 1.8 and Asterisk Version 10 thru 16) (master) +```xml - - org.asteriskjava - asterisk-java - 3.0.19 - + + org.asteriskjava + asterisk-java + 3.41.0 + +``` -Asterisk-Java 2.x (Java 1.7 and Asterisk < Version 10) (branch 2.0.4) +### Gradle - - org.asteriskjava - asterisk-java - 2.2.0 - +```text +implementation group: 'org.asteriskjava', name: 'asterisk-java', version: '3.41.0' +``` +### Installation from source -INSTALLATION FROM SOURCE ------------------------- +```text +git clone https://github.com/asterisk-java/asterisk-java.git +cd asterisk-java +mvn install +``` - 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. -After the build is complete, the jar will then be built as target/asterisk-java.jar in the asterisk-java directory. +## Example -EXAMPLE -------- +The file `examples/ExampleCallIn.java` will answer the call and playback the +audio file 'tt-monkeys'. -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; - 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(); - } - } +/* 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 diaplan context to the class you would like to invoke above. +The file `examples/fastagi.properties` maps your Asterisk dialplan context to +the class you would like to invoke above. - callin.agi = ExampleCallIn +```text +callin.agi = ExampleCallIn +``` -To compile and run do: +To compile and run: - javac -cp asterisk-java.jar ExampleCallIn.java - java -cp asterisk-java.jar org.asteriskjava.fastagi.DefaultAgiServer +```text +javac -cp asterisk-java.jar ExampleCallIn.java +java -cp asterisk-java.jar org.asteriskjava.fastagi.DefaultAgiServer +``` -SYSTEM REQUIREMENTS -------------------- +## System Requirements -Asterisk-Java needs a Java Virtual Machine of at least version 1.7 ([Java SE 7.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 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 ------ +## Legal -Asterisk-Java is subject to the terms detailed in the license agreement accompanying it. +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 index 23723bf1e..a2acf6699 100644 --- a/bnd.bnd +++ b/bnd.bnd @@ -9,8 +9,7 @@ Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt -exportcontents: !*.internal.*, * Import-Package: \ - javax.net,\ - javax.net.ssl,\ - javax.script,\ - org.apache.log4j;resolution:=optional,\ - org.slf4j;resolution:=optional + !org.asteriskjava.*,\ + org.apache.logging.log4j.*;resolution:=optional,\ + org.slf4j.*;resolution:=optional,\ + * diff --git a/build.gradle b/build.gradle deleted file mode 100644 index af4d8d86d..000000000 --- a/build.gradle +++ /dev/null @@ -1,156 +0,0 @@ -apply plugin: 'java' -apply plugin: 'maven' -apply plugin: 'idea' -apply plugin: 'eclipse' -apply plugin: 'signing' - -group = 'org.asteriskjava' -version = '2.0.0.CI-SNAPSHOT' - -description = """Asterisk-Java""" - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -repositories { - - maven { url "http://repo.maven.apache.org/maven2" } -} - -dependencies { - compile group: 'log4j', name: 'log4j', version:'1.2.17' - compile group: 'org.apache.commons', name: 'commons-lang3', version:'3.1' - compile group: 'org.slf4j', name: 'slf4j-api', version:'1.7.9' - testCompile group: 'org.easymock', name: 'easymock', version:'3.3' - testCompile group: 'junit', name: 'junit', version:'4.12' - testCompile group: 'ch.qos.logback', name: 'logback-classic', version:'1.1.2' -} - -test { - testLogging { - events 'started', 'passed' - } -} - -task javadocJar(type: Jar) { - classifier = 'javadoc' - from javadoc -} - -task sourcesJar(type: Jar) { - classifier = 'sources' - from sourceSets.main.allSource -} - -artifacts { - archives javadocJar, sourcesJar -} - -signing { - required { gradle.taskGraph.hasTask("uploadArchives") } - sign configurations.archives -} - -def ossrhUsername = hasProperty('ossrhUsername') ? ossrhUsername : '' -def ossrhPassword = hasProperty('ossrhPassword') ? ossrhPassword : '' - -uploadArchives { - repositories { - mavenDeployer { - beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } - - repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { - authentication(userName: ossrhUsername, password: ossrhPassword) - } - - snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { - authentication(userName: ossrhUsername, password: ossrhPassword) - } - - pom.project { - name 'Asterisk-Java' - packaging 'jar' - // optionally artifactId can be defined here - description 'The free Java library for Asterisk PBX integration.' - url 'https://github.com/asterisk-java/asterisk-java' - - scm { - connection 'scm:git:https://github.com/asterisk-java/asterisk-java.git' - developerConnection 'scm:git:https://github.com/asterisk-java/asterisk-java.git' - url 'https://github.com/asterisk-java/asterisk-java' - } - - licenses { - license { - name 'Apache 2.0' - url 'http://www.apache.org/licenses/LICENSE-2.0.html' - } - } - - mailingLists { - mailingList { - name 'Asterisk-Java User List' - subscribe "http://lists.sourceforge.net/mailman/listinfo/asterisk-java-users" - unsubscribe "http://lists.sourceforge.net/mailman/listinfo/asterisk-java-users" - archive "http://sourceforge.net/mailarchive/forum.php?forum=asterisk-java-users" - } - mailingList { - name "Asterisk-Java Developer List" - subscribe "http://lists.sourceforge.net/mailman/listinfo/asterisk-java-devel" - unsubscribe "http://lists.sourceforge.net/mailman/listinfo/asterisk-java-devel" - archive "http://sourceforge.net/mailarchive/forum.php?forum=asterisk-java-devel" - } - } - - developers { - developer { - id 'srt' - name 'Stefan Reuter' - email 'stefan.reuter at reucon.com' - timezone '+1' - } - developer { - name 'Pierre-Yves Roger' - id 'partoutatis' - email 'partoutatis at users.sourceforge.net' - timezone '+1' - } - developer { - name 'John Hood' - id 'squinky86' - email 'john at asteriasgi.com' - organization 'Asteria Solutions Group, Inc.' - timezone '-6' - } - developer { - name 'Martin B. Smith' - id 'martins' - email 'martins at bebr.ufl.edu' - organization 'Bureau of Economic and Business Research, University of Florida' - timezone '-5' - } - developer { - name 'S. Brett Sutton' - id 'bsutton' - email 'bsutton at noojee.com.au' - organization 'Noojee Telephony Solutions Pty Ltd' - timezone '+10' - } - developer { - name 'Octavio Luna' - id 'itaqua' - email 'octavio.luna at gmail.com' - organization 'N4Utilus Take your Business to the Cloud' - timezone '-6' - } - developer { - name 'Zoumana TRAORE' - id 'zoumhussein' - email 'github at zoumanatraore dot fr' - timezone '+1' - } - } - } - } - } -} 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/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 2322723c7..000000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index cf497ceec..000000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Tue Jun 16 01:35:27 CDT 2015 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.2-all.zip diff --git a/gradlew b/gradlew deleted file mode 100755 index 91a7e269e..000000000 --- a/gradlew +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -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" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index aec99730b..000000000 --- a/gradlew.bat +++ /dev/null @@ -1,90 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/mvnw b/mvnw new file mode 100755 index 000000000..b7f064624 --- /dev/null +++ b/mvnw @@ -0,0 +1,287 @@ +#!/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.1.1 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="`/usr/libexec/java_home`"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + 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" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`\\unset -f command; \\command -v java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + printf '%s' "$(cd "$basedir"; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname $0)") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) wrapperUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $wrapperUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + QUIET="--quiet" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + QUIET="" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" + fi + [ $? -eq 0 ] || rm -f "$wrapperJarPath" + elif command -v curl > /dev/null; then + QUIET="--silent" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + QUIET="" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L + fi + [ $? -eq 0 ] || rm -f "$wrapperJarPath" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaSource="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=`cygpath --path --windows "$javaSource"` + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 000000000..474c9d6b7 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,187 @@ +@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.1.1 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml index fabb03ebc..ea3beefe2 100644 --- a/pom.xml +++ b/pom.xml @@ -1,289 +1,316 @@ - - 4.0.0 - org.asteriskjava - asterisk-java - Asterisk-Java - ${releaseVersion} - The free Java library for Asterisk PBX integration. - 2004 + + 4.0.0 + org.asteriskjava + asterisk-java + 3.42.0-SNAPSHOT - - 3.3.0 - UTF-8 - + Asterisk-Java + The free Java library for Asterisk PBX integration. + https://github.com/asterisk-java/asterisk-java + 2004 - - - The Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - + + + The Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + + - https://github.com/asterisk-java/asterisk-java + + GitHub + https://github.com/asterisk-java/asterisk-java/issues + - - - Stefan Reuter - srt - stefan.reuter at reucon.com - +1 - - - Pierre-Yves Roger - partoutatis - partoutatis at users.sourceforge.net - +1 - - - John Hood - squinky86 - john at asteriasgi.com - Asteria Solutions Group, Inc. - -6 - - - Martin B. Smith - martins - martins at bebr.ufl.edu - Bureau of Economic and Business Research, University of Florida - -5 - - - S. Brett Sutton - martins - 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 - - - - 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 - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2 - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.5 - - true - - - - biz.aQute.bnd - bnd-maven-plugin - 3.2.0 - - - - bnd-process - - - - - - org.apache.maven.plugins - maven-release-plugin - 2.5.3 - - true - false - release - deploy - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 3.0.0-M4 - - - maven-assembly-plugin - 2.5.3 - - - ${project.basedir}/src/main/assembly/bin.xml - - - - - make-assembly - package - - attached - - - - - - ${project.artifactId} - - - - org.easymock - easymock - 3.3 - test - - - junit - junit - 4.12 - test - - - org.slf4j - slf4j-api - 1.7.9 - compile - - - log4j - log4j - 1.2.17 - provided - - - ch.qos.logback - logback-classic - 1.1.2 - test - - + + + Stefan Reuter + srt + stefan.reuter at reucon.com + +1 + + + Pierre-Yves Roger + partoutatis + partoutatis at users.sourceforge.net + +1 + + + John Hood + squinky86 + john at asteriasgi.com + Asteria Solutions Group, Inc. + -6 + + + Martin B. Smith + martins + martins at bebr.ufl.edu + 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 + + + + + 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.3 + + org.reflections reflections - 0.9.12 + 0.10.2 - - - - deploy - - - - org.apache.maven.plugins - maven-source-plugin - 2.4 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - - attach-javadocs - - jar - - - - - -Xdoclint:none - -Xdoclint:none - - -Xdoclint:none - + + org.junit.jupiter + junit-jupiter + 5.14.1 + test + + + org.assertj + assertj-core + 3.27.6 + test + + + org.mockito + mockito-core + 4.10.0 + test + + + org.slf4j + slf4j-simple + 2.0.17 + test + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.5.0 + + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + true + + + + + + biz.aQute.bnd + bnd-maven-plugin + 6.4.0 + + + + bnd-process + + + + + + org.apache.maven.plugins + maven-release-plugin + 3.3.1 + + true + false + release + deploy + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.4 + + + org.apache.maven.plugins + maven-assembly-plugin + 3.8.0 + + + ${project.basedir}/src/main/assembly/bin.xml + + + + + make-assembly + package + + single + + + + + + ${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}
+
+
- - - 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://oss.sonatype.org/ + true + + +
+
+
+
- - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - EA919AF2 - - - - sign-artifacts - verify - - sign - - - - - --pinentry-mode - loopback - - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - true - - - - - - + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2 + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + +
diff --git a/pubspec.lock b/pubspec.lock deleted file mode 100644 index 4d600c6ee..000000000 --- a/pubspec.lock +++ /dev/null @@ -1,229 +0,0 @@ -# Generated by pub -# See https://dart.dev/tools/pub/glossary#lockfile -packages: - args: - dependency: "direct main" - description: - name: args - url: "https://pub.dartlang.org" - source: hosted - version: "1.5.2" - async: - dependency: transitive - description: - name: async - url: "https://pub.dartlang.org" - source: hosted - version: "2.4.0" - boolean_selector: - dependency: transitive - description: - name: boolean_selector - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.0" - charcode: - dependency: transitive - description: - name: charcode - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.3" - collection: - dependency: transitive - description: - name: collection - url: "https://pub.dartlang.org" - source: hosted - version: "1.14.12" - csv: - dependency: transitive - description: - name: csv - url: "https://pub.dartlang.org" - source: hosted - version: "4.0.3" - dshell: - dependency: "direct main" - description: - name: dshell - url: "https://pub.dartlang.org" - source: hosted - version: "1.8.2" - equatable: - dependency: transitive - description: - name: equatable - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - file: - dependency: transitive - description: - name: file - url: "https://pub.dartlang.org" - source: hosted - version: "5.1.0" - file_utils: - dependency: transitive - description: - name: file_utils - url: "https://pub.dartlang.org" - source: hosted - version: "0.1.4" - globbing: - dependency: transitive - description: - name: globbing - url: "https://pub.dartlang.org" - source: hosted - version: "0.3.0" - intl: - dependency: transitive - description: - name: intl - url: "https://pub.dartlang.org" - source: hosted - version: "0.16.1" - io: - dependency: transitive - description: - name: io - url: "https://pub.dartlang.org" - source: hosted - version: "0.3.3" - logger: - dependency: transitive - description: - name: logger - url: "https://pub.dartlang.org" - source: hosted - version: "0.8.3" - matcher: - dependency: transitive - description: - name: matcher - url: "https://pub.dartlang.org" - source: hosted - version: "0.12.6" - meta: - dependency: transitive - description: - name: meta - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.8" - mockito: - dependency: transitive - description: - name: mockito - url: "https://pub.dartlang.org" - source: hosted - version: "4.1.1" - money2: - dependency: transitive - description: - name: money2 - url: "https://pub.dartlang.org" - source: hosted - version: "1.3.0" - path: - dependency: "direct main" - description: - name: path - url: "https://pub.dartlang.org" - source: hosted - version: "1.6.4" - pub_semver: - dependency: transitive - description: - name: pub_semver - url: "https://pub.dartlang.org" - source: hosted - version: "1.4.3" - pubspec: - dependency: transitive - description: - name: pubspec - url: "https://pub.dartlang.org" - source: hosted - version: "0.1.4" - quiver: - dependency: transitive - description: - name: quiver - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.2+1" - recase: - dependency: transitive - description: - name: recase - url: "https://pub.dartlang.org" - source: hosted - version: "3.0.0" - source_span: - dependency: transitive - description: - name: source_span - url: "https://pub.dartlang.org" - source: hosted - version: "1.6.0" - stack_trace: - dependency: transitive - description: - name: stack_trace - url: "https://pub.dartlang.org" - source: hosted - version: "1.9.3" - stream_channel: - dependency: transitive - description: - name: stream_channel - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.0" - string_scanner: - dependency: transitive - description: - name: string_scanner - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.5" - term_glyph: - dependency: transitive - description: - name: term_glyph - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - test_api: - dependency: transitive - description: - name: test_api - url: "https://pub.dartlang.org" - source: hosted - version: "0.2.14" - uri: - dependency: transitive - description: - name: uri - url: "https://pub.dartlang.org" - source: hosted - version: "0.11.3+1" - utf: - dependency: transitive - description: - name: utf - url: "https://pub.dartlang.org" - source: hosted - version: "0.9.0+5" - yaml: - dependency: transitive - description: - name: yaml - url: "https://pub.dartlang.org" - source: hosted - version: "2.2.0" -sdks: - dart: ">=2.7.0 <3.0.0" diff --git a/pubspec.yaml b/pubspec.yaml deleted file mode 100644 index e3067123e..000000000 --- a/pubspec.yaml +++ /dev/null @@ -1,12 +0,0 @@ -name: asterisk_java_installer -version: 1.0.0 -environment: - sdk: '>=2.7.0 <3.0.0' -dependencies: - dshell: ^1.4.3 - args: ^1.5.2 - path: ^1.6.4 - - - - diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index 553c1b13b..000000000 --- a/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'asterisk-java' diff --git a/settings.xml b/settings.xml deleted file mode 100644 index 7480a1434..000000000 --- a/settings.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - github - - - - - github - - - central - https://repo1.maven.org/maven2 - - true - - - true - - - - - - - - - github - ${env.GITHUB_USERNAME} - ${env.GITHUB_TOKEN} - - - \ No newline at end of file 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/main/java/org/asteriskjava/.gitignore b/src/main/java/org/asteriskjava/.gitignore deleted file mode 100644 index 3595ce329..000000000 --- a/src/main/java/org/asteriskjava/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/AsteriskVersion.class -/Cli.class diff --git a/src/main/java/org/asteriskjava/AsteriskVersion.java b/src/main/java/org/asteriskjava/AsteriskVersion.java index 5e7dd4f83..df18b2ae1 100644 --- a/src/main/java/org/asteriskjava/AsteriskVersion.java +++ b/src/main/java/org/asteriskjava/AsteriskVersion.java @@ -26,8 +26,16 @@ * @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[-. ].*"; @@ -36,8 +44,12 @@ public class AsteriskVersion implements Comparable, Serializabl private final String versionString; private final Pattern patterns[]; + 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. */ @@ -96,7 +108,7 @@ public class AsteriskVersion implements Comparable, Serializabl * @since 1.0.0 */ public static final AsteriskVersion ASTERISK_13 = new AsteriskVersion(1300, "Asterisk 13", VERSION_PATTERN_13, - VERSION_PATTERN_CERTIFIED_13); + VERSION_PATTERN_CERTIFIED_13); /** * Represents the Asterisk 14 series. @@ -117,28 +129,77 @@ public class AsteriskVersion implements Comparable, Serializabl * * @since 2.1.0 */ - public static final AsteriskVersion ASTERISK_16 = new AsteriskVersion(1600, "Asterisk 16", VERSION_PATTERN_16); + 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); + + /** + * 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_16, ASTERISK_15, ASTERISK_14, - ASTERISK_13, ASTERISK_12, ASTERISK_11, ASTERISK_10, ASTERISK_1_8, ASTERISK_1_6}; + 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 03/07/2018 - public static final AsteriskVersion DEFAULT_VERSION = ASTERISK_13; + // 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, String... patterns) - { + 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) - { + for (String pattern : patterns) { this.patterns[i++] = Pattern.compile(pattern); } } @@ -149,27 +210,22 @@ private AsteriskVersion(int version, String versionString, String... patterns) * * @param o the version to compare to * @return true if this version is equal to or higher than the - * given version, false otherwise. + * given version, false otherwise. */ - public boolean isAtLeast(AsteriskVersion o) - { + public boolean isAtLeast(AsteriskVersion o) { return version >= o.version; } - public int compareTo(AsteriskVersion o) - { + 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; } @@ -179,14 +235,12 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { return version; } @Override - public String toString() - { + public String toString() { return versionString; } @@ -197,14 +251,10 @@ public String toString() * @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()) - { + public static AsteriskVersion getDetermineVersionFromString(String coreLine) { + for (AsteriskVersion version : knownVersions) { + for (Pattern pattern : version.patterns) { + if (pattern.matcher(coreLine).matches()) { return version; } } diff --git a/src/main/java/org/asteriskjava/Cli.java b/src/main/java/org/asteriskjava/Cli.java index 82e49fcbd..56d2f2857 100644 --- a/src/main/java/org/asteriskjava/Cli.java +++ b/src/main/java/org/asteriskjava/Cli.java @@ -23,7 +23,7 @@ *
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 @@ -52,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/.gitignore b/src/main/java/org/asteriskjava/config/.gitignore deleted file mode 100644 index 46cfb38ff..000000000 --- a/src/main/java/org/asteriskjava/config/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -/Category.class -/ConfigDirective.class -/ConfigElement.class -/ConfigFile.class -/ConfigFileImpl.class -/ConfigFileReader.class -/ConfigParseException.class -/ConfigVariable.class -/ExecDirective.class -/IncludeDirective.class -/MissingDirectiveParameterException.class -/MissingEqualSignException.class -/UnknownDirectiveException.class diff --git a/src/main/java/org/asteriskjava/config/Category.java b/src/main/java/org/asteriskjava/config/Category.java index 6c9532836..4ffd86036 100644 --- a/src/main/java/org/asteriskjava/config/Category.java +++ b/src/main/java/org/asteriskjava/config/Category.java @@ -4,11 +4,7 @@ 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<>(); @@ -18,18 +14,14 @@ public class Category extends ConfigElement * 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 b8150688e..08ff6e474 100644 --- a/src/main/java/org/asteriskjava/config/ConfigFile.java +++ b/src/main/java/org/asteriskjava/config/ConfigFile.java @@ -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 2810f5e20..f4510d774 100644 --- a/src/main/java/org/asteriskjava/config/ConfigFileImpl.java +++ b/src/main/java/org/asteriskjava/config/ConfigFileImpl.java @@ -16,6 +16,9 @@ */ package org.asteriskjava.config; +import org.asteriskjava.lock.LockableMap; +import org.asteriskjava.lock.Locker.LockCloser; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -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<>(); - 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) - { + 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) - { + 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 b4f08f035..474266428 100644 --- a/src/main/java/org/asteriskjava/config/ConfigFileReader.java +++ b/src/main/java/org/asteriskjava/config/ConfigFileReader.java @@ -6,15 +6,7 @@ import java.io.InputStreamReader; import java.nio.CharBuffer; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; +import java.util.*; /** * Reads and parses Asterisk configuration files.
@@ -24,15 +16,13 @@ * @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; + private static final Set> WARNING_CLASSES; - static - { + static { WARNING_CLASSES = new HashSet<>(); WARNING_CLASSES.add(MissingEqualSignException.class); WARNING_CLASSES.add(UnknownDirectiveException.class); @@ -46,24 +36,19 @@ 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<>(); } - public ConfigFile readFile(String configfile) - { + public ConfigFile readFile(String configfile) { final ConfigFile result; try (BufferedReader reader = new BufferedReader( - new InputStreamReader(new FileInputStream(configfile), StandardCharsets.UTF_8))) - { + new InputStreamReader(new FileInputStream(configfile), StandardCharsets.UTF_8))) { readFile(configfile, reader); - } - catch (Exception e) - { + } catch (Exception e) { // ignored } @@ -72,8 +57,7 @@ public ConfigFile readFile(String configfile) return result; } - void reset() - { + void reset() { commentBlock = new StringBuilder(); categories.clear(); warnings.clear(); @@ -81,25 +65,21 @@ void reset() currentCommentLevel = 0; } - Collection getCategories() - { + Collection getCategories() { return categories.values(); } - public Collection getWarnings() - { + 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); @@ -110,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; @@ -120,46 +99,38 @@ 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); - 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) - { + && 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); - 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) - @@ -182,18 +153,14 @@ else if (inComment() && position >= 2 && buffer.get(position - 1) == COMMENT_TAG // System.out.println("Buffer compacted"); continue; } - } - else - { - if (!inComment()) - { + } 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()) - { + while (buffer.hasRemaining()) { lineCommentBuilder.append(buffer.get()); } break; @@ -204,12 +171,9 @@ else if (inComment() && position >= 2 && buffer.get(position - 1) == COMMENT_TAG } } - if (inComment()) - { + if (inComment()) { commentBlock.append(c); - } - else - { + } else { // System.out.println("Added '" + c + "' to processLine"); processLineBuilder.append(c); } @@ -223,43 +187,34 @@ else if (inComment() && position >= 2 && buffer.get(position - 1) == COMMENT_TAG lineCommentString = lineCommentBuilder.toString().trim(); // System.out.println("process line: '" + processLineString + "'"); - if (processLineString.length() == 0) - { - if (lineCommentString.length() != 0) - { + 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) - { + } catch (ConfigParseException e) { // some parsing exceptions are treated as warnings by Asterisk, we // mirror this behavior. - if (WARNING_CLASSES.contains(e.getClass())) - { + if (WARNING_CLASSES.contains(e.getClass())) { warnings.add(e); return null; } 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()); } @@ -267,27 +222,22 @@ else if (inComment() && position >= 2 && buffer.get(position - 1) == COMMENT_TAG 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) - { + if (currentCategory == null) { throw new ConfigParseException(configfile, lineno, "parse error: No category context for line %d of %s", lineno, configfile); } @@ -299,8 +249,7 @@ 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; @@ -315,8 +264,7 @@ protected Category parseCategoryHeader(String configfile, int lineno, String lin */ nameEndPos = line.indexOf(']'); - if (nameEndPos == -1) - { + if (nameEndPos == -1) { throw new ConfigParseException(configfile, lineno, "parse error: no closing ']', line %d of %s", lineno, configfile); } @@ -324,34 +272,29 @@ protected Category parseCategoryHeader(String configfile, int lineno, String lin 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) - { + 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); @@ -359,14 +302,11 @@ else if ("+".equals(cur)) // category addition // todo implement category addition // category = categoryToAddTo; - } - else - { + } 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); @@ -380,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; @@ -390,76 +329,60 @@ 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) == '>')) - { + && (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 - { + } else { throw new UnknownDirectiveException(configfile, lineno, "Unknown directive '%s' at line %d of %s", name, lineno, configfile); } - if (param.length() == 0) - { - if (name == null) - { + 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), + "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) - { + if (pos == -1) { throw new MissingEqualSignException(configfile, lineno, "No '=' (equal sign) in line %d of %s", lineno, configfile); } @@ -467,8 +390,7 @@ protected ConfigVariable parseVariable(String configfile, int lineno, String lin 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++; } @@ -476,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 e872ca7ad..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 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/.gitignore b/src/main/java/org/asteriskjava/config/dialplan/.gitignore deleted file mode 100644 index 6b973a36c..000000000 --- a/src/main/java/org/asteriskjava/config/dialplan/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/ConfigExtension.class -/ConfigInclude.class -/ExtensionsConfigFile.class -/ExtensionsConfigFileReader.class 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 9a875ff6b..65593428f 100644 --- a/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFileReader.java +++ b/src/main/java/org/asteriskjava/config/dialplan/ExtensionsConfigFileReader.java @@ -1,19 +1,18 @@ package org.asteriskjava.config.dialplan; -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 @@ -21,8 +20,7 @@ public class ExtensionsConfigFileReader extends ConfigFileReader * 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 @@ -37,14 +35,11 @@ protected ConfigElement processTextLine(String configfile, int lineno, String li * 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()); @@ -59,8 +54,7 @@ else if (line.trim().startsWith("include")) } /* 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")) @@ -85,60 +79,47 @@ protected ConfigExtension parseExtension(String configfile, int lineno, String l } /* Roughly corresponds to pbx_config.c:2276 */ - private static String[] harvestApplicationWithArguments(String arg) - { + private static String[] harvestApplicationWithArguments(String arg) { List args = new ArrayList<>(); - if (arg.trim().length() >= 0) - { + 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)) - { + if (firstc != -1 && (firstp == -1 || firstc < firstp)) { /* comma found, no parenthesis */ /* or both found, but comma found first */ String[] split = arg.split(","); appl = split[0]; for (int i = 1; i < split.length; i++) data += split[i] + (i + 1 < split.length ? "," : ""); - } - else if (firstc == -1 && firstp == -1) - { + } else if (firstc == -1 && firstp == -1) { /* Neither found */ data = ""; - } - else - { + } else { /* Final remaining case is parenthesis found first */ String[] split = arg.split("\\("); appl = split[0]; for (int i = 1; i < split.length; i++) data += split[i] + (i + 1 < split.length ? "(" : ""); int end = data.lastIndexOf(')'); - if (end == -1) - { + if (end == -1) { // ast_log(LOG_WARNING, "No closing parenthesis found? // '%s(%s'\n", appl, data); - } - else if (end == data.length() - 1) - { + } else if (end == data.length() - 1) { data = data.substring(0, end); } data = processQuotesAndSlashes(data, ',', '|'); } - if (!appl.trim().equals("")) - { + if (!appl.trim().equals("")) { args.add(appl.trim()); - if (!data.trim().equals("")) - { + if (!data.trim().equals("")) { String[] dataSplit = data.split("\\|"); - for (String aDataSplit : dataSplit) - { + for (String aDataSplit : dataSplit) { args.add(aDataSplit.trim()); } } @@ -148,8 +129,7 @@ else if (end == data.length() - 1) return args.toArray(new String[args.size()]); } - public ExtensionsConfigFile readExtensionsFile(String configfile) - { + public ExtensionsConfigFile readExtensionsFile(String configfile) { super.readFile(configfile); /* at some point, we may want to resolve back references */ /* that include or goto from one context to another */ @@ -157,32 +137,22 @@ public ExtensionsConfigFile readExtensionsFile(String configfile) } /* ast_process_quotes_and_slashes rewritten to be java friendly */ - private static String processQuotesAndSlashes(String start, char find, char replace_with) - { + private static String processQuotesAndSlashes(String start, char find, char replace_with) { String dataPut = ""; int inEscape = 0; int inQuotes = 0; char[] startChars = start.toCharArray(); - for (char startChar : startChars) - { - if (inEscape != 0) - { + for (char startChar : startChars) { + if (inEscape != 0) { dataPut += startChar; /* Always goes verbatim */ inEscape = 0; - } - else - { - if (startChar == '\\') - { + } else { + if (startChar == '\\') { inEscape = 1; /* Do not copy \ into the data */ - } - else if (startChar == '\'') - { + } else if (startChar == '\'') { inQuotes = 1 - inQuotes; /* Do not copy ' into the data */ - } - else - { + } else { /* Replace , with |, unless in quotes */ dataPut += inQuotes != 0 ? startChar : ((startChar == find) ? replace_with : startChar); } diff --git a/src/main/java/org/asteriskjava/config/dialplan/package.html b/src/main/java/org/asteriskjava/config/dialplan/package.html index 7783de3c2..b98059c8d 100644 --- a/src/main/java/org/asteriskjava/config/dialplan/package.html +++ b/src/main/java/org/asteriskjava/config/dialplan/package.html @@ -1,27 +1,27 @@ - +

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 index fb4de37e9..3a25b60f2 100644 --- a/src/main/java/org/asteriskjava/examples/activities/BlindTransfer.java +++ b/src/main/java/org/asteriskjava/examples/activities/BlindTransfer.java @@ -1,33 +1,23 @@ package org.asteriskjava.examples.activities; -import java.io.IOException; - import org.asteriskjava.manager.AuthenticationFailedException; import org.asteriskjava.manager.TimeoutException; -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.ActivityStatusEnum; -import org.asteriskjava.pbx.Call; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.Call.OperandChannel; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXFactory; -import org.asteriskjava.pbx.TechType; -import org.asteriskjava.pbx.Trunk; 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 -{ +public class BlindTransfer { - static public void main(String[] args) throws IOException, AuthenticationFailedException, TimeoutException - { + static public void main(String[] args) throws IOException, AuthenticationFailedException, TimeoutException { /** * Initialise the PBX Factory. You need to implement your own * AsteriskSettings class. @@ -46,8 +36,7 @@ static public void main(String[] args) throws IOException, AuthenticationFailedE blindTransfer(); } - static private void blindTransfer() - { + static private void blindTransfer() { String dialOptions = ""; PBX pbx = PBXFactory.getActivePBX(); @@ -70,14 +59,11 @@ static private void blindTransfer() // Start the dial and return immediately. // progress is provided via the ActivityCallback. - pbx.dial(from, fromCallerID, to, toCallerID, new ActivityCallback() - { + pbx.dial(from, fromCallerID, to, toCallerID, new ActivityCallback() { @Override - public void progress(DialActivity activity, ActivityStatusEnum status, String message) - { - if (status == ActivityStatusEnum.SUCCESS) - { + 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 @@ -85,13 +71,11 @@ public void progress(DialActivity activity, ActivityStatusEnum status, String me 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() - { + new ActivityCallback() { @Override public void progress(BlindTransferActivity activity, ActivityStatusEnum status, - String message) - { + String message) { // if success the blind transfer completed. } }, ""); diff --git a/src/main/java/org/asteriskjava/examples/activities/Dial.java b/src/main/java/org/asteriskjava/examples/activities/Dial.java index edfe26690..06e5821cf 100644 --- a/src/main/java/org/asteriskjava/examples/activities/Dial.java +++ b/src/main/java/org/asteriskjava/examples/activities/Dial.java @@ -1,25 +1,14 @@ package org.asteriskjava.examples.activities; -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.ActivityStatusEnum; -import org.asteriskjava.pbx.Call; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; -import org.asteriskjava.pbx.TechType; -import org.asteriskjava.pbx.Trunk; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.activities.DialActivity; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class Dial -{ +public class Dial { static private Log logger = LogFactory.getLog(Dial.class); - static public void main(String[] args) - { + static public void main(String[] args) { syncDial(); asyncDial(); @@ -30,10 +19,8 @@ static public void main(String[] args) * 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 - { + static private void syncDial() { + try { String dialOptions = ""; PBX pbx = PBXFactory.getActivePBX(); @@ -66,15 +53,12 @@ static private void syncDial() logger.warn("Hanging up"); pbx.hangup(call); - } - catch (PBXException | InterruptedException e) - { + } catch (PBXException | InterruptedException e) { System.out.println(e); } } - static private void asyncDial() - { + static private void asyncDial() { String dialOptions = ""; PBX pbx = PBXFactory.getActivePBX(); @@ -90,25 +74,19 @@ static private void asyncDial() // Start the dial and return immediately. // progress is provided via the ActivityCallback. - pbx.dial(from, fromCallerID, to, toCallerID, new ActivityCallback() - { + pbx.dial(from, fromCallerID, to, toCallerID, new ActivityCallback() { @Override - public void progress(DialActivity activity, ActivityStatusEnum status, String message) - { - if (status == ActivityStatusEnum.SUCCESS) - { + public void progress(DialActivity activity, ActivityStatusEnum status, String message) { + if (status == ActivityStatusEnum.SUCCESS) { System.out.println("Dial all good"); - try - { + 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) - { + } catch (PBXException e) { System.out.println(e); } } diff --git a/src/main/java/org/asteriskjava/examples/activities/ExamplesAsteriskSettings.java b/src/main/java/org/asteriskjava/examples/activities/ExamplesAsteriskSettings.java index f7a5d0629..bcaa2a672 100644 --- a/src/main/java/org/asteriskjava/examples/activities/ExamplesAsteriskSettings.java +++ b/src/main/java/org/asteriskjava/examples/activities/ExamplesAsteriskSettings.java @@ -2,35 +2,30 @@ import org.asteriskjava.pbx.DefaultAsteriskSettings; -public class ExamplesAsteriskSettings extends 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 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 + @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. + @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"; - } + @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 index 3034785d8..c13b998be 100644 --- a/src/main/java/org/asteriskjava/examples/activities/Hold.java +++ b/src/main/java/org/asteriskjava/examples/activities/Hold.java @@ -1,32 +1,21 @@ package org.asteriskjava.examples.activities; -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.ActivityStatusEnum; -import org.asteriskjava.pbx.Call; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXFactory; -import org.asteriskjava.pbx.TechType; +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 -{ +public class Hold { - static public void main(String[] args) - { + static public void main(String[] args) { hold(); } - static private void hold() - { + static private void hold() { String dialOptions = ""; PBX pbx = PBXFactory.getActivePBX(); @@ -42,14 +31,11 @@ static private void hold() // Start the dial and return immediately. // progress is provided via the ActivityCallback. - pbx.dial(from, fromCallerID, to, toCallerID, new ActivityCallback() - { + pbx.dial(from, fromCallerID, to, toCallerID, new ActivityCallback() { @Override - public void progress(DialActivity activity, ActivityStatusEnum status, String message) - { - if (status == ActivityStatusEnum.SUCCESS) - { + 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 diff --git a/src/main/java/org/asteriskjava/examples/fastagi/ExampleCallIn.java b/src/main/java/org/asteriskjava/examples/fastagi/ExampleCallIn.java index debdd01ae..66e8dd8ab 100644 --- a/src/main/java/org/asteriskjava/examples/fastagi/ExampleCallIn.java +++ b/src/main/java/org/asteriskjava/examples/fastagi/ExampleCallIn.java @@ -2,22 +2,22 @@ /* 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 index 916b40c85..ec313ea80 100644 --- a/src/main/java/org/asteriskjava/examples/fastagi/fastagi.properties +++ b/src/main/java/org/asteriskjava/examples/fastagi/fastagi.properties @@ -1 +1 @@ -callin.agi = ExampleCallIn \ No newline at end of file +callin.agi=ExampleCallIn diff --git a/src/main/java/org/asteriskjava/fastagi/.gitignore b/src/main/java/org/asteriskjava/fastagi/.gitignore deleted file mode 100644 index 98a4ac9ad..000000000 --- a/src/main/java/org/asteriskjava/fastagi/.gitignore +++ /dev/null @@ -1,31 +0,0 @@ -/AbstractAgiServer.class -/AbstractMappingStrategy.class -/AgiChannel.class -/AgiException.class -/AgiHangupException.class -/AgiNetworkException.class -/AgiOperations.class -/AgiRequest.class -/AgiScript.class -/AgiServer.class -/AgiServerThread$1.class -/AgiServerThread$AgiThreadUncaughtExceptionHanlder.class -/AgiServerThread.class -/AgiSpeechException.class -/AsyncAgiServer.class -/BaseAgiScript.class -/ClassNameMappingStrategy.class -/CompositeMappingStrategy.class -/DefaultAgiServer.class -/InvalidCommandSyntaxException.class -/InvalidOrUnknownCommandException.class -/MappingStrategy.class -/NamedAgiScript.class -/ResourceBundleMappingStrategy.class -/ScriptEngineMappingStrategy$1.class -/ScriptEngineMappingStrategy$ScriptEngineAgiScript.class -/ScriptEngineMappingStrategy.class -/SimpleMappingStrategy.class -/SpeechRecognitionResult$SpeechResult.class -/SpeechRecognitionResult.class -/StaticMappingStrategy.class diff --git a/src/main/java/org/asteriskjava/fastagi/AbstractAgiServer.java b/src/main/java/org/asteriskjava/fastagi/AbstractAgiServer.java index f6782de25..7085a3b41 100644 --- a/src/main/java/org/asteriskjava/fastagi/AbstractAgiServer.java +++ b/src/main/java/org/asteriskjava/fastagi/AbstractAgiServer.java @@ -1,22 +1,21 @@ package org.asteriskjava.fastagi; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - import org.asteriskjava.fastagi.internal.DefaultAgiChannelFactory; import org.asteriskjava.util.DaemonThreadFactory; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + /** * 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()); /** @@ -59,8 +58,7 @@ public abstract class AbstractAgiServer private volatile boolean die = false; - public AbstractAgiServer() - { + public AbstractAgiServer() { this(new DefaultAgiChannelFactory()); } @@ -68,13 +66,11 @@ public AbstractAgiServer() * Creates a new AbstractAgiServer with the given channel factory. * * @param agiChannelFactory the AgiChannelFactory to use for creating new - * AgiChannel instances. + * 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"); } @@ -87,10 +83,9 @@ public AbstractAgiServer(AgiChannelFactory agiChannelFactory) * instances. * * @return the AgiChannelFactory to use for creating new AgiChannel - * instances. + * instances. */ - protected AgiChannelFactory getAgiChannelFactory() - { + protected AgiChannelFactory getAgiChannelFactory() { return this.agiChannelFactory; } @@ -100,8 +95,7 @@ protected AgiChannelFactory getAgiChannelFactory() * @return the default number of worker threads in the thread pool. * @since 1.0.0 */ - public synchronized int getPoolSize() - { + public synchronized int getPoolSize() { return poolSize; } @@ -115,15 +109,12 @@ public synchronized int getPoolSize() * @throws IllegalArgumentException if the new pool size is negative * @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; @@ -135,8 +126,7 @@ public synchronized void setPoolSize(int poolSize) * @return the maximum number of worker threads in the thread pool. * @since 1.0.0 */ - public synchronized int getMaximumPoolSize() - { + public synchronized int getMaximumPoolSize() { return maximumPoolSize; } @@ -148,24 +138,20 @@ public synchronized int getMaximumPoolSize() * * @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. + * 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) - { + 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; @@ -177,36 +163,29 @@ public synchronized void setMaximumPoolSize(int maximumPoolSize) * * @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 - { + protected void finalize() throws Throwable { this.die = true; - if (pool != null) - { + if (pool != null) { pool.shutdown(); } @@ -220,10 +199,8 @@ protected void finalize() throws Throwable * @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; } @@ -231,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."); } @@ -250,24 +224,20 @@ private synchronized ThreadPoolExecutor getPool() /** * 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) - { + public int getPoolActiveTaskCount() { + if (pool != null) { return pool.getActiveCount(); } return -1; }// getPoolActiveCount - public int getPoolActiveThreadCount() - { - if (pool != null) - { + public int getPoolActiveThreadCount() { + if (pool != null) { return pool.getPoolSize(); } return -1; @@ -281,7 +251,7 @@ public int getPoolActiveThreadCount() *

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

      * return Executors.newCachedThreadPool(new DaemonThreadFactory());
      * 
@@ -290,8 +260,7 @@ public int getPoolActiveThreadCount() * @see #setPoolSize(int) * @see #setMaximumPoolSize(int) */ - protected ThreadPoolExecutor createPool() - { + 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 bcf043784..333a65c5f 100644 --- a/src/main/java/org/asteriskjava/fastagi/AbstractMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/AbstractMappingStrategy.java @@ -16,6 +16,10 @@ */ 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; @@ -24,9 +28,6 @@ import java.util.ArrayList; import java.util.List; -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; - /** * Abstract base class for common mapping strategies.
* If you implement your own mapping strategy you can derive from this class. @@ -34,8 +35,7 @@ * @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. */ @@ -45,8 +45,7 @@ public abstract class AbstractMappingStrategy implements MappingStrategy private ClassLoader defaultClassLoader = null; @Override - public AgiScript determineScript(AgiRequest request, AgiChannel channel) - { + public AgiScript determineScript(AgiRequest request, AgiChannel channel) { return determineScript(request); } @@ -64,36 +63,28 @@ public AgiScript determineScript(AgiRequest request, AgiChannel channel) * 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<>(); - 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.isEmpty()) - { + if (dirUrls.isEmpty()) { return parentClassLoader; } @@ -107,47 +98,39 @@ protected synchronized ClassLoader getClassLoader() * Creates a new instance of an AGI script. * * @param className Class name of the AGI script. The class must implement - * {@link AgiScript}. + * {@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) - { - Class< ? > tmpClass; + protected AgiScript createAgiScriptInstance(String className) { + Class tmpClass; Class agiScriptClass; Constructor constructor; AgiScript agiScript; 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 023dbdba3..4a0398b73 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiChannel.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiChannel.java @@ -29,8 +29,7 @@ * @author srt * @version $Id$ */ -public interface AgiChannel -{ +public interface AgiChannel { /** * Returns the name of the channel. * @@ -50,7 +49,7 @@ public interface AgiChannel * Asterisk. * * @return the reply received in response to the last command sent to - * Asterisk or null if none has yet been received. + * Asterisk or null if none has yet been received. * @since 1.0.0 */ AgiReply getLastReply(); @@ -62,7 +61,7 @@ public interface AgiChannel * @param command the command to send. * @return the reply of the asterisk server containing the return value. * @throws AgiException if the command can't be sent to Asterisk (for - * example because the channel has been hung up) + * example because the channel has been hung up) */ AgiReply sendCommand(AgiCommand command) throws AgiException; @@ -85,9 +84,9 @@ public interface AgiChannel * in the future. * * @param time the number of seconds before this channel is automatically - * hung up. - *

- * 0 disables the autohangup feature. + * hung up. + *

+ * 0 disables the autohangup feature. * @since 0.2 */ void setAutoHangup(int time) throws AgiException; @@ -96,7 +95,7 @@ public interface AgiChannel * Sets the caller id on the current channel. * * @param callerId the raw caller id to set, for example - * "John Doe<1234>". + * "John Doe<1234>". * @since 0.2 */ void setCallerId(String callerId) throws AgiException; @@ -112,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 musiconhold.conf. + * configures in Asterisk's musiconhold.conf. * @since 0.2 */ void playMusicOnHold(String musicOnHoldClass) throws AgiException; @@ -160,11 +159,11 @@ public interface AgiChannel * presses '#' or the timeout occurs. The user may interrupt the streaming * by starting to enter digits. * - * @param file the name of the file to play + * @param file the name of the file to play * @param timeout the timeout in milliseconds to wait for user input. - *

- * 0 means standard timeout value, -1 means "ludicrous time" - * (essentially never times out). + *

+ * 0 means standard timeout value, -1 means "ludicrous time" + * (essentially never times out). * @return a String containing the DTMF the user entered * @since 0.2 */ @@ -176,13 +175,13 @@ public interface AgiChannel * been entered. The user may interrupt the streaming 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. - *

- * 0 means standard timeout value, -1 means "ludicrous time" - * (essentially never times out). + * @param file the name of the file to play + * @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 - * enter + * enter * @return a String containing the DTMF the user entered * @since 0.2 */ @@ -194,9 +193,9 @@ public interface AgiChannel * it waits for the default timeout of 5 seconds still waiting for the user * to press a digit. * - * @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 the user is expected to - * press. + * press. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -208,11 +207,11 @@ public interface AgiChannel * it waits for the specified timeout still waiting for the user to press a * digit. * - * @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 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. + * press. + * @param timeout the timeout in milliseconds to wait if none of the defined + * esacpe digits was presses while streaming. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -220,7 +219,7 @@ public interface AgiChannel /** * since at least asterisk 13 - * + * * @param room * @param profile * @throws AgiException @@ -229,7 +228,7 @@ public interface AgiChannel /** * since at least asterisk 1.4 - * + * * @param room * @param options * @throws AgiException @@ -240,9 +239,9 @@ public interface AgiChannel * Executes the given command. * * @param application the name of the application to execute, for example - * "Dial". + * "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; @@ -251,11 +250,11 @@ public interface AgiChannel * Executes the given command. * * @param application the name of the application to execute, for example - * "Dial". - * @param options the parameters to pass to the application, for example - * "SIP/123". + * "Dial". + * @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; @@ -272,7 +271,7 @@ public interface AgiChannel * Sets the extension for continuation upon exiting the application. * * @param extension the extension for continuation upon exiting the - * application. + * application. * @since 0.2 */ void setExtension(String extension) throws AgiException; @@ -281,7 +280,7 @@ public interface AgiChannel * Sets the priority or label for continuation upon exiting the application. * * @param priority the priority or label for continuation upon exiting the - * application. + * application. * @since 0.2 */ void setPriority(String priority) throws AgiException; @@ -298,9 +297,9 @@ public interface AgiChannel * Plays the given file and allows the user to escape by pressing one of the * given digit. * - * @param file name of the file to play. + * @param file name of the file to play. * @param escapeDigits a String containing the DTMF digits that allow the - * user to escape. + * user to escape. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -310,10 +309,10 @@ public interface AgiChannel * 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 file name of the file to play. * @param escapeDigits a String containing the DTMF digits that allow the - * user to escape. - * @param offset the offset samples to skip before streaming. + * user to escape. + * @param offset the offset samples to skip before streaming. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 1.0.0 */ @@ -331,9 +330,9 @@ public interface AgiChannel * Says the given number, returning early if any of the given DTMF number * are received on the channel. * - * @param digits the digit string to say. + * @param digits the digit string to say. * @param escapeDigits a String containing the DTMF digits that allow the - * user to escape. + * user to escape. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -351,9 +350,9 @@ public interface AgiChannel * Says the given number, returning early if any of the given DTMF number * are received on the channel. * - * @param number the number to say. + * @param number the number to say. * @param escapeDigits a String containing the DTMF digits that allow the - * user to escape. + * user to escape. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -371,9 +370,9 @@ public interface AgiChannel * Says the given character string with phonetics, returning early if any of * the given DTMF number are received on the channel. * - * @param text the text to say. + * @param text the text to say. * @param escapeDigits a String containing the DTMF digits that allow the - * user to escape. + * user to escape. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -391,9 +390,9 @@ public interface AgiChannel * Says the given character string, returning early if any of the given DTMF * number are received on the channel. * - * @param text the text to say. + * @param text the text to say. * @param escapeDigits a String containing the DTMF digits that allow the - * user to escape. + * user to escape. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -411,9 +410,9 @@ public interface AgiChannel * Says the given time, returning early if any of the given DTMF number are * received on the channel. * - * @param time 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. * @param escapeDigits a String containing the DTMF digits that allow the - * user to escape. + * user to escape. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -438,7 +437,7 @@ public interface AgiChannel * 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 name the name of the variable (or function call) to set. * @param value the new value to set. * @since 0.2 */ @@ -448,7 +447,7 @@ public interface AgiChannel * Waits up to 'timeout' milliseconds to receive a DTMF digit. * * @param timeout timeout the milliseconds to wait for the channel to - * receive a DTMF digit, -1 will wait forever. + * receive a DTMF digit, -1 will wait forever. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -462,7 +461,7 @@ public interface AgiChannel * * @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 */ @@ -475,10 +474,10 @@ public interface AgiChannel *

* Available since Asterisk 1.2. * - * @param expr the the expression to evaluate. + * @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; @@ -489,7 +488,7 @@ public interface AgiChannel * Available since Asterisk 1.2. * * @param time the time to say in seconds elapsed since 00:00:00 on January - * 1, 1970, Coordinated Universal Time (UTC) + * 1, 1970, Coordinated Universal Time (UTC) * @since 0.2 */ void sayDateTime(long time) throws AgiException; @@ -500,10 +499,10 @@ public interface AgiChannel *

* Available since Asterisk 1.2. * - * @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) * @param escapeDigits the digits that allow the user to interrupt this - * command or null for none. + * command or null for none. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -515,11 +514,11 @@ public interface AgiChannel *

* Available since Asterisk 1.2. * - * @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) * @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 + * command or null for none. + * @param format the format the time should be said in * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -531,13 +530,13 @@ public interface AgiChannel *

* Available since Asterisk 1.2. * - * @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) * @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". + * 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". * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.2 */ @@ -547,9 +546,9 @@ public interface AgiChannel * 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. + * @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. + * there is no such value. * @since 0.3 */ String databaseGet(String family, String key) throws AgiException; @@ -559,8 +558,8 @@ public interface AgiChannel * 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. - * @param value the new value of the entry. + * @param key the key of the entry to add or update. + * @param value the new value of the entry. * @since 0.3 */ void databasePut(String family, String key, String value) throws AgiException; @@ -569,7 +568,7 @@ public interface AgiChannel * Deletes an entry in the Asterisk database for a given family and key. * * @param family the family of the entry to delete. - * @param key the key of the entry to delete. + * @param key the key of the entry to delete. * @since 0.3 */ void databaseDel(String family, String key) throws AgiException; @@ -586,7 +585,7 @@ public interface AgiChannel * 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 family the family of the entries to delete. * @param keytree the prefix of the keys of the entries to delete. * @since 0.3 */ @@ -596,7 +595,7 @@ public interface AgiChannel * Sends a message to the Asterisk console via the verbose message system. * * @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]. * @since 0.3 */ void verbose(String message, int level) throws AgiException; @@ -604,12 +603,12 @@ public interface AgiChannel /** * Record to a file until a given dtmf digit in the sequence is received. * - * @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 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. + * recording. + * @param timeout the maximum record time in milliseconds, or -1 for no + * timeout. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.3 */ @@ -618,17 +617,17 @@ public interface AgiChannel /** * Record to a file until a given dtmf digit in the sequence is received. * - * @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 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. + * 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. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.3 */ @@ -649,9 +648,9 @@ char recordFile(String file, String format, String escapeDigits, int timeout, in * "#" 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 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. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.3 */ @@ -662,11 +661,11 @@ char recordFile(String file, String format, String escapeDigits, int timeout, in * "#" 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 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. + * this command. May be null if you don't want the + * user to interrupt. + * @param offset the offset samples to skip before streaming. * @return the DTMF digit pressed or 0x0 if none was pressed. * @since 0.3 */ @@ -678,20 +677,20 @@ char recordFile(String file, String format, String escapeDigits, int timeout, in * 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 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. + * 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 forwardDigit the digit for fast forward. - * @param rewindDigit the digit for rewind. - * @param pauseDigit the digit for pause and unpause. + * @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, - String pauseDigit) throws AgiException; + String pauseDigit) throws AgiException; /** * Creates a speech object that uses the default speech engine. The speech @@ -719,7 +718,7 @@ char controlStreamFile(String file, String escapeDigits, int offset, String forw /** * Sets the speech engine setting indicated by name to the given value. * - * @param name the name of the setting to set. + * @param name the name of the setting to set. * @param value the value to set. * @throws AgiSpeechException if the setting cannot be set. * @since 1.0.0 @@ -743,10 +742,10 @@ char controlStreamFile(String file, String escapeDigits, int offset, String forw * 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 path the path to the grammar to load. + * {@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) * @see #speechActivateGrammar(String) @@ -788,11 +787,11 @@ char controlStreamFile(String file, String escapeDigits, int offset, String forw /** * Plays the given prompt while listening for speech and DTMF. * - * @param prompt the name of the file to stream, must not include extension. + * @param prompt the name of the file to stream, must not include extension. * @param timeout the timeout in milliseconds to wait for user input. - *

- * 0 means standard timeout value, -1 means "ludicrous time" - * (essentially never times out). + *

+ * 0 means standard timeout value, -1 means "ludicrous time" + * (essentially never times out). * @return the recognition result * @since 1.0.0 */ @@ -801,13 +800,13 @@ char controlStreamFile(String file, String escapeDigits, int offset, String forw /** * Plays the given prompt while listening for speech and DTMF. * - * @param prompt the name of the file to stream, must not include extension. + * @param prompt the name of the file to stream, must not include extension. * @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. + *

+ * 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. * @return the recognition result * @since 1.0.0 */ @@ -820,11 +819,11 @@ char controlStreamFile(String file, String escapeDigits, int offset, String forw * 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 context the context for continuation upon exiting the application. * @param extension the extension for continuation upon exiting the - * application. - * @param priority the priority or label for continuation upon exiting the - * application. + * application. + * @param priority the priority or label for continuation upon exiting the + * application. * @see #setContext(String) * @see #setExtension(String) * @see #setPriority(String) @@ -836,9 +835,9 @@ char controlStreamFile(String file, String escapeDigits, int offset, String forw * Calls a subroutine in the dialplan
* This method is available since Asterisk 1.6. * - * @param context the context of the called subroutine. + * @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 priority the priority of the called extension. * @since 1.0.0 */ void gosub(String context, String extension, String priority) throws AgiException; @@ -849,19 +848,19 @@ char controlStreamFile(String file, String escapeDigits, int offset, String forw *
* This method is available since Asterisk 1.6. * - * @param context the context of the called subroutine. + * @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 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. + * should be separated by comma. They will accessible in the form + * of ${ARG1}, ${ARG2}, etc in the subroutine body. * @since 1.0.0 */ void gosub(String context, String extension, String priority, String... arguments) throws AgiException; /** * invoke the dial command - * + * * @param target * @param timeout * @param options @@ -871,7 +870,7 @@ char controlStreamFile(String file, String escapeDigits, int offset, String forw /** * invoke the bridge command - * + * * @param channelName * @param options * @throws AgiException diff --git a/src/main/java/org/asteriskjava/fastagi/AgiChannelFactory.java b/src/main/java/org/asteriskjava/fastagi/AgiChannelFactory.java index 100eca517..362031f4c 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiChannelFactory.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiChannelFactory.java @@ -9,8 +9,7 @@ * * @since 1.0.0 */ -public interface AgiChannelFactory -{ +public interface AgiChannelFactory { /** * Creates a new AgiChannel. * 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 0a61a1810..a33b58ac5 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiOperations.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiOperations.java @@ -24,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"); } @@ -80,391 +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 - { + 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 - { + 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 - { + 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 - { + 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 - { + public void confbridge(String room, String profile) throws AgiException { getChannel().confbridge(room, profile); } @Override - public void meetme(String room, String options) throws AgiException - { + 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 - { + public void dial(String target, int timeout, String options) throws AgiException { getChannel().dial(target, timeout, options); } @Override - public void bridge(String channelName, String options) throws AgiException - { + public void bridge(String channelName, String options) throws AgiException { getChannel().bridge(channelName, options); } @Override - public void queue(String queue) throws AgiException - { + public void queue(String queue) throws AgiException { getChannel().queue(queue); } @Override - public AsteriskVersion getAsteriskVersion() - { + public AsteriskVersion getAsteriskVersion() { return getChannel().getAsteriskVersion(); } } diff --git a/src/main/java/org/asteriskjava/fastagi/AgiReader.java b/src/main/java/org/asteriskjava/fastagi/AgiReader.java index 68850f90e..0a50f7ae1 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiReader.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiReader.java @@ -21,15 +21,14 @@ /** * 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. */ @@ -37,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 64115a54c..d98b5b47c 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiRequest.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiRequest.java @@ -16,24 +16,23 @@ */ package org.asteriskjava.fastagi; +import org.asteriskjava.AsteriskVersion; + import java.net.InetAddress; import java.util.Map; -import org.asteriskjava.AsteriskVersion; - /** * 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(); @@ -44,7 +43,7 @@ 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(); @@ -52,36 +51,36 @@ public interface AgiRequest /** * Returns the full URL of the requestURL in the form * agi://host[:port][/script][?param1=value1&param2=value2]. - * + * * @return the full URL of the requestURL in the form - * agi://host[:port][/script][?param1=value1&param2=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(); @@ -90,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(); @@ -127,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(); @@ -179,7 +179,7 @@ public interface AgiRequest /** * Returns the Callerid presentation/screening.

* Available since Asterisk 1.2. - * + * * @return the Callerid presentation/screening. * @since 0.2 */ @@ -188,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 */ @@ -197,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 */ @@ -206,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 */ @@ -221,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) */ @@ -234,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. */ @@ -242,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(); @@ -264,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 */ @@ -273,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 */ @@ -282,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 */ @@ -291,7 +291,7 @@ 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 */ 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 16eea9520..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,43 @@ *

    *
  • 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; @@ -78,7 +77,7 @@ public interface AgiServer * Connection is dropped if it stales on read longer than the timeout. * * @param socketReadTimeout the read timeout value to be used in - * milliseconds. + * milliseconds. * @see java.net.Socket#setSoTimeout(int) * @since 3.0.0 */ diff --git a/src/main/java/org/asteriskjava/fastagi/AgiServerThread.java b/src/main/java/org/asteriskjava/fastagi/AgiServerThread.java index 77a226cfe..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 synchronized void setAgiServer(AgiServer agiServer) - { + public synchronized void setAgiServer(AgiServer agiServer) { this.agiServer = agiServer; } @@ -85,14 +81,13 @@ public synchronized 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/AgiWriter.java b/src/main/java/org/asteriskjava/fastagi/AgiWriter.java index 0b4527f5a..29746eef2 100644 --- a/src/main/java/org/asteriskjava/fastagi/AgiWriter.java +++ b/src/main/java/org/asteriskjava/fastagi/AgiWriter.java @@ -16,20 +16,18 @@ */ 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 335ad2c42..bbb136a41 100644 --- a/src/main/java/org/asteriskjava/fastagi/AsyncAgiServer.java +++ b/src/main/java/org/asteriskjava/fastagi/AsyncAgiServer.java @@ -1,11 +1,9 @@ package org.asteriskjava.fastagi; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.RejectedExecutionException; - 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.ManagerEventListener; import org.asteriskjava.manager.event.AsyncAgiEvent; @@ -14,115 +12,121 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +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; @@ -130,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; } @@ -186,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 38806e56d..d68af3550 100644 --- a/src/main/java/org/asteriskjava/fastagi/ClassNameMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/ClassNameMappingStrategy.java @@ -22,7 +22,7 @@ /** * 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: *

@@ -30,34 +30,31 @@
  * 
* 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.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 e3ec008ad..8c9b6e6c9 100644 --- a/src/main/java/org/asteriskjava/fastagi/CompositeMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/CompositeMappingStrategy.java @@ -35,56 +35,50 @@ * 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)); } /** * Creates a new CompositeMappingStrategy. - * + * * @param strategies the strategies to use. */ - public CompositeMappingStrategy(List strategies) - { + public CompositeMappingStrategy(List strategies) { super(); 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) - { + public void addStrategy(MappingStrategy strategy) { + if (strategies == null) { strategies = new ArrayList<>(); } strategies.add(strategy); @@ -92,29 +86,24 @@ public void addStrategy(MappingStrategy strategy) /** * Sets the strategies to use. - * + * * @param strategies the strategies to use. */ - public void setStrategies(List 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 7b4088a6b..48f0560d6 100644 --- a/src/main/java/org/asteriskjava/fastagi/DefaultAgiServer.java +++ b/src/main/java/org/asteriskjava/fastagi/DefaultAgiServer.java @@ -16,23 +16,20 @@ */ package org.asteriskjava.fastagi; -import java.io.IOException; -import java.net.InetAddress; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.concurrent.RejectedExecutionException; - import org.asteriskjava.fastagi.internal.AgiConnectionHandler; import org.asteriskjava.fastagi.internal.DefaultAgiChannelFactory; import org.asteriskjava.fastagi.internal.FastAgiConnectionHandler; -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; -import org.asteriskjava.util.ReflectionUtil; -import org.asteriskjava.util.ServerSocketFacade; -import org.asteriskjava.util.SocketConnectionFacade; +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. @@ -40,8 +37,7 @@ * @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()); /** @@ -54,7 +50,9 @@ public class DefaultAgiServer extends AbstractAgiServer implements AgiServer */ private static final int DEFAULT_BIND_PORT = 4573; - /** Default 50? Windows server max 200? */ + /** + * Default 50? Windows server max 200? + */ private static final int BACKLOG = 200; private ServerSocketFacade serverSocket; @@ -64,8 +62,8 @@ public class DefaultAgiServer extends AbstractAgiServer implements AgiServer private InetAddress address = null; /** - * Closes the connection if no input has been read for the - * given amount of milliseconds. + * Closes the connection if no input has been read for the given amount of + * milliseconds. * * @see Socket#setSoTimeout(int) */ @@ -74,8 +72,7 @@ public class DefaultAgiServer extends AbstractAgiServer implements AgiServer /** * Creates a new DefaultAgiServer. */ - public DefaultAgiServer() - { + public DefaultAgiServer() { this(null, null); } @@ -85,10 +82,9 @@ public DefaultAgiServer() * AgiChannels * * @param agiChannelFactory The factory to use for creating new AgiChannel - * instances. + * instances. */ - public DefaultAgiServer(AgiChannelFactory agiChannelFactory) - { + public DefaultAgiServer(AgiChannelFactory agiChannelFactory) { this(null, null, agiChannelFactory); } @@ -97,10 +93,9 @@ public DefaultAgiServer(AgiChannelFactory agiChannelFactory) * alternative resource bundle. * * @param configResourceBundleName the name of the conifiguration resource - * bundle (default is "fastagi"). + * bundle (default is "fastagi"). */ - public DefaultAgiServer(String configResourceBundleName) - { + public DefaultAgiServer(String configResourceBundleName) { this(configResourceBundleName, null); } @@ -109,11 +104,10 @@ public DefaultAgiServer(String configResourceBundleName) * {@link MappingStrategy}. * * @param mappingStrategy the MappingStrategy to use to determine the - * AgiScript to run. + * AgiScript to run. * @since 1.0.0 */ - public DefaultAgiServer(MappingStrategy mappingStrategy) - { + public DefaultAgiServer(MappingStrategy mappingStrategy) { this(null, mappingStrategy); } @@ -124,8 +118,7 @@ public DefaultAgiServer(MappingStrategy mappingStrategy) * @param agiScript the AgiScript to run. * @since 1.0.0 */ - public DefaultAgiServer(AgiScript agiScript) - { + public DefaultAgiServer(AgiScript agiScript) { this(null, new StaticMappingStrategy(agiScript)); } @@ -134,13 +127,12 @@ public DefaultAgiServer(AgiScript agiScript) * 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. + * 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()); } @@ -149,47 +141,38 @@ public DefaultAgiServer(String configResourceBundleName, MappingStrategy mapping * 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. + * 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) - { + 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")) - { + if (ReflectionUtil.isClassAvailable("javax.script.ScriptEngineManager")) { MappingStrategy scriptEngineMappingStrategy = (MappingStrategy) ReflectionUtil .newInstance("org.asteriskjava.fastagi.ScriptEngineMappingStrategy"); - if (scriptEngineMappingStrategy != null) - { + 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; } @@ -204,8 +187,7 @@ public DefaultAgiServer(String configResourceBundleName, MappingStrategy mapping * @deprecated use {@link #setPort(int)} instead */ @Deprecated - public void setBindPort(int bindPort) - { + public void setBindPort(int bindPort) { this.port = bindPort; } @@ -216,8 +198,7 @@ public void setBindPort(int bindPort) * @param port the port to bind to. * @since 0.2 */ - public void setPort(int port) - { + public void setPort(int port) { this.port = port; } @@ -227,125 +208,107 @@ 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; } /** * Returns the address this server is configured to bind to. - * + * * @return the address this server is configured to bind to. */ - public InetAddress getAddress() - { + public InetAddress getAddress() { return address; } /** * Sets the address to bind server. - * + * * @param address the address to bind to. */ - public void setAddress(InetAddress address) - { + public void setAddress(InetAddress address) { this.address = address; } - private void loadConfig() - { + 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 } } - public void setSocketReadTimeout(int socketReadTimeout) - { + public void setSocketReadTimeout(int socketReadTimeout) { this.socketReadTimeout = socketReadTimeout; } - protected ServerSocketFacade createServerSocket() throws IOException - { - ServerSocketFacade serverSocketFacade = new ServerSocketFacadeImpl(port, BACKLOG, address); + 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 - { + 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; } // handle exception but continue to run @@ -358,12 +321,9 @@ public void startup() throws IOException, IllegalStateException // execute connection handler final AgiConnectionHandler connectionHandler = new FastAgiConnectionHandler(getMappingStrategy(), socket, this.getAgiChannelFactory()); - 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 like closing the socket if execution was // rejected due to the pool size @@ -377,13 +337,10 @@ 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 @@ -392,38 +349,29 @@ public void run() } @Override - public synchronized 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 - { + protected void finalize() throws Throwable { - if (serverSocket != null) - { - try - { + if (serverSocket != null) { + try { serverSocket.close(); - } - catch (IOException e) // NOPMD + } catch (IOException e) // NOPMD { // swallow } @@ -440,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 ac387c9a1..df31e0c31 100644 --- a/src/main/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategy.java @@ -16,12 +16,9 @@ */ package org.asteriskjava.fastagi; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.MissingResourceException; -import java.util.ResourceBundle; +import org.asteriskjava.lock.Locker.LockCloser; + +import java.util.*; /** * A MappingStrategy that is configured via a resource bundle. @@ -30,24 +27,23 @@ * 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. *

* The resource bundle (properties) file is called * 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; @@ -57,32 +53,29 @@ 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. - * + * * @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. - * + * * @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); } @@ -90,14 +83,13 @@ public ResourceBundleMappingStrategy(boolean shareInstances) * 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; @@ -107,14 +99,12 @@ public ResourceBundleMappingStrategy(String resourceBundleName, boolean shareIns * 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; } @@ -126,41 +116,34 @@ public void setResourceBundleName(String resourceBundleName) * 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; + Enumeration keys; mappings = new HashMap<>(); - if (shareInstances) - { + 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; @@ -170,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); @@ -184,15 +165,12 @@ 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()); } 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 13b74dc2f..780b6562e 100644 --- a/src/main/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategy.java +++ b/src/main/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategy.java @@ -16,14 +16,14 @@ */ package org.asteriskjava.fastagi; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; +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.ScriptException; +import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; @@ -33,14 +33,6 @@ import java.util.List; import java.util.regex.Matcher; -import javax.script.Bindings; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; - -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; - /** * A MappingStrategy that uses {@link javax.script.ScriptEngine} to run * AgiScripts. This MappingStrategy can be used to run JavaScript, Groovy, @@ -48,8 +40,7 @@ * * @since 1.0.0 */ -public class ScriptEngineMappingStrategy implements MappingStrategy -{ +public class ScriptEngineMappingStrategy implements MappingStrategy { protected final Log logger = LogFactory.getLog(getClass()); /** @@ -73,8 +64,7 @@ public class ScriptEngineMappingStrategy implements MappingStrategy * Creates a new ScriptEngineMappingStrategy that searches for scripts in * the current directory. */ - public ScriptEngineMappingStrategy() - { + public ScriptEngineMappingStrategy() { this(DEFAULT_SCRIPT_PATH, DEFAULT_LIB_PATH); } @@ -83,11 +73,10 @@ public ScriptEngineMappingStrategy() * 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); } @@ -99,8 +88,7 @@ public ScriptEngineMappingStrategy(String[] scriptPath, String[] libPath) * * @param scriptPath array of directory names to search for script files. */ - public void setScriptPath(String[] scriptPath) - { + public void setScriptPath(String[] scriptPath) { this.scriptPath = Arrays.copyOf(scriptPath, scriptPath.length); } @@ -110,28 +98,24 @@ public void setScriptPath(String[] scriptPath) * Default is "lib". * * @param libPath array of directory names to search for additional - * libraries (jar files). + * 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) - { + 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; } @@ -145,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; } @@ -164,10 +146,8 @@ protected ScriptEngine getScriptEngine(File file) * @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; @@ -181,54 +161,40 @@ protected synchronized ScriptEngineManager getScriptEngineManager() * @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<>(); - 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"); } }); - if (jarFiles != null) - { + if (jarFiles != null) { - for (File jarFile : jarFiles) - { - try - { + for (File jarFile : jarFiles) { + try { jarFileUrls.add(jarFile.toURI().toURL()); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { // should not happen } } - } - else - { + } else { logger.error("Didn't find any jar files at " + libDir.getAbsolutePath()); } } - if (jarFileUrls.isEmpty()) - { + if (jarFileUrls.isEmpty()) { return parentClassLoader; } @@ -239,53 +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. + * @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. + * 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); } } @@ -297,14 +251,13 @@ protected File searchFile(String scriptName, String[] path) * directory) or not. * * @param file the file to check. - * @param dir the directory to check. + * @param dir the directory to check. * @return true if file is below directory, false - * otherwise. + * otherwise. * @throws IOException if the canonical path of file or dir cannot be - * determined. + * 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()); } @@ -313,71 +266,59 @@ protected final boolean isInside(File file, File dir) throws IOException * * @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. + * 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, StandardCharsets.UTF_8); } - protected class ScriptEngineAgiScript implements NamedAgiScript - { + protected class ScriptEngineAgiScript implements NamedAgiScript { final File file; final ScriptEngine scriptEngine; /** * Creates a new ScriptEngineAgiScript. * - * @param file the file that contains the script to execute. + * @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()); @@ -387,16 +328,11 @@ 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); } } @@ -408,13 +344,12 @@ public void service(AgiRequest request, AgiChannel channel) throws AgiException * 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 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 353e8d542..821a93caf 100644 --- a/src/main/java/org/asteriskjava/fastagi/SpeechRecognitionResult.java +++ b/src/main/java/org/asteriskjava/fastagi/SpeechRecognitionResult.java @@ -1,11 +1,11 @@ package org.asteriskjava.fastagi; +import org.asteriskjava.fastagi.reply.AgiReply; + import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import org.asteriskjava.fastagi.reply.AgiReply; - /** * 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,8 +72,7 @@ public char getDigit() * * @return the position where the prompt stopped playing, 0 if it was played completely. */ - public int getEndpos() - { + public int getEndpos() { return Integer.parseInt(agiReply.getAttribute("endpos")); } @@ -90,8 +82,7 @@ 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.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,19 +111,16 @@ 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.parseInt(numberOfResults); } - public List getAllResults() - { + public List getAllResults() { final int numberOfResults = getNumberOfResults(); 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.parseInt(agiReply.getAttribute("score" + i)), agiReply.getAttribute("text" + 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/.gitignore b/src/main/java/org/asteriskjava/fastagi/command/.gitignore deleted file mode 100644 index c436b7ecf..000000000 --- a/src/main/java/org/asteriskjava/fastagi/command/.gitignore +++ /dev/null @@ -1,49 +0,0 @@ -/AbstractAgiCommand.class -/AgiCommand.class -/AnswerCommand.class -/AsyncAgiBreakCommand.class -/ChannelStatusCommand.class -/ControlStreamFileCommand.class -/DatabaseDelCommand.class -/DatabaseDelTreeCommand.class -/DatabaseGetCommand.class -/DatabasePutCommand.class -/ExecCommand.class -/GetDataCommand.class -/GetFullVariableCommand.class -/GetOptionCommand.class -/GetVariableCommand.class -/GosubCommand.class -/HangupCommand.class -/NoopCommand.class -/ReceiveCharCommand.class -/ReceiveTextCommand.class -/RecordFileCommand.class -/SayAlphaCommand.class -/SayDateTimeCommand.class -/SayDigitsCommand.class -/SayNumberCommand.class -/SayPhoneticCommand.class -/SayTimeCommand.class -/SendImageCommand.class -/SendTextCommand.class -/SetAutoHangupCommand.class -/SetCallerIdCommand.class -/SetContextCommand.class -/SetExtensionCommand.class -/SetMusicOffCommand.class -/SetMusicOnCommand.class -/SetPriorityCommand.class -/SetVariableCommand.class -/SpeechActivateGrammarCommand.class -/SpeechCreateCommand.class -/SpeechDeactivateGrammarCommand.class -/SpeechDestroyCommand.class -/SpeechLoadGrammarCommand.class -/SpeechRecognizeCommand.class -/SpeechSetCommand.class -/SpeechUnloadGrammarCommand.class -/StreamFileCommand.class -/TddModeCommand.class -/VerboseCommand.class -/WaitForDigitCommand.class diff --git a/src/main/java/org/asteriskjava/fastagi/command/AbstractAgiCommand.java b/src/main/java/org/asteriskjava/fastagi/command/AbstractAgiCommand.java index 232ba2a5f..595984897 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/AbstractAgiCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/AbstractAgiCommand.java @@ -1,113 +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 java.io.Serializable; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; + +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; - private static final Log logger = LogFactory.getLog(AbstractAgiCommand.class); + 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() - { - StringBuilder sb; - - sb = new StringBuilder(getClass().getName()).append("["); - sb.append("command='").append(buildCommand()).append("', "); - sb.append("systemHashcode=").append(System.identityHashCode(this)).append("]"); - - return sb.toString(); - } - - public void setAsteriskVersion(AsteriskVersion asteriskVersion) - { - this.asteriskVersion = asteriskVersion; - } - - AsteriskVersion getAsteriskVersion() - { - if (asteriskVersion == null) - { - logger.warn("Asterisk Version isn't known, returning 1.4"); - return AsteriskVersion.ASTERISK_1_4; - } - return asteriskVersion; - } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/AgiCommand.java b/src/main/java/org/asteriskjava/fastagi/command/AgiCommand.java index 556942fe6..73dc10242 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/AgiCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/AgiCommand.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 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(); 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 index a9f79e75e..758f6ffd2 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/BridgeCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/BridgeCommand.java @@ -1,43 +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 org.asteriskjava.AsteriskVersion; +import static org.asteriskjava.AsteriskVersion.ASTERISK_13; -public class BridgeCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +/** + * 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 String options; - private String channel; - /** - * Creates a new AnswerCommand. - */ - public BridgeCommand(String channel, String options) - { + 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() - { + public String buildCommand() { String command = "EXEC " + escapeAndQuote("bridge") + " " + escapeAndQuote(channel); - if (options != null && options.length() > 0) - { - if (getAsteriskVersion().isAtLeast(AsteriskVersion.ASTERISK_13)) - { + if (options != null && options.length() > 0) { + if (getAsteriskVersion().isAtLeast(ASTERISK_13)) { command += "," + escapeAndQuote(options); - } - else - { + } 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 index dc58fa3a6..60f6a70c9 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/ConfbridgeCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/ConfbridgeCommand.java @@ -1,38 +1,51 @@ +/* + * 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; -public class ConfbridgeCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +/** + * 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 String room; - private String profile; - - /** - * Creates a new AnswerCommand. - */ - public ConfbridgeCommand(String room, String profile) - { + + 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() - { + public String buildCommand() { String separator = "|"; - if (getAsteriskVersion().isAtLeast(AsteriskVersion.ASTERISK_10)) - { + if (getAsteriskVersion().isAtLeast(AsteriskVersion.ASTERISK_10)) { separator = ","; } String command = "EXEC " + escapeAndQuote("confbridge") + " " + escapeAndQuote(room); - if (profile != null && profile.length() > 0) - { + if (profile != null && profile.length() > 0) { command += separator + escapeAndQuote(profile); } diff --git a/src/main/java/org/asteriskjava/fastagi/command/ControlStreamFileCommand.java b/src/main/java/org/asteriskjava/fastagi/command/ControlStreamFileCommand.java index c7e30e4d2..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() - { - StringBuilder sb; - - sb = new StringBuilder("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 383a8241c..17e438797 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelTreeCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/DatabaseDelTreeCommand.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; /** - * 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; /** @@ -44,11 +40,10 @@ 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; } @@ -56,12 +51,11 @@ public DatabaseDelTreeCommand(String family) /** * Creates a new DatabaseDelCommand to delete a keytree within a given * family. - * - * @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 DatabaseDelTreeCommand(String family, String keyTree) - { + public DatabaseDelTreeCommand(String family, String keyTree) { super(); this.family = family; this.keyTree = keyTree; @@ -69,50 +63,43 @@ 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. + * + * @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); } 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 index ba1acead0..e306f8e46 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/DialCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/DialCommand.java @@ -1,25 +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.fastagi.command; -import org.asteriskjava.AsteriskVersion; import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; -public class DialCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +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 String options; - private String target; - private int timeout; - private final Log logger = LogFactory.getLog(getClass()); - - /** - * Creates a new AnswerCommand. - */ - public DialCommand(String target, int timeout, String options) - { + + 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; @@ -27,25 +45,20 @@ public DialCommand(String target, int timeout, String options) } @Override - public String buildCommand() - { + public String buildCommand() { String separator = "|"; - if (getAsteriskVersion().isAtLeast(AsteriskVersion.ASTERISK_10)) - { + if (getAsteriskVersion().isAtLeast(ASTERISK_10)) { separator = ","; } - String command = "EXEC " + escapeAndQuote("dial") + " " + escapeAndQuote(target) + separator - + escapeAndQuote("" + timeout); - if (options != null && options.length() > 0) - { + 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 d93a0b5e7..64bd2c31d 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/GetDataCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/GetDataCommand.java @@ -17,26 +17,22 @@ package org.asteriskjava.fastagi.command; /** - * Stream the given file, and recieve DTMF data. The user may interrupt the - * streaming by starting to enter digits. + * AGI Command: GET DATA *

- * Returns the digits recieved from the channel at the other end. + * 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 #. - * + * 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. @@ -46,8 +42,7 @@ public class GetDataCommand extends AbstractAgiCommand /** * The timeout in milliseconds to wait for data. *

- * 0 means standard timeout value, -1 means "ludicrous time" (essentially - * never times out). + * 0 means standard timeout value, -1 means "ludicrous time" (essentially never times out). */ private long timeout; @@ -59,13 +54,11 @@ public class GetDataCommand extends AbstractAgiCommand 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; @@ -75,15 +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 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). + *

+ * 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; @@ -92,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 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]. + *

+ * 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; @@ -118,11 +104,10 @@ public GetDataCommand(String file, long timeout, int maxDigits) throws IllegalAr /** * Returns the name of the file to stream. - * + * * @return the name of the file to stream. */ - public String getFile() - { + public String getFile() { return file; } @@ -130,76 +115,70 @@ public String getFile() * 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). + *

+ * 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]. + *

+ * 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); } 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]"); + } + } } diff --git a/src/main/java/org/asteriskjava/fastagi/command/GetFullVariableCommand.java b/src/main/java/org/asteriskjava/fastagi/command/GetFullVariableCommand.java index ff94d205c..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() - { - StringBuilder sb; + public String buildCommand() { + StringBuilder sb; 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 dd6bc5532..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 3c6826795..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,7 +45,7 @@ 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; @@ -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 index 04024a28e..328bde93c 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/MeetmeCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/MeetmeCommand.java @@ -1,34 +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; -public class MeetmeCommand extends AbstractAgiCommand -{ - /** - * Serial version identifier. - */ +/** + * 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 String room; - private String options; - /** - * Creates a new AnswerCommand. - */ - public MeetmeCommand(String room, String options) - { + 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() - { + public String buildCommand() { String command = "EXEC " + escapeAndQuote("meetme") + " " + escapeAndQuote(room); - if (options != null && options.length() > 0) - { + 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 index 86f3420fb..8452a8466 100644 --- a/src/main/java/org/asteriskjava/fastagi/command/QueueCommand.java +++ b/src/main/java/org/asteriskjava/fastagi/command/QueueCommand.java @@ -1,35 +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; -public class QueueCommand extends AbstractAgiCommand -{ - - /** - * Serial version identifier. - */ +/** + * 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 String queue; + private final String queue; - /** - * Creates a new AnswerCommand. - */ - public QueueCommand(String queue) - { + public QueueCommand(String queue) { super(); this.queue = queue; } @Override - public String buildCommand() - { - String command = "EXEC " + escapeAndQuote("queue") + " " + escapeAndQuote(queue); - // if (options != null && options.length() > 0) - // { - // command += " " + escapeAndQuote(options); - // } - - return command; - + 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 b90a52506..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() - { - StringBuilder sb; + public String buildCommand() { + StringBuilder sb; 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/.gitignore b/src/main/java/org/asteriskjava/fastagi/internal/.gitignore deleted file mode 100644 index df400e5e4..000000000 --- a/src/main/java/org/asteriskjava/fastagi/internal/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -/AgiChannelFactory.class -/AgiChannelImpl.class -/AgiConnectionHandler.class -/AgiReader.class -/AgiReplyImpl.class -/AgiRequestImpl.class -/AgiWriter.class -/AsyncAgiConnectionHandler.class -/AsyncAgiReader.class -/AsyncAgiWriter.class -/DefaultAgiChannelFactory.class -/FastAgiConnectionHandler.class -/FastAgiReader.class -/FastAgiWriter.class diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelImpl.java b/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelImpl.java index 93d04794d..cb51f56d0 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelImpl.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AgiChannelImpl.java @@ -17,62 +17,8 @@ package org.asteriskjava.fastagi.internal; import org.asteriskjava.AsteriskVersion; -import org.asteriskjava.fastagi.AgiChannel; -import org.asteriskjava.fastagi.AgiException; -import org.asteriskjava.fastagi.AgiHangupException; -import org.asteriskjava.fastagi.AgiReader; -import org.asteriskjava.fastagi.AgiRequest; -import org.asteriskjava.fastagi.AgiSpeechException; -import org.asteriskjava.fastagi.AgiWriter; -import org.asteriskjava.fastagi.InvalidCommandSyntaxException; -import org.asteriskjava.fastagi.InvalidOrUnknownCommandException; -import org.asteriskjava.fastagi.SpeechRecognitionResult; -import org.asteriskjava.fastagi.command.AgiCommand; -import org.asteriskjava.fastagi.command.AnswerCommand; -import org.asteriskjava.fastagi.command.BridgeCommand; -import org.asteriskjava.fastagi.command.ChannelStatusCommand; -import org.asteriskjava.fastagi.command.ConfbridgeCommand; -import org.asteriskjava.fastagi.command.ControlStreamFileCommand; -import org.asteriskjava.fastagi.command.DatabaseDelCommand; -import org.asteriskjava.fastagi.command.DatabaseDelTreeCommand; -import org.asteriskjava.fastagi.command.DatabaseGetCommand; -import org.asteriskjava.fastagi.command.DatabasePutCommand; -import org.asteriskjava.fastagi.command.DialCommand; -import org.asteriskjava.fastagi.command.ExecCommand; -import org.asteriskjava.fastagi.command.GetDataCommand; -import org.asteriskjava.fastagi.command.GetFullVariableCommand; -import org.asteriskjava.fastagi.command.GetOptionCommand; -import org.asteriskjava.fastagi.command.GetVariableCommand; -import org.asteriskjava.fastagi.command.GosubCommand; -import org.asteriskjava.fastagi.command.HangupCommand; -import org.asteriskjava.fastagi.command.MeetmeCommand; -import org.asteriskjava.fastagi.command.QueueCommand; -import org.asteriskjava.fastagi.command.RecordFileCommand; -import org.asteriskjava.fastagi.command.SayAlphaCommand; -import org.asteriskjava.fastagi.command.SayDateTimeCommand; -import org.asteriskjava.fastagi.command.SayDigitsCommand; -import org.asteriskjava.fastagi.command.SayNumberCommand; -import org.asteriskjava.fastagi.command.SayPhoneticCommand; -import org.asteriskjava.fastagi.command.SayTimeCommand; -import org.asteriskjava.fastagi.command.SetAutoHangupCommand; -import org.asteriskjava.fastagi.command.SetCallerIdCommand; -import org.asteriskjava.fastagi.command.SetContextCommand; -import org.asteriskjava.fastagi.command.SetExtensionCommand; -import org.asteriskjava.fastagi.command.SetMusicOffCommand; -import org.asteriskjava.fastagi.command.SetMusicOnCommand; -import org.asteriskjava.fastagi.command.SetPriorityCommand; -import org.asteriskjava.fastagi.command.SetVariableCommand; -import org.asteriskjava.fastagi.command.SpeechActivateGrammarCommand; -import org.asteriskjava.fastagi.command.SpeechCreateCommand; -import org.asteriskjava.fastagi.command.SpeechDeactivateGrammarCommand; -import org.asteriskjava.fastagi.command.SpeechDestroyCommand; -import org.asteriskjava.fastagi.command.SpeechLoadGrammarCommand; -import org.asteriskjava.fastagi.command.SpeechRecognizeCommand; -import org.asteriskjava.fastagi.command.SpeechSetCommand; -import org.asteriskjava.fastagi.command.SpeechUnloadGrammarCommand; -import org.asteriskjava.fastagi.command.StreamFileCommand; -import org.asteriskjava.fastagi.command.VerboseCommand; -import org.asteriskjava.fastagi.command.WaitForDigitCommand; +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; @@ -83,8 +29,7 @@ * @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; @@ -94,536 +39,437 @@ public class AgiChannelImpl implements AgiChannel 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 AsteriskVersion getAsteriskVersion() - { - if (request == null) - { + public AsteriskVersion getAsteriskVersion() { + if (request == null) { logger.warn("Request is null, I assume you're testing..."); return AsteriskVersion.DEFAULT_VERSION; } - if (asteriskVersion == null) - { + if (asteriskVersion == null) { asteriskVersion = request.getAsteriskVersion(); } return asteriskVersion; } - public void answer() throws AgiException - { + 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)); } - private void checkFile(String file) - { - if (file == null || file.length() == 0) - { + 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 - { + 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 - { + 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 - { + 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"); } 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() - { + public AgiRequest getInternalAgiRequest() { return request; } @Override - public void confbridge(String room, String profile) throws AgiException - { + public void confbridge(String room, String profile) throws AgiException { sendCommand(new ConfbridgeCommand(room, profile)); } @Override - public void meetme(String room, String options) throws AgiException - { + 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 - { + 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 - { + public void bridge(String channelName, String options) throws AgiException { sendCommand(new BridgeCommand(channelName, options)); } @Override - public void queue(String queue) throws AgiException - { + 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 5d5a0e6aa..cf66f8c9c 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiConnectionHandler.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AgiConnectionHandler.java @@ -16,22 +16,14 @@ */ package org.asteriskjava.fastagi.internal; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.asteriskjava.fastagi.AgiChannel; -import org.asteriskjava.fastagi.AgiChannelFactory; -import org.asteriskjava.fastagi.AgiException; -import org.asteriskjava.fastagi.AgiReader; -import org.asteriskjava.fastagi.AgiRequest; -import org.asteriskjava.fastagi.AgiScript; -import org.asteriskjava.fastagi.AgiWriter; -import org.asteriskjava.fastagi.MappingStrategy; -import org.asteriskjava.fastagi.NamedAgiScript; +import org.asteriskjava.fastagi.*; import org.asteriskjava.fastagi.command.VerboseCommand; 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.
@@ -41,8 +33,7 @@ * @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"; @@ -64,19 +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 mappingStrategy the strategy to use to determine which script to + * run. * @param agiChannelFactory the AgiFactory, that is used to create new - * AgiChannel objects. + * 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"); } @@ -84,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; } @@ -109,12 +94,10 @@ protected AgiScript getScript() public abstract void release(); @Override - public void run() - { + public void run() { AgiChannel channel = null; - try - { + try { AgiReader reader; AgiWriter writer; AgiRequest request; @@ -127,13 +110,11 @@ 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 '" @@ -142,98 +123,79 @@ public void run() 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.debug("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.debug("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 } @@ -243,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 68fd13d06..2bded2bd1 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiReplyImpl.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AgiReplyImpl.java @@ -16,24 +16,19 @@ */ package org.asteriskjava.fastagi.internal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import org.asteriskjava.fastagi.reply.AgiReply; + +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.asteriskjava.fastagi.reply.AgiReply; - /** * Default implementation of the AgiReply interface. * * @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* +\\((.*)\\)"); @@ -81,140 +76,112 @@ public class AgiReplyImpl implements AgiReply */ private String usage; - AgiReplyImpl() - { + AgiReplyImpl() { super(); this.status = null; } - AgiReplyImpl(List lines) - { + AgiReplyImpl(List lines) { this(); - if (lines != null) - { + if (lines != null) { this.lines = new ArrayList<>(lines); - if (!lines.isEmpty()) - { + 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) - { + 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<>(); 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<>(); @@ -222,41 +189,27 @@ Map parseAttributes(String s) 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); } } @@ -264,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; @@ -273,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); } } @@ -321,22 +265,18 @@ public String getSynopsis() * syntax (getStatus() == SC_INVALID_COMMAND_SYNTAX). * * @return the usage of the command sent, null if there were no - * syntax errors. + * 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; } @@ -349,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 ca74a14af..a24b8453d 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AgiRequestImpl.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AgiRequestImpl.java @@ -16,33 +16,26 @@ */ package org.asteriskjava.fastagi.internal; -import java.io.UnsupportedEncodingException; -import java.net.InetAddress; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.fastagi.AgiRequest; import org.asteriskjava.util.AstUtil; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +import java.io.UnsupportedEncodingException; +import java.net.InetAddress; +import java.net.URLDecoder; +import java.util.*; +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("^(.*)=(.*)$"); @@ -71,10 +64,9 @@ 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)); } @@ -82,19 +74,16 @@ public class AgiRequestImpl implements AgiRequest * 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. + * 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); } @@ -106,25 +95,22 @@ private AgiRequestImpl(final Map request) * 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. + * 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<>(); - for (String line : lines) - { + for (String line : lines) { int colonPosition; String key; String value; @@ -132,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); } } @@ -161,88 +143,76 @@ 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() - { + 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() - { + 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; } @@ -252,16 +222,13 @@ public String getCallerIdNumber() 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; } @@ -273,22 +240,19 @@ public String getCallerIdName() /** * 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]; } return parsedCallerId[1]; @@ -296,13 +260,11 @@ private synchronized String getCallerId10() /** * 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; } @@ -310,59 +272,48 @@ 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; } - 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; } - 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; } return Boolean.FALSE; @@ -370,97 +321,72 @@ public Boolean getEnhanced() 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]; } @@ -468,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; @@ -479,12 +403,11 @@ 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; @@ -492,14 +415,12 @@ private synchronized Map parseParameters(String s) 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; @@ -508,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) - { + 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()]; @@ -559,82 +467,67 @@ 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<>(); 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.parseInt(entry.getKey().substring(4)); - if (index > maxIndex) - { + 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() - { + public String toString() { StringBuilder sb; sb = new StringBuilder("AgiRequest["); diff --git a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiConnectionHandler.java b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiConnectionHandler.java index 930c35c40..4fce51751 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiConnectionHandler.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiConnectionHandler.java @@ -16,19 +16,15 @@ */ package org.asteriskjava.fastagi.internal; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -import org.asteriskjava.fastagi.AgiChannelFactory; -import org.asteriskjava.fastagi.AgiException; -import org.asteriskjava.fastagi.AgiReader; -import org.asteriskjava.fastagi.AgiWriter; -import org.asteriskjava.fastagi.MappingStrategy; +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; + /** * An AgiConnectionHandler for AsyncAGI. *
@@ -38,8 +34,7 @@ * @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; @@ -54,11 +49,9 @@ 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(); @@ -69,47 +62,38 @@ public AsyncAgiConnectionHandler(MappingStrategy mappingStrategy, AsyncAgiEvent } @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 dc5880ffc..631fc956d 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiReader.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiReader.java @@ -1,8 +1,5 @@ package org.asteriskjava.fastagi.internal; -import java.util.List; -import java.util.concurrent.BlockingQueue; - import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiReader; import org.asteriskjava.fastagi.AgiRequest; @@ -10,13 +7,14 @@ import org.asteriskjava.manager.ManagerConnection; import org.asteriskjava.manager.event.AsyncAgiEvent; -public class AsyncAgiReader implements AgiReader -{ +import java.util.List; +import java.util.concurrent.BlockingQueue; + +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; @@ -26,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 4440bd60b..bfe44849e 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiWriter.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/AsyncAgiWriter.java @@ -1,7 +1,5 @@ package org.asteriskjava.fastagi.internal; -import java.io.IOException; - import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiWriter; import org.asteriskjava.fastagi.command.AgiCommand; @@ -11,56 +9,48 @@ import org.asteriskjava.manager.response.ManagerError; import org.asteriskjava.manager.response.ManagerResponse; +import java.io.IOException; + /** * Implementation of AgiWriter that uses a {@link org.asteriskjava.manager.ManagerConnection} to send * {@link org.asteriskjava.fastagi.command.AgiCommand AgiCommands} as part of an AsyncAgi conversation. * * @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 index 59bda0e1e..a5b7e9c6b 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/DefaultAgiChannelFactory.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/DefaultAgiChannelFactory.java @@ -1,21 +1,15 @@ package org.asteriskjava.fastagi.internal; -import org.asteriskjava.fastagi.AgiChannel; -import org.asteriskjava.fastagi.AgiChannelFactory; -import org.asteriskjava.fastagi.AgiReader; -import org.asteriskjava.fastagi.AgiRequest; -import org.asteriskjava.fastagi.AgiWriter; +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 -{ +public class DefaultAgiChannelFactory implements AgiChannelFactory { @Override - public AgiChannel createAgiChannel(AgiRequest request, AgiWriter agiWriter, AgiReader agiReader) - { + 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 edd32d8aa..99e4005c4 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/FastAgiConnectionHandler.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/FastAgiConnectionHandler.java @@ -16,14 +16,14 @@ */ 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. *
@@ -33,8 +33,7 @@ * @author srt * @version $Id$ */ -public class FastAgiConnectionHandler extends AgiConnectionHandler -{ +public class FastAgiConnectionHandler extends AgiConnectionHandler { /** * The socket connection. */ @@ -47,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 e337321ad..92323dc50 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/FastAgiReader.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/FastAgiReader.java @@ -16,55 +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.AgiReader; -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<>(); - 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); } @@ -77,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<>(); - 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) - { + if (line.startsWith("HANGUP")) { + if (line.length() > 6) { line = line.substring(6); - } - else - { + } else { return readReply(); } } @@ -117,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); } } @@ -139,8 +112,7 @@ public AgiReply readReply() throws AgiException reply = new AgiReplyImpl(lines); // Special handling for gosub, see AJ-257 - if (reply.getStatus() == AgiReply.SC_TRYING) - { + 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 f7656bc79..8c144c1e9 100644 --- a/src/main/java/org/asteriskjava/fastagi/internal/FastAgiWriter.java +++ b/src/main/java/org/asteriskjava/fastagi/internal/FastAgiWriter.java @@ -16,39 +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/.gitignore b/src/main/java/org/asteriskjava/fastagi/reply/.gitignore deleted file mode 100644 index 56de7ec63..000000000 --- a/src/main/java/org/asteriskjava/fastagi/reply/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/AgiReply.class diff --git a/src/main/java/org/asteriskjava/fastagi/reply/AgiReply.java b/src/main/java/org/asteriskjava/fastagi/reply/AgiReply.java index bf7c70621..4b3e91519 100644 --- a/src/main/java/org/asteriskjava/fastagi/reply/AgiReply.java +++ b/src/main/java/org/asteriskjava/fastagi/reply/AgiReply.java @@ -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/.gitignore b/src/main/java/org/asteriskjava/live/.gitignore deleted file mode 100644 index 305344291..000000000 --- a/src/main/java/org/asteriskjava/live/.gitignore +++ /dev/null @@ -1,36 +0,0 @@ -/AbstractAsteriskServerListener.class -/AgentState.class -/AmaFlags.class -/AsteriskAgent.class -/AsteriskChannel.class -/AsteriskQueue.class -/AsteriskQueueEntry.class -/AsteriskQueueListener.class -/AsteriskQueueMember.class -/AsteriskServer.class -/AsteriskServerListener.class -/CallDetailRecord.class -/CallerId.class -/ChannelState.class -/ChannelStateHistoryEntry.class -/DefaultAsteriskServer.class -/DialedChannelHistoryEntry.class -/Disposition.class -/Extension.class -/ExtensionHistoryEntry.class -/HangupCause.class -/InvalidPenaltyException.class -/LinkedChannelHistoryEntry.class -/LiveException.class -/LiveObject.class -/ManagerCommunicationException.class -/MeetMeRoom.class -/MeetMeUser.class -/MeetMeUserState.class -/NoSuchChannelException.class -/NoSuchInterfaceException.class -/OriginateCallback.class -/QueueEntryState.class -/QueueMemberState.class -/SecureAsteriskServer.class -/Voicemailbox.class 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 3246a6fb4..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 * @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 96e61019f..7fa231b43 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskAgent.java +++ b/src/main/java/org/asteriskjava/live/AsteriskAgent.java @@ -24,12 +24,11 @@ *
  • state
  • * * - * @since 0.3.1 * @author Patrick Breucking * @version $Id$ + * @since 0.3.1 */ -public interface AsteriskAgent extends LiveObject -{ +public interface AsteriskAgent extends LiveObject { String PROPERTY_STATE = "state"; /** diff --git a/src/main/java/org/asteriskjava/live/AsteriskChannel.java b/src/main/java/org/asteriskjava/live/AsteriskChannel.java index 124017e8a..06da80821 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskChannel.java +++ b/src/main/java/org/asteriskjava/live/AsteriskChannel.java @@ -16,12 +16,12 @@ */ package org.asteriskjava.live; +import org.asteriskjava.util.MixMonitorDirection; + import java.util.Date; import java.util.List; import java.util.Map; -import org.asteriskjava.util.MixMonitorDirection; - /** * Represents an Asterisk channel. *

    @@ -44,11 +44,10 @@ *

  • 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"; @@ -70,32 +69,35 @@ public interface AsteriskChannel extends LiveObject 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"; + /** + * 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(); @@ -105,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 */ @@ -143,7 +145,7 @@ public interface AsteriskChannel extends LiveObject /** * Returns the first visited dialplan entry. - * + * * @return the first visited dialplan entry. * @since 0.2 */ @@ -151,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 */ @@ -161,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(); @@ -169,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(); @@ -209,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(); @@ -225,41 +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. + * if none was dialing. */ - List getDialedChannels(); + 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(); @@ -267,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(); @@ -280,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. @@ -331,14 +333,14 @@ public interface AsteriskChannel extends LiveObject 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; @@ -347,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; @@ -363,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; @@ -381,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; @@ -399,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, @@ -418,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; @@ -447,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; @@ -464,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 @@ -484,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 @@ -518,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() @@ -559,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 @@ -579,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) @@ -598,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 */ @@ -616,34 +618,34 @@ void changeMonitoring(String filename) throws ManagerCommunicationException, NoS * ignored. *

    * This method is available since Asterisk 1.4. - * + * * @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. + * 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. + * 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)} ()} @@ -652,14 +654,14 @@ void changeMonitoring(String filename) throws ManagerCommunicationException, NoS * 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. + * 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 23a4f4a41..9393c6119 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskQueue.java +++ b/src/main/java/org/asteriskjava/live/AsteriskQueue.java @@ -26,8 +26,7 @@ * @author itaqua * @version $Id$ */ -public interface AsteriskQueue -{ +public interface AsteriskQueue { String STRATEGY_RINGALL = "ringall"; String STRATEGY_ROUNDROBIN = "roundrobin"; String STRATAGY_LEAST_RECENT = "leastrecent"; @@ -91,7 +90,7 @@ public interface AsteriskQueue * 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(); @@ -138,63 +137,70 @@ public interface AsteriskQueue /** * Returns the number of abandoned calls. - * @author itaqua + * * @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). - * @author itaqua + * * @return the ratio of calls answered within the specified service level per total completed - * calls (in percent). + * calls (in percent). + * @author itaqua */ - Double getServiceLevelPerf(); + Double getServiceLevelPerf(); - /** + /** * Returns the number of completed calls. - * @author itaqua + * * @return the number of completed calls. + * @author itaqua */ - Integer getCompleted(); + 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(); + Integer getTalkTime(); - /** + /** * Returns the current average holdtime for this queue (in seconds). - * @author itaqua + * * @return the current average holdtime for this queue (in seconds). + * @author itaqua */ - Integer getHoldTime(); + 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() - * @return the number of calls currently waiting in the queue. */ - Integer getCalls(); + Integer getCalls(); - /** + /** * Returns the number of calls currently waiting in the queue. * More verbose Method than getCalls() - * @author itaqua + * * @return the number of calls currently waiting in the queue. + * @author itaqua */ - Integer getWaiting(); + Integer getWaiting(); - /** + /** * timestamp (miliseconds) of last update of this object + * + * @return * @todo maybe change this to an immutable object * @author itaqua - * @return */ 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 e8951b6ea..c88dbe7df 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskQueueMember.java +++ b/src/main/java/org/asteriskjava/live/AsteriskQueueMember.java @@ -31,8 +31,7 @@ * @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"; @@ -66,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.. @@ -102,7 +102,7 @@ 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 */ String getMembership(); @@ -112,7 +112,7 @@ public interface AsteriskQueueMember extends LiveObject * 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 */ boolean isStatic(); @@ -122,7 +122,7 @@ public interface AsteriskQueueMember extends LiveObject * 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 */ boolean isDynamic(); @@ -149,15 +149,17 @@ public interface AsteriskQueueMember extends LiveObject /** * get the timestamp when the last call was terminated - * @author itaqua + * * @return + * @author itaqua */ - Long getLastCall(); + Long getLastCall(); /** * total calls taken - * @author itaqua + * * @return + * @author itaqua */ - Integer getCallsTaken(); + Integer getCallsTaken(); } diff --git a/src/main/java/org/asteriskjava/live/AsteriskServer.java b/src/main/java/org/asteriskjava/live/AsteriskServer.java index da543db02..6e2e2c13e 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskServer.java +++ b/src/main/java/org/asteriskjava/live/AsteriskServer.java @@ -16,16 +16,16 @@ */ package org.asteriskjava.live; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Map; - import org.asteriskjava.config.ConfigFile; import org.asteriskjava.manager.ManagerConnection; import org.asteriskjava.manager.ManagerEventListener; import org.asteriskjava.manager.action.OriginateAction; +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 @@ -35,12 +35,11 @@ * 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 -{ +public interface AsteriskServer { /** * Returns the underlying ManagerConnection. *

    @@ -50,57 +49,57 @@ public interface AsteriskServer * 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 + * 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 */ 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 + * originate + * @param cb callback to inform about the result * @throws ManagerCommunicationException if the originate action cannot be - * sent to Asterisk + * sent to Asterisk */ 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; @@ -108,45 +107,45 @@ AsteriskChannel originateToExtension(String channel, String context, String exte /** * 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; + 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; @@ -154,170 +153,170 @@ AsteriskChannel originateToApplication(String channel, String application, Strin /** * 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; + 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; + 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; + 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; + 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; + 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; /** * 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. + * no such channel. * @throws ManagerCommunicationException if there is a problem communication - * with Asterisk + * with Asterisk */ 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; /** * 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; /** * 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; /** * 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; @@ -325,56 +324,54 @@ void originateToApplicationAsync(String channel, String application, String data * 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; /** - * <<<<<<< HEAD Returns the CVS revision of a given source file of this + * Returns the CVS revision of a given source file of this * Asterisk server.
    - * ======= Returns the CVS revision of a given source file of this Asterisk - * server.
    - * >>>>>>> refs/heads/release-1.1 For example getVersion("app_meetme.c") may - * return {1, 102} for CVS revision "1.102".
    + * 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; /** * 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; @@ -382,21 +379,21 @@ void originateToApplicationAsync(String channel, String application, String data /** * 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 @@ -409,9 +406,9 @@ void originateToApplicationAsync(String channel, String application, String data * Available since Asterisk 1.6 * * @param module name of the module to load (with out without the ".so" - * extension). + * extension). * @return true if the module is currently loaded, - * false otherwise. + * false otherwise. * @throws ManagerCommunicationException if the module can't be checked. */ boolean isModuleLoaded(String module) throws ManagerCommunicationException; @@ -422,7 +419,7 @@ void originateToApplicationAsync(String channel, String application, String data * Available since Asterisk 1.6 * * @param module name of the module to load (including ".so" extension) or - * subsystem name. + * subsystem name. * @throws ManagerCommunicationException if the module cannot be loaded. * @since 1.0.0 */ @@ -434,7 +431,7 @@ void originateToApplicationAsync(String channel, String application, String data * Available since Asterisk 1.6 * * @param module name of the module to unload (including ".so" extension) or - * subsystem name. + * subsystem name. * @throws ManagerCommunicationException if the module cannot be unloaded. * @since 1.0.0 */ @@ -446,7 +443,7 @@ void originateToApplicationAsync(String channel, String application, String data * Available since Asterisk 1.6 * * @param module name of the module to reload (including ".so" extension) or - * subsystem name. + * subsystem name. * @throws ManagerCommunicationException if the module cannot be reloaded. * @since 1.0.0 */ @@ -474,16 +471,16 @@ void originateToApplicationAsync(String channel, String application, String data /** * 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); @@ -517,7 +514,7 @@ void originateToApplicationAsync(String channel, String application, String data /** * remove the chain listener. - * + * * @param chainListener */ void removeChainListener(ManagerEventListener chainListener); @@ -529,42 +526,42 @@ void originateToApplicationAsync(String channel, String application, String data /** * Opens the connection to this server. - * + * * @throws ManagerCommunicationException if login fails */ void initialize() throws ManagerCommunicationException; /** * get Asterisk Queue by name - * - * @author itaqua + * * @param queueName Name of the queue to retrieve * @return + * @author itaqua */ AsteriskQueue getQueueByName(String queueName); /** * List of Queues Objects updated after certain date - * - * @author itaqua + * * @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 - * - * @author itaqua + * * @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 922369881..4cbf1ee92 100644 --- a/src/main/java/org/asteriskjava/live/AsteriskServerListener.java +++ b/src/main/java/org/asteriskjava/live/AsteriskServerListener.java @@ -8,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(AsteriskAgent agent); - + /** * 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 592b5e1ca..216eccc67 100644 --- a/src/main/java/org/asteriskjava/live/CallerId.java +++ b/src/main/java/org/asteriskjava/live/CallerId.java @@ -16,10 +16,10 @@ */ package org.asteriskjava.live; -import java.io.Serializable; - import org.asteriskjava.util.AstUtil; +import java.io.Serializable; + /** * Represents a Caller*ID containing name and number. *
    @@ -29,8 +29,7 @@ * @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 88820d140..0d919c280 100644 --- a/src/main/java/org/asteriskjava/live/DefaultAsteriskServer.java +++ b/src/main/java/org/asteriskjava/live/DefaultAsteriskServer.java @@ -16,11 +16,6 @@ */ package org.asteriskjava.live; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Map; - import org.asteriskjava.config.ConfigFile; import org.asteriskjava.live.internal.AsteriskServerImpl; import org.asteriskjava.manager.DefaultManagerConnection; @@ -28,6 +23,11 @@ import org.asteriskjava.manager.ManagerEventListener; import org.asteriskjava.manager.action.OriginateAction; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; + /** * Default implementation of the AsteriskServer interface. * @@ -35,8 +35,7 @@ * @version $Id$ * @see org.asteriskjava.live.AsteriskServer */ -public class DefaultAsteriskServer implements AsteriskServer -{ +public class DefaultAsteriskServer implements AsteriskServer { private final AsteriskServerImpl impl; /** @@ -45,8 +44,7 @@ public class DefaultAsteriskServer implements AsteriskServer * {@link #setManagerConnection(ManagerConnection)} before you can use this * AsteriskServer. */ - public DefaultAsteriskServer() - { + public DefaultAsteriskServer() { this.impl = new AsteriskServerImpl(); } @@ -58,8 +56,7 @@ 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); this.impl = new AsteriskServerImpl(connection); @@ -70,20 +67,18 @@ public DefaultAsteriskServer(String hostname, String username, String password) * 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 * @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); 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,10 +88,9 @@ protected DefaultManagerConnection createManagerConnection(String hostname, int * Creates a new instance that uses the given {@link ManagerConnection}. * * @param eventConnection the ManagerConnection to use for receiving events - * from Asterisk. + * from Asterisk. */ - public DefaultAsteriskServer(ManagerConnection eventConnection) - { + public DefaultAsteriskServer(ManagerConnection eventConnection) { this.impl = new AsteriskServerImpl(eventConnection); } @@ -108,237 +102,194 @@ public DefaultAsteriskServer(ManagerConnection eventConnection) * Default is false. * * @param skipQueues true to skip queue initialization, - * false to not skip. + * false to not skip. * @since 0.2 */ - public void setSkipQueues(boolean skipQueues) - { + public void setSkipQueues(boolean skipQueues) { this.impl.setSkipQueues(skipQueues); } - public void setManagerConnection(ManagerConnection eventConnection) - { + public void setManagerConnection(ManagerConnection eventConnection) { this.impl.setManagerConnection(eventConnection); } - public void initialize() throws ManagerCommunicationException - { + public void initialize() throws ManagerCommunicationException { this.impl.initialize(); } /* Implementation of the AsteriskServer interface */ - public ManagerConnection getManagerConnection() - { + public ManagerConnection getManagerConnection() { return this.impl.getManagerConnection(); } public AsteriskChannel originate(OriginateAction originateAction) - throws ManagerCommunicationException, NoSuchChannelException - { + throws ManagerCommunicationException, NoSuchChannelException { return this.impl.originate(originateAction); } public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) - throws ManagerCommunicationException, NoSuchChannelException - { + throws ManagerCommunicationException, NoSuchChannelException { return this.impl.originateToExtension(channel, context, exten, priority, timeout); } public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout, - CallerId callerId, Map variables) throws ManagerCommunicationException, NoSuchChannelException - { + 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 - { + 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 - { + 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 - { + public void originateAsync(OriginateAction originateAction, OriginateCallback cb) throws ManagerCommunicationException { this.impl.originateAsync(originateAction, cb); } public void originateToApplicationAsync(String channel, String application, String data, long timeout, CallerId callerId, - Map variables, OriginateCallback cb) throws ManagerCommunicationException - { + Map variables, OriginateCallback cb) throws ManagerCommunicationException { this.impl.originateToApplicationAsync(channel, application, data, timeout, callerId, variables, cb); } public void originateToApplicationAsync(String channel, String application, String data, long timeout, - OriginateCallback cb) throws ManagerCommunicationException - { + OriginateCallback cb) throws ManagerCommunicationException { this.impl.originateToApplicationAsync(channel, application, data, timeout, cb); } public void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, - CallerId callerId, Map variables, OriginateCallback cb) throws ManagerCommunicationException - { + CallerId callerId, Map variables, OriginateCallback cb) throws ManagerCommunicationException { this.impl.originateToExtensionAsync(channel, context, exten, priority, timeout, callerId, variables, cb); } public void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, - OriginateCallback cb) throws ManagerCommunicationException - { + OriginateCallback cb) throws ManagerCommunicationException { this.impl.originateToExtensionAsync(channel, context, exten, priority, timeout, cb); } - public Collection getChannels() throws ManagerCommunicationException - { + public Collection getChannels() throws ManagerCommunicationException { return this.impl.getChannels(); } - public AsteriskChannel getChannelByName(String name) throws ManagerCommunicationException - { + public AsteriskChannel getChannelByName(String name) throws ManagerCommunicationException { return this.impl.getChannelByName(name); } - public AsteriskChannel getChannelById(String id) throws ManagerCommunicationException - { + public AsteriskChannel getChannelById(String id) throws ManagerCommunicationException { return this.impl.getChannelById(id); } - public Collection getMeetMeRooms() throws ManagerCommunicationException - { + public Collection getMeetMeRooms() throws ManagerCommunicationException { return this.impl.getMeetMeRooms(); } - public MeetMeRoom getMeetMeRoom(String name) throws ManagerCommunicationException - { + public MeetMeRoom getMeetMeRoom(String name) throws ManagerCommunicationException { return this.impl.getMeetMeRoom(name); } - public Collection getQueues() throws ManagerCommunicationException - { + public Collection getQueues() throws ManagerCommunicationException { return this.impl.getQueues(); } - public String getVersion() throws ManagerCommunicationException - { + public String getVersion() throws ManagerCommunicationException { return this.impl.getVersion(); } - public int[] getVersion(String file) throws ManagerCommunicationException - { + public int[] getVersion(String file) throws ManagerCommunicationException { return this.impl.getVersion(file); } - public String getGlobalVariable(String variable) throws ManagerCommunicationException - { + public String getGlobalVariable(String variable) throws ManagerCommunicationException { return this.impl.getGlobalVariable(variable); } - public void setGlobalVariable(String variable, String value) throws ManagerCommunicationException - { + public void setGlobalVariable(String variable, String value) throws ManagerCommunicationException { this.impl.setGlobalVariable(variable, value); } - public Collection getVoicemailboxes() throws ManagerCommunicationException - { + public Collection getVoicemailboxes() throws ManagerCommunicationException { return this.impl.getVoicemailboxes(); } - public List executeCliCommand(String command) throws ManagerCommunicationException - { + public List executeCliCommand(String command) throws ManagerCommunicationException { return this.impl.executeCliCommand(command); } - public boolean isModuleLoaded(String module) throws ManagerCommunicationException - { + public boolean isModuleLoaded(String module) throws ManagerCommunicationException { return this.impl.isModuleLoaded(module); } - public ConfigFile getConfig(String filename) throws ManagerCommunicationException - { + public ConfigFile getConfig(String filename) throws ManagerCommunicationException { return this.impl.getConfig(filename); } - public void reloadAllModules() throws ManagerCommunicationException - { + public void reloadAllModules() throws ManagerCommunicationException { this.impl.reloadAllModules(); } - public void reloadModule(String module) throws ManagerCommunicationException - { + public void reloadModule(String module) throws ManagerCommunicationException { this.impl.reloadModule(module); } - public void unloadModule(String module) throws ManagerCommunicationException - { + public void unloadModule(String module) throws ManagerCommunicationException { this.impl.unloadModule(module); } - public void loadModule(String module) throws ManagerCommunicationException - { + public void loadModule(String module) throws ManagerCommunicationException { this.impl.loadModule(module); } - public void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException - { + public void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException { this.impl.addAsteriskServerListener(listener); } - public void removeAsteriskServerListener(AsteriskServerListener listener) - { + public void removeAsteriskServerListener(AsteriskServerListener listener) { this.impl.removeAsteriskServerListener(listener); } - public boolean isAsteriskServerListening(AsteriskServerListener listener) - { + public boolean isAsteriskServerListening(AsteriskServerListener listener) { return this.impl.isAsteriskServerListening(listener); } - public void shutdown() - { + public void shutdown() { this.impl.shutdown(); } - public Collection getAgents() throws ManagerCommunicationException - { + public Collection getAgents() throws ManagerCommunicationException { return this.impl.getAgents(); } - public AsteriskQueue getQueueByName(String queueName) - { + public AsteriskQueue getQueueByName(String queueName) { return impl.getQueueByName(queueName); } @Override - public List getQueuesUpdatedAfter(Date date) - { + public List getQueuesUpdatedAfter(Date date) { return impl.getQueuesUpdatedAfter(date); } @Override - public void forceQueuesMonitor(boolean force) - { + public void forceQueuesMonitor(boolean force) { impl.forceQueuesMonitor(force); } @Override - public boolean isQueuesMonitorForced() - { + public boolean isQueuesMonitorForced() { return impl.isQueuesMonitorForced(); } @Override - public void addChainListener(ManagerEventListener chainListener) - { + public void addChainListener(ManagerEventListener chainListener) { this.impl.addChainListener(chainListener); } @Override - public void removeChainListener(ManagerEventListener chainListener) - { + 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 f944001ee..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,35 +54,29 @@ 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() - { - StringBuilder sb; + public String toString() { + StringBuilder sb; sb = new StringBuilder("Extension["); sb.append("context='").append(getContext()).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 ae08cccef..c8c81ae91 100644 --- a/src/main/java/org/asteriskjava/live/HangupCause.java +++ b/src/main/java/org/asteriskjava/live/HangupCause.java @@ -26,8 +26,7 @@ * @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), @@ -88,13 +87,11 @@ public enum HangupCause AST_CAUSE_NOTDEFINED(0), AST_CAUSE_NOSUCHDRIVER(AST_CAUSE_CHAN_NOT_IMPLEMENTED); - HangupCause(int code) - { + HangupCause(int code) { this.code = code; } - HangupCause(HangupCause cause) - { + HangupCause(HangupCause cause) { this.code = cause.code; } @@ -104,8 +101,7 @@ public enum HangupCause * * @return the numeric cause code. */ - public int getCode() - { + public int getCode() { return code; } @@ -115,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) - { + public static synchronized HangupCause getByCode(int code) { + if (causes == null) { causes = new HashMap<>(); - for (HangupCause cause : values()) - { + for (HangupCause cause : values()) { causes.put(cause.code, cause); } } @@ -132,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 3186f4d34..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,14 +66,15 @@ 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 8a4ca11ed..384f00248 100644 --- a/src/main/java/org/asteriskjava/live/QueueMemberState.java +++ b/src/main/java/org/asteriskjava/live/QueueMemberState.java @@ -47,11 +47,10 @@ * @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), /** @@ -89,8 +88,6 @@ public enum QueueMemberState DEVICE_ONHOLD(QueueMemberEvent.AST_DEVICE_ONHOLD); - - private final int status; /** @@ -98,8 +95,7 @@ public enum QueueMemberState * * @param status the numerical status code. */ - QueueMemberState(int status) - { + QueueMemberState(int status) { this.status = status; } @@ -107,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; } @@ -121,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 index b54a7e05d..25a1aff66 100644 --- a/src/main/java/org/asteriskjava/live/RecordingException.java +++ b/src/main/java/org/asteriskjava/live/RecordingException.java @@ -18,12 +18,11 @@ /** * Indicates that a record operation related issue has occured, - * + * * @author videanuadrian * @version $Id$ */ -public class RecordingException extends LiveException -{ +public class RecordingException extends LiveException { /** * Serial version identifier. */ @@ -32,11 +31,10 @@ public class RecordingException extends LiveException /** * Creates a new instance with the given message. - * + * * @param message the message */ - public RecordingException(String 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 15367b458..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,78 +51,70 @@ 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() - { - StringBuilder sb; + public String toString() { + StringBuilder sb; sb = new StringBuilder(100); sb.append("Voicemailbox["); diff --git a/src/main/java/org/asteriskjava/live/internal/.gitignore b/src/main/java/org/asteriskjava/live/internal/.gitignore deleted file mode 100644 index 9f05d58f2..000000000 --- a/src/main/java/org/asteriskjava/live/internal/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -/ConfigFileImpl.class -/Constants.class -/ManagerCommunicationExceptionMapper.class -/ManagerConnectionPool.class -/MeetMeManager.class -/MeetMeRoomImpl.class -/MeetMeUserImpl.class -/OriginateCallbackData.class -/QueueManager.class -/AbstractLiveObject.class -/AgentManager.class -/AsteriskAgentImpl.class -/AsteriskChannelImpl.class -/AsteriskQueueEntryImpl.class -/AsteriskQueueImpl$ServiceLevelTimerTask.class -/AsteriskQueueImpl.class -/AsteriskQueueMemberImpl.class -/AsteriskServerImpl.class -/CallDetailRecordImpl.class -/ChannelManager.class diff --git a/src/main/java/org/asteriskjava/live/internal/AbstractLiveObject.java b/src/main/java/org/asteriskjava/live/internal/AbstractLiveObject.java index 0ae501c3c..231bb9c0e 100644 --- a/src/main/java/org/asteriskjava/live/internal/AbstractLiveObject.java +++ b/src/main/java/org/asteriskjava/live/internal/AbstractLiveObject.java @@ -16,22 +16,22 @@ */ 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; @@ -39,74 +39,58 @@ abstract class AbstractLiveObject implements LiveObject // last time this object was updated private long lastUpdate; - AbstractLiveObject(AsteriskServerImpl server) - { + 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) - { + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { boolean haveToAdd = true; - for (PropertyChangeListener l : changes.getPropertyChangeListeners()) - { - if (l == listener) - { + for (PropertyChangeListener l : changes.getPropertyChangeListeners()) { + if (l == listener) { haveToAdd = false; break; } } - if (haveToAdd) - { + 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) - { + protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + if (oldValue != null || newValue != null) { stampLastUpdate(); - try - { + try { changes.firePropertyChange(propertyName, oldValue, newValue); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn("Uncaught exception in PropertyChangeListener", e); } } } @Override - public long getLastUpdateMillis() - { + public long getLastUpdateMillis() { return lastUpdate; } - public void stampLastUpdate() - { + 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 51bc073f5..f9f5a2533 100644 --- a/src/main/java/org/asteriskjava/live/internal/AgentManager.java +++ b/src/main/java/org/asteriskjava/live/internal/AgentManager.java @@ -16,28 +16,21 @@ */ 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 @@ -47,8 +40,7 @@ * @version $Id$ * @since 0.3.1 */ -public class AgentManager -{ +public class AgentManager { private final Log logger = LogFactory.getLog(this.getClass()); @@ -57,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<>()); } /** @@ -79,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) - { - logger.info( 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(); } } @@ -108,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); @@ -122,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); @@ -137,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); } } @@ -150,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; } @@ -167,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); } } @@ -184,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); @@ -201,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; @@ -238,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; } @@ -256,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; @@ -277,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; } @@ -296,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; @@ -312,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 1d38c3f67..97d3ef6c7 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskAgentImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskAgentImpl.java @@ -18,6 +18,7 @@ import org.asteriskjava.live.AgentState; import org.asteriskjava.live.AsteriskAgent; +import org.asteriskjava.lock.Locker.LockCloser; /** * Default implementation of the AsteriskAgent interface. @@ -25,17 +26,14 @@ * @author Patrick Breucking * @version $Id$ */ -public class AsteriskAgentImpl extends AbstractLiveObject implements AsteriskAgent -{ +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,31 +41,29 @@ 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() - { + public String toString() { final StringBuilder sb; sb = new StringBuilder("AsteriskAgent["); @@ -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 770d4001a..ff1015708 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskChannelImpl.java @@ -16,67 +16,41 @@ */ package org.asteriskjava.live.internal; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -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.live.RecordingException; -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.PauseMixMonitorAction; -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. * * @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 List extensionHistory; - private final List stateHistory; - private final List linkedChannelHistory; - private final List dialedChannelHistory; - private final List dialedChannels; - private final List dialingChannels; + 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 List linkedChannels; - private final Map variables; + private final LockableList linkedChannels; + private final LockableMap variables; /** * Unique id of this channel. */ @@ -149,31 +123,26 @@ class AsteriskChannelImpl extends AbstractLiveObject implements AsteriskChannel /** * Creates a new Channel. * - * @param server server this channel belongs to. - * @param name name of this channel, for example "SIP/1310-20da". - * @param id unique id of this channel, for example "1099015093.165". + * @param server server this channel belongs to. + * @param name name of this channel, for example "SIP/1310-20da". + * @param id unique id of this channel, for example "1099015093.165". * @param dateOfCreation date this channel has been created. * @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) - { + if (dateOfCreation == null) { throw new IllegalArgumentException( "Parameter 'dateOfCreation' passed to AsteriskChannelImpl() must not be null."); } @@ -181,18 +150,17 @@ class AsteriskChannelImpl extends AbstractLiveObject implements AsteriskChannel 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.dialedChannels = new ArrayList<>(); - this.dialingChannels = new ArrayList<>(); - this.linkedChannels = new ArrayList<>(); - } - - public String getId() - { + 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() { return id; } @@ -200,14 +168,12 @@ public String getId() * Changes the id of this channel. * * @param date date of the name change. - * @param id the new unique id of this channel. + * @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,8 +242,7 @@ public boolean wasInState(ChannelState state) return false; } - public boolean wasBusy() - { + public boolean wasBusy() { return wasInState(ChannelState.BUSY) || hangupCause == HangupCause.AST_CAUSE_BUSY || hangupCause == HangupCause.AST_CAUSE_USER_BUSY; } @@ -297,33 +250,32 @@ public boolean wasBusy() /** * Changes the state of this channel. * - * @param date when the state change occurred. + * @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; } @@ -332,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(); } } @@ -359,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(); } } @@ -378,12 +319,10 @@ public Extension getFirstExtension() return extension; } - public List getExtensionHistory() - { + public List getExtensionHistory() { final List copy; - synchronized (extensionHistory) - { + try (LockCloser closer = extensionHistory.withLock()) { copy = new ArrayList<>(extensionHistory); } @@ -393,51 +332,43 @@ public List getExtensionHistory() /** * Adds a visted dialplan entry to the history. * - * @param date the date the extension has been visited. + * @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; @@ -448,17 +379,18 @@ void callDetailRecordReceived(Date date, CallDetailRecordImpl callDetailRecord) * Sets dateOfRemoval, hangupCause and hangupCauseText and changes state to * {@link ChannelState#HUNGUP}. Fires a PropertyChangeEvent for state. * - * @param dateOfRemoval date the channel was hung up - * @param hangupCause cause for hangup + * @param dateOfRemoval date the channel was hung up + * @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); + } } /** @@ -466,12 +398,10 @@ synchronized void hungup(Date dateOfRemoval, HangupCause hangupCause, String han * * @return List of all dialed channels */ - public List getDialedChannels() - { + public List getDialedChannels() { final List copy; - synchronized (dialedChannels) - { + try (LockCloser closer = dialedChannels.withLock()) { copy = new ArrayList<>(dialedChannels); } @@ -480,12 +410,9 @@ public List getDialedChannels() /* dialed channels */ - public AsteriskChannel getDialedChannel() - { - synchronized (dialedChannels) - { - for (AsteriskChannel channel : dialedChannels) - { + public AsteriskChannel getDialedChannel() { + try (LockCloser closer = dialedChannels.withLock()) { + for (AsteriskChannel channel : dialedChannels) { if (channel != null) return channel; } @@ -493,183 +420,156 @@ public AsteriskChannel getDialedChannel() return null; } - public List getDialedChannelHistory() - { + public List getDialedChannelHistory() { final List copy; - synchronized (dialedChannelHistory) - { + try (LockCloser closer = dialedChannelHistory.withLock()) { copy = new ArrayList<>(dialedChannelHistory); } return copy; } - synchronized void channelDialed(Date date, AsteriskChannel dialedChannel) - { - final AsteriskChannel oldDialedChannel; - synchronized (dialedChannels) - { - if (dialedChannels.isEmpty()) - oldDialedChannel = null; - else - oldDialedChannel = dialedChannels.get(dialedChannels.size() - 1); - dialedChannels.add(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); - synchronized (dialedChannelHistory) - { - dialedChannelHistory.add(historyEntry); - } + historyEntry = new DialedChannelHistoryEntry(date, dialedChannel); + try (LockCloser closer3 = dialedChannelHistory.withLock()) { + dialedChannelHistory.add(historyEntry); + } - firePropertyChange(PROPERTY_DIALED_CHANNEL, oldDialedChannel, dialedChannel); + firePropertyChange(PROPERTY_DIALED_CHANNEL, oldDialedChannel, dialedChannel); + } } /* dialed channels */ - public AsteriskChannel getDialingChannel() - { - synchronized (dialingChannels) - { + 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; - synchronized (this.dialingChannels) - { - if (this.dialingChannels.isEmpty()) - { - oldDialingChannel = null; - this.dialingChannels.add(dialingChannel); - } - else - { - oldDialingChannel = this.dialingChannels.get(0); - this.dialingChannels.set(0, 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); + } } - } - firePropertyChange(PROPERTY_DIALING_CHANNEL, oldDialingChannel, dialingChannel); + firePropertyChange(PROPERTY_DIALING_CHANNEL, oldDialingChannel, dialingChannel); + } } /* linked channels */ - public AsteriskChannel getLinkedChannel() - { - synchronized (linkedChannels) - { + 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) - { + try (LockCloser closer = linkedChannelHistory.withLock()) { copy = new ArrayList<>(linkedChannelHistory); } return copy; } - public boolean wasLinked() - { + public boolean wasLinked() { return wasLinked; } /** * Sets the channel this channel is bridged with. * - * @param date the date this channel was linked. + * @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; - synchronized (this.linkedChannels) - { - if (this.linkedChannels.isEmpty()) - { - oldLinkedChannel = null; - this.linkedChannels.add(linkedChannel); - } - else - { - oldLinkedChannel = this.linkedChannels.get(0); - this.linkedChannels.set(0, linkedChannel); + 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); + } } - } - final LinkedChannelHistoryEntry historyEntry; + final LinkedChannelHistoryEntry historyEntry; - historyEntry = new LinkedChannelHistoryEntry(date, linkedChannel); - synchronized (linkedChannelHistory) - { - linkedChannelHistory.add(historyEntry); + historyEntry = new LinkedChannelHistoryEntry(date, linkedChannel); + try (LockCloser closer3 = linkedChannelHistory.withLock()) { + linkedChannelHistory.add(historyEntry); + } + this.wasLinked = true; + firePropertyChange(PROPERTY_LINKED_CHANNEL, oldLinkedChannel, linkedChannel); } - this.wasLinked = true; - firePropertyChange(PROPERTY_LINKED_CHANNEL, oldLinkedChannel, linkedChannel); } - synchronized void channelUnlinked(Date date) - { - final AsteriskChannel oldLinkedChannel; + void channelUnlinked(Date date) { + try (LockCloser closer = this.withLock()) { + final AsteriskChannel oldLinkedChannel; - synchronized (this.linkedChannels) - { - if (this.linkedChannels.isEmpty()) - { - oldLinkedChannel = null; - } - else - { - oldLinkedChannel = this.linkedChannels.get(0); + try (LockCloser closer2 = this.linkedChannels.withLock()) { + if (this.linkedChannels.isEmpty()) { + oldLinkedChannel = null; + } else { + oldLinkedChannel = this.linkedChannels.get(0); + } + linkedChannels.clear(); } - linkedChannels.clear(); - } - final LinkedChannelHistoryEntry historyEntry; + final LinkedChannelHistoryEntry historyEntry; - synchronized (linkedChannelHistory) - { - if (linkedChannelHistory.isEmpty()) - { - historyEntry = null; + try (LockCloser closer3 = linkedChannelHistory.withLock()) { + if (linkedChannelHistory.isEmpty()) { + historyEntry = null; + } else { + historyEntry = linkedChannelHistory.get(linkedChannelHistory.size() - 1); + } } - else - { - historyEntry = linkedChannelHistory.get(linkedChannelHistory.size() - 1); + + if (historyEntry != null) { + historyEntry.setDateUnlinked(date); } - } - if (historyEntry != null) - { - historyEntry.setDateUnlinked(date); + firePropertyChange(PROPERTY_LINKED_CHANNEL, oldLinkedChannel, 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); @@ -677,102 +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 - { + 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 - { + throws ManagerCommunicationException, NoSuchChannelException { ManagerResponse response; - synchronized (linkedChannels) - { - if (linkedChannels.isEmpty()) - { + try (LockCloser closer = linkedChannels.withLock()) { + if (linkedChannels.isEmpty()) { response = server.sendAction(new RedirectAction(name, context, exten, priority)); - } - else - { + } 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 } @@ -781,118 +660,96 @@ 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 - { + 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 - { + 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 - { + 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")) - { + 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()); @@ -900,35 +757,29 @@ public void pauseMixMonitor(MixMonitorDirection direction) } public void unPauseMixMonitor(MixMonitorDirection direction) - throws ManagerCommunicationException, NoSuchChannelException, RecordingException - { + 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")) - { + 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() - { + 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; } - public String getParkingLot() - { + public String getParkingLot() { return this.parkingLot; } - void setParkedAt(Extension parkedAt, String parkingLot) - { + void setParkedAt(Extension parkedAt, String parkingLot) { final Extension oldParkedAt = this.parkedAt; final String oldParkingLot = this.parkingLot; @@ -938,70 +789,58 @@ void setParkedAt(Extension parkedAt, String parkingLot) firePropertyChange(PROPERTY_PARKING_LOT, oldParkingLot, parkingLot); } - void updateVariable(String name, String value) - { - synchronized (variables) - { + 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) - { + 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); } - 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() - { + public boolean isMonitored() { return this.isMonitored; } - void setMonitored(boolean monitored) - { + void setMonitored(boolean monitored) { final boolean oldMonitored = this.isMonitored; this.isMonitored = monitored; @@ -1009,62 +848,46 @@ void setMonitored(boolean monitored) } @Override - public String toString() - { + public String toString() { final StringBuilder sb; - final List dialedChannels; - final List dialingChannel; - final List linkedChannel; + final LockableList dialingChannel; + final LockableList linkedChannel; 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(","); - dialedChannels = getDialedChannels(); dialingChannel = this.dialingChannels; linkedChannel = this.linkedChannels; } - if (dialedChannels.isEmpty()) - { + if (dialedChannels.isEmpty()) { sb.append("dialedChannel=null,"); - } - else - { + } else { sb.append("dialedChannel=AsteriskChannel["); - synchronized (dialedChannels) - { - for (AsteriskChannel dialedChannel : dialedChannels) - { + 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.isEmpty()) - { + if (dialingChannel.isEmpty()) { sb.append("dialingChannel=null,"); - } - else - { + } else { sb.append("dialingChannel=AsteriskChannel["); sb.append("id='").append(dialingChannel.get(0).getId()).append("',"); sb.append("name='").append(dialingChannel.get(0).getName()).append("'],"); } - synchronized (linkedChannel) - { - if (linkedChannel.isEmpty()) - { + try (LockCloser closer = linkedChannel.withLock()) { + if (linkedChannel.isEmpty()) { sb.append("linkedChannel=null"); - } - else - { + } else { sb.append("linkedChannel=AsteriskChannel["); { sb.append("id='").append(linkedChannel.get(0).getId()).append("',"); diff --git a/src/main/java/org/asteriskjava/live/internal/AsteriskQueueEntryImpl.java b/src/main/java/org/asteriskjava/live/internal/AsteriskQueueEntryImpl.java index 4ab3d0f90..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() - { - StringBuilder sb; + public String toString() { + StringBuilder sb; int systemHashcode; 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 989f72531..b3b922ef6 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskQueueImpl.java @@ -16,48 +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.Map; -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 */ - 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); } } @@ -68,7 +60,9 @@ public void run() private String strategy; private Integer serviceLevel; - /** 101118 Octavio Luna Agregado para Ver cambios en Vivo **/ + /** + * 101118 Octavio Luna Agregado para Ver cambios en Vivo + **/ private Integer calls; private Integer holdTime; private Integer talkTime; @@ -78,28 +72,26 @@ public void run() /****/ private Integer weight; - private final List entries; + private final LockableList entries; private final Timer timer; - private final Map members; - private final List listeners; - private final Map serviceLevelTimerTasks; - - 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) - { + 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, 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; @@ -110,225 +102,201 @@ public void run() 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; } /** - * * @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() - { + boolean setMax(Integer max) { + if (!AstUtil.isEqual(this.max, max)) { + this.max = max; + stampLastUpdate(); + return true; + } + return false; + } + + public Integer getServiceLevel() { return serviceLevel; } /** - * * @param serviceLevel * @return */ - boolean setServiceLevel(Integer serviceLevel) - { - if(!AstUtil.isEqual(this.serviceLevel, serviceLevel)){ - this.serviceLevel = serviceLevel; - stampLastUpdate(); - return true; - } - return false; + boolean setServiceLevel(Integer serviceLevel) { + if (!AstUtil.isEqual(this.serviceLevel, serviceLevel)) { + this.serviceLevel = serviceLevel; + stampLastUpdate(); + return true; + } + return false; } @Override - public Integer getCalls() { - return calls; - } + public Integer getCalls() { + return calls; + } /** - * * @param calls - * @return true if value updated, false otherwise + * @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; - } + if (!AstUtil.isEqual(this.calls, calls)) { + this.calls = calls; + stampLastUpdate(); + return true; + } + return false; + } @Override public Integer getWaiting() { - return calls; + return calls; } @Override - public Integer getHoldTime() { - return holdTime; - } + 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; - } + if (!AstUtil.isEqual(this.holdTime, holdTime)) { + this.holdTime = holdTime; + stampLastUpdate(); + return true; + } + return false; + } @Override - public Integer getTalkTime() { - return talkTime; - } + 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; - } + if (!AstUtil.isEqual(this.talkTime, talkTime)) { + this.talkTime = talkTime; + stampLastUpdate(); + return true; + } + return false; + } @Override - public Integer getCompleted() { - return completed; - } + public Integer getCompleted() { + return completed; + } /** - * * @param completed - * @return true if value updated, false otherwise + * @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; - } + if (!AstUtil.isEqual(this.completed, completed)) { + this.completed = completed; + stampLastUpdate(); + return true; + } + return false; + } @Override - public Integer getAbandoned() { - return abandoned; - } + 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() - { + 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() { return 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) - { + boolean setWeight(Integer weight) { + if (!AstUtil.isEqual(this.weight, weight)) { + this.weight = weight; + stampLastUpdate(); + return true; + } + return false; + } + + 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++; @@ -337,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
    • @@ -347,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 ! @@ -375,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); @@ -385,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
    • @@ -396,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); @@ -409,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); @@ -430,8 +400,7 @@ void removeEntry(AsteriskQueueEntryImpl entry, Date dateReceived) } @Override - public String toString() - { + public String toString() { final StringBuilder sb; sb = new StringBuilder("AsteriskQueue["); @@ -447,12 +416,10 @@ public String toString() sb.append("abandoned='").append(getAbandoned()).append("',"); sb.append("serviceLevelPerf='").append(getServiceLevelPerf()).append("',"); - synchronized (entries) - { + 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)); @@ -461,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); } } @@ -482,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); } } @@ -505,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); } } @@ -524,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); } } @@ -547,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); } } @@ -574,11 +515,9 @@ void fireMemberRemoved(AsteriskQueueMemberImpl member) * * @see org.asteriskjava.live.AsteriskQueue#getMembers() */ - public Collection getMembers() - { + public Collection getMembers() { List listOfMembers = new ArrayList<>(members.size()); - synchronized (members) - { + try (LockCloser closer = members.withLock()) { listOfMembers.addAll(members.values()); } return listOfMembers; @@ -590,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); } } @@ -607,13 +543,10 @@ 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. @@ -630,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; @@ -649,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); } } @@ -673,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; } } @@ -688,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); } } @@ -736,21 +645,17 @@ 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 0831b6290..e37a44f61 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskQueueMemberImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskQueueMemberImpl.java @@ -16,12 +16,8 @@ */ package org.asteriskjava.live.internal; -import org.asteriskjava.live.AsteriskQueue; -import org.asteriskjava.live.AsteriskQueueMember; -import org.asteriskjava.live.InvalidPenaltyException; -import org.asteriskjava.live.ManagerCommunicationException; -import org.asteriskjava.live.NoSuchInterfaceException; -import org.asteriskjava.live.QueueMemberState; +import org.asteriskjava.live.*; +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.action.QueuePauseAction; import org.asteriskjava.manager.action.QueuePenaltyAction; import org.asteriskjava.manager.response.ManagerError; @@ -36,8 +32,7 @@ * @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; @@ -50,19 +45,18 @@ class AsteriskQueueMemberImpl extends AbstractLiveObject implements AsteriskQueu /** * Creates a new queue member. * - * @param server server this channel belongs to. - * @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 penalty penalty of this member. + * @param server server this channel belongs to. + * @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 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. + * 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, Integer callsTaken, Long lastCall) - { + QueueMemberState state, boolean paused, Integer penalty, String membership, Integer callsTaken, Long lastCall) { super(server); this.queue = queue; this.location = location; @@ -74,29 +68,24 @@ class AsteriskQueueMemberImpl extends AbstractLiveObject implements AsteriskQueu 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; } @Override - public Integer getCallsTaken() - { + public Integer getCallsTaken() { return callsTaken; } - public void setCallsTaken(Integer callsTaken) - { + public void setCallsTaken(Integer callsTaken) { this.callsTaken = callsTaken; } @@ -105,49 +94,40 @@ public void setCallsTaken(Integer callsTaken) * 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. */ @Override - public Long getLastCall() - { + public Long getLastCall() { return lastCall; } - public void setLastCall(Long lastCall) - { + public void setLastCall(Long lastCall) { this.lastCall = lastCall; } @Deprecated - public boolean getPaused() - { + 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) - { + if (response instanceof ManagerError) { // Message: Interface not found - if (action.getQueue() != null) - { + if (action.getQueue() != null) { // Message: Interface not found throw new NoSuchInterfaceException("Unable to change paused state for '" + action.getInterface() + "' on '" + action.getQueue() + "': " + response.getMessage()); @@ -157,45 +137,37 @@ private void sendPauseAction(QueuePauseAction action) throws ManagerCommunicatio } } - public String getMembership() - { + public String getMembership() { return membership; } - public boolean isStatic() - { + public boolean isStatic() { return "static".equals(membership); } - public boolean isDynamic() - { + 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) - { + 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) - { + if (response instanceof ManagerError) { throw new InvalidPenaltyException( "Unable to set penalty for '" + location + "' on '" + queue.getName() + "': " + response.getMessage()); } } @Override - public String toString() - { + public String toString() { final StringBuilder sb; sb = new StringBuilder("AsteriskQueueMember["); @@ -212,64 +184,64 @@ public String toString() return sb.toString(); } - synchronized boolean stateChanged(QueueMemberState state) - { - if (!AstUtil.isEqual(this.state, state)) - { - QueueMemberState oldState = this.state; - this.state = state; - firePropertyChange(PROPERTY_STATE, oldState, state); - return true; + 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; } - return false; } - synchronized boolean penaltyChanged(Integer penalty) - { - if (!AstUtil.isEqual(this.penalty, penalty)) - { - Integer oldPenalty = this.penalty; - this.penalty = penalty; - firePropertyChange(PROPERTY_PENALTY, oldPenalty, penalty); - return true; - } + 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; + return false; + } } - synchronized boolean pausedChanged(boolean paused) - { - if (!AstUtil.isEqual(this.paused, paused)) - { - boolean oldPaused = this.paused; - this.paused = paused; - firePropertyChange(PROPERTY_PAUSED, oldPaused, paused); - return true; + 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; } - return false; } - synchronized boolean callsTakenChanged(Integer callsTaken) - { - if (!AstUtil.isEqual(this.callsTaken, callsTaken)) - { - Integer oldcallsTaken = this.callsTaken; - this.callsTaken = callsTaken; - firePropertyChange(PROPERTY_CALLSTAKEN, oldcallsTaken, callsTaken); - return true; + 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; } - return false; } - synchronized boolean lastCallChanged(Long lastCall) - { - if (!AstUtil.isEqual(this.lastCall, lastCall)) - { - Long oldlastCall = this.lastCall; - this.lastCall = lastCall; - firePropertyChange(PROPERTY_LASTCALL, oldlastCall, lastCall); - return true; + 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; } - 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 f05b33e40..7062e5ad7 100644 --- a/src/main/java/org/asteriskjava/live/internal/AsteriskServerImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/AsteriskServerImpl.java @@ -16,114 +16,35 @@ */ package org.asteriskjava.live.internal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.config.ConfigFile; -import org.asteriskjava.live.AsteriskAgent; -import org.asteriskjava.live.AsteriskChannel; -import org.asteriskjava.live.AsteriskQueue; -import org.asteriskjava.live.AsteriskQueueEntry; -import org.asteriskjava.live.AsteriskServer; -import org.asteriskjava.live.AsteriskServerListener; -import org.asteriskjava.live.CallerId; -import org.asteriskjava.live.ChannelState; -import org.asteriskjava.live.LiveException; -import org.asteriskjava.live.ManagerCommunicationException; -import org.asteriskjava.live.MeetMeRoom; -import org.asteriskjava.live.MeetMeUser; -import org.asteriskjava.live.NoSuchChannelException; -import org.asteriskjava.live.OriginateCallback; -import org.asteriskjava.live.Voicemailbox; -import org.asteriskjava.manager.ManagerConnection; -import org.asteriskjava.manager.ManagerConnectionState; -import org.asteriskjava.manager.ManagerEventListener; -import org.asteriskjava.manager.ManagerEventListenerProxy; -import org.asteriskjava.manager.ResponseEvents; -import org.asteriskjava.manager.action.CommandAction; -import org.asteriskjava.manager.action.DbGetAction; -import org.asteriskjava.manager.action.DbPutAction; -import org.asteriskjava.manager.action.EventGeneratingAction; -import org.asteriskjava.manager.action.GetConfigAction; -import org.asteriskjava.manager.action.GetVarAction; -import org.asteriskjava.manager.action.MailboxCountAction; -import org.asteriskjava.manager.action.ManagerAction; -import org.asteriskjava.manager.action.ModuleCheckAction; -import org.asteriskjava.manager.action.ModuleLoadAction; -import org.asteriskjava.manager.action.OriginateAction; -import org.asteriskjava.manager.action.SetVarAction; -import org.asteriskjava.manager.action.SipPeersAction; -import org.asteriskjava.manager.event.AbstractMeetMeEvent; -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.BridgeEvent; -import org.asteriskjava.manager.event.CdrEvent; -import org.asteriskjava.manager.event.ConnectEvent; -import org.asteriskjava.manager.event.DbGetResponseEvent; -import org.asteriskjava.manager.event.DialEvent; -import org.asteriskjava.manager.event.DisconnectEvent; -import org.asteriskjava.manager.event.DtmfEvent; -import org.asteriskjava.manager.event.HangupEvent; -import org.asteriskjava.manager.event.JoinEvent; -import org.asteriskjava.manager.event.LeaveEvent; -import org.asteriskjava.manager.event.ManagerEvent; -import org.asteriskjava.manager.event.MonitorStartEvent; -import org.asteriskjava.manager.event.MonitorStopEvent; -import org.asteriskjava.manager.event.NewCallerIdEvent; -import org.asteriskjava.manager.event.NewChannelEvent; -import org.asteriskjava.manager.event.NewExtenEvent; -import org.asteriskjava.manager.event.NewStateEvent; -import org.asteriskjava.manager.event.OriginateResponseEvent; -import org.asteriskjava.manager.event.ParkedCallEvent; -import org.asteriskjava.manager.event.ParkedCallGiveUpEvent; -import org.asteriskjava.manager.event.ParkedCallTimeOutEvent; -import org.asteriskjava.manager.event.PeerEntryEvent; -import org.asteriskjava.manager.event.QueueMemberAddedEvent; -import org.asteriskjava.manager.event.QueueMemberPausedEvent; -import org.asteriskjava.manager.event.QueueMemberPenaltyEvent; -import org.asteriskjava.manager.event.QueueMemberRemovedEvent; -import org.asteriskjava.manager.event.QueueMemberStatusEvent; -import org.asteriskjava.manager.event.RenameEvent; -import org.asteriskjava.manager.event.ResponseEvent; -import org.asteriskjava.manager.event.UnparkedCallEvent; -import org.asteriskjava.manager.event.VarSetEvent; -import org.asteriskjava.manager.response.CommandResponse; -import org.asteriskjava.manager.response.GetConfigResponse; -import org.asteriskjava.manager.response.MailboxCountResponse; -import org.asteriskjava.manager.response.ManagerError; -import org.asteriskjava.manager.response.ManagerResponse; -import org.asteriskjava.manager.response.ModuleCheckResponse; +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 java.util.*; +import java.util.concurrent.atomic.AtomicLong; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * Default implementation of the {@link AsteriskServer} interface. * * @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"; @@ -146,7 +67,7 @@ public class AsteriskServerImpl implements AsteriskServer, ManagerEventListener private boolean initialized = false; private boolean initializing = false; - final Set listeners; + final LockableSet listeners; final ChannelManager channelManager; final MeetMeManager meetMeManager; @@ -168,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; @@ -203,16 +124,15 @@ public class AsteriskServerImpl implements AsteriskServer, ManagerEventListener * events have been processed by the live ChannelManager before you receive * an event and as such the names will always match. */ - private List chainListeners = new ArrayList<>(); + private LockableList chainListeners = new LockableList<>(new ArrayList<>()); /** * Creates a new instance. */ - public AsteriskServerImpl() - { + public AsteriskServerImpl() { idCounter = new AtomicLong(); - listeners = new LinkedHashSet<>(); - 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); @@ -223,14 +143,13 @@ public AsteriskServerImpl() * Creates a new instance. * * @param eventConnection the ManagerConnection to use for receiving events - * from Asterisk. + * from Asterisk. */ - public AsteriskServerImpl(ManagerConnection eventConnection) - { + public AsteriskServerImpl(ManagerConnection eventConnection) { this(); setManagerConnection(eventConnection); // todo: !!! Possible bug !!!: - // call to overridable method - // over object construction + // call to overridable method + // over object construction } /** @@ -241,100 +160,82 @@ public AsteriskServerImpl(ManagerConnection eventConnection) * Default is false. * * @param skipQueues true to skip queue initialization, - * false to not skip. + * 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; } - 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 || initializing) - { - return; - } - if (asyncEventHandling && managerEventListenerProxy == null) - { - managerEventListenerProxy = new ManagerEventListenerProxy(this); - eventConnection.addEventListener(managerEventListenerProxy); - } - else if (!asyncEventHandling && eventListener == null) - { - eventListener = this; - eventConnection.addEventListener(eventListener); - } + private void initializeIfNeeded() throws ManagerCommunicationException { + try (LockCloser closer = this.withLock()) { + if (initialized || initializing) { + return; + } + if (asyncEventHandling && managerEventListenerProxy == null) { + managerEventListenerProxy = new ManagerEventListenerProxy(this); + eventConnection.addEventListener(managerEventListenerProxy); + } else if (!asyncEventHandling && eventListener == null) { + eventListener = this; + eventConnection.addEventListener(eventListener); + } - initializing = true; + initializing = true; - if (eventConnection.getState() == ManagerConnectionState.INITIAL - || eventConnection.getState() == ManagerConnectionState.DISCONNECTED) - { - try - { - eventConnection.login(); - } - catch (Exception e) - { - throw new ManagerCommunicationException("Unable to login: " + e.getMessage(), e); + 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(); - } + 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); + 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"); - initializing = false; - initialized = true; } /* Implementation of the AsteriskServer interface */ public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) - throws ManagerCommunicationException, NoSuchChannelException - { + 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 - { + CallerId callerId, Map variables) throws ManagerCommunicationException, NoSuchChannelException { final OriginateAction originateAction; originateAction = new OriginateAction(); @@ -343,8 +244,7 @@ public AsteriskChannel originateToExtension(String channel, String context, Stri originateAction.setExten(exten); originateAction.setPriority(priority); originateAction.setTimeout(timeout); - if (callerId != null) - { + if (callerId != null) { originateAction.setCallerId(callerId.toString()); } originateAction.setVariables(variables); @@ -353,14 +253,12 @@ public AsteriskChannel originateToExtension(String channel, String context, Stri } public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout) - throws ManagerCommunicationException, NoSuchChannelException - { + 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 - { + CallerId callerId, Map variables) throws ManagerCommunicationException, NoSuchChannelException { final OriginateAction originateAction; originateAction = new OriginateAction(); @@ -368,8 +266,7 @@ public AsteriskChannel originateToApplication(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); @@ -378,8 +275,7 @@ public AsteriskChannel originateToApplication(String channel, String application } public AsteriskChannel originate(OriginateAction originateAction) - throws ManagerCommunicationException, NoSuchChannelException - { + throws ManagerCommunicationException, NoSuchChannelException { final ResponseEvents responseEvents; final Iterator responseEventIterator; String uniqueId; @@ -394,21 +290,18 @@ public AsteriskChannel originate(OriginateAction originateAction) 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"); } @@ -416,14 +309,12 @@ public AsteriskChannel originate(OriginateAction originateAction) } public void originateToExtensionAsync(String channel, String context, String exten, int priority, long timeout, - OriginateCallback cb) throws ManagerCommunicationException - { + 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 - { + CallerId callerId, Map variables, OriginateCallback cb) throws ManagerCommunicationException { final OriginateAction originateAction; originateAction = new OriginateAction(); @@ -432,8 +323,7 @@ public void originateToExtensionAsync(String channel, String context, String ext originateAction.setExten(exten); originateAction.setPriority(priority); originateAction.setTimeout(timeout); - if (callerId != null) - { + if (callerId != null) { originateAction.setCallerId(callerId.toString()); } originateAction.setVariables(variables); @@ -442,14 +332,12 @@ public void originateToExtensionAsync(String channel, String context, String ext } public void originateToApplicationAsync(String channel, String application, String data, long timeout, - OriginateCallback cb) throws ManagerCommunicationException - { + 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 - { + Map variables, OriginateCallback cb) throws ManagerCommunicationException { final OriginateAction originateAction; originateAction = new OriginateAction(); @@ -457,8 +345,7 @@ public void originateToApplicationAsync(String channel, String application, Stri originateAction.setApplication(application); originateAction.setData(data); originateAction.setTimeout(timeout); - if (callerId != null) - { + if (callerId != null) { originateAction.setCallerId(callerId.toString()); } originateAction.setVariables(variables); @@ -466,18 +353,14 @@ public void originateToApplicationAsync(String channel, String application, Stri 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) - { + if (originateAction.getVariables() == null) { variables = new HashMap<>(); - } - else - { + } else { variables = new HashMap<>(originateAction.getVariables()); } @@ -490,14 +373,12 @@ public void originateAsync(OriginateAction originateAction, OriginateCallback cb 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); } } @@ -506,133 +387,109 @@ public void originateAsync(OriginateAction originateAction, OriginateCallback cb 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(); } @Override - public AsteriskQueue getQueueByName(String queueName) - { + public AsteriskQueue getQueueByName(String queueName) { initializeIfNeeded(); return queueManager.getQueueByName(queueName); } @Override - public List getQueuesUpdatedAfter(Date date) - { + public List getQueuesUpdatedAfter(Date date) { initializeIfNeeded(); return queueManager.getQueuesUpdatedAfter(date); } - public synchronized String getVersion() throws ManagerCommunicationException - { - final ManagerResponse response; - final String command; + 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; - } + 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.isEmpty()) - { - version = 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); @@ -642,41 +499,29 @@ public int[] getVersion(String file) throws ManagerCommunicationException fileVersion = map.get(file); versions = map; - } - else - { + } 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; } } @@ -684,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) - { + 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)) - { + 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)) - { + 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.isEmpty()) - { + 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; @@ -756,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; } @@ -770,22 +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(); 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); } } @@ -793,14 +621,12 @@ 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)) - { + if (!(response instanceof CommandResponse)) { throw new ManagerCommunicationException( "Response to CommandAction(\"" + command + "\") was not a CommandResponse but " + response, null); } @@ -808,52 +634,43 @@ public List executeCliCommand(String command) throws ManagerCommunicatio 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)) - { + if (!(response instanceof GetConfigResponse)) { throw new ManagerCommunicationException( "Response to GetConfigAction(\"" + filename + "\") was not a CommandResponse but " + response, null); } @@ -862,17 +679,13 @@ public ConfigFile getConfig(String filename) throws ManagerCommunicationExceptio final Map categoryMap = getConfigResponse.getCategories(); final Map> categories = new LinkedHashMap<>(); - for (Map.Entry categoryEntry : categoryMap.entrySet()) - { + for (Map.Entry categoryEntry : categoryMap.entrySet()) { final List lines; final Map lineMap = getConfigResponse.getLines(categoryEntry.getKey()); - if (lineMap == null) - { + if (lineMap == null) { lines = new ArrayList<>(); - } - else - { + } else { lines = new ArrayList<>(lineMap.values()); } @@ -883,141 +696,102 @@ public ConfigFile getConfig(String filename) throws ManagerCommunicationExceptio } @Override - public void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException - { + public void addAsteriskServerListener(AsteriskServerListener listener) throws ManagerCommunicationException { initializeIfNeeded(); - synchronized (listeners) - { - if (!listeners.contains(listener)) - { + try (LockCloser closer = listeners.withLock()) { + if (!listeners.contains(listener)) { listeners.add(listener); } } } @Override - public void removeAsteriskServerListener(AsteriskServerListener listener) - { - synchronized (listeners) - { + public void removeAsteriskServerListener(AsteriskServerListener listener) { + try (LockCloser closer = listeners.withLock()) { listeners.remove(listener); } } @Override - public boolean isAsteriskServerListening(AsteriskServerListener listener) - { + public boolean isAsteriskServerListening(AsteriskServerListener listener) { return listeners.contains(listener); } - public void addChainListener(ManagerEventListener chainListener) - { - synchronized (this.chainListeners) - { + 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) - { + public void removeChainListener(ManagerEventListener chainListener) { this.chainListeners.remove(chainListener); } - void fireNewAsteriskChannel(AsteriskChannel channel) - { - synchronized (listeners) - { - for (AsteriskServerListener listener : listeners) - { - try - { + 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 - { + 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); } } @@ -1029,158 +803,94 @@ OriginateCallbackData getOriginateCallbackDataByTraceId(String traceId) * 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) - { + } else if (event instanceof MonitorStartEvent) { channelManager.handleMonitorStartEvent((MonitorStartEvent) event); - } - else if (event instanceof MonitorStopEvent) - { + } 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 @@ -1191,13 +901,11 @@ else if (event instanceof AgentLogoffEvent) /** * dispatch the event to the chainListener if they exist. - * + * * @param event */ - private void fireChainListeners(ManagerEvent event) - { - synchronized (this.chainListeners) - { + private void fireChainListeners(ManagerEvent event) { + try (LockCloser closer = this.chainListeners.withLock()) { for (ManagerEventListener listener : this.chainListeners) listener.onManagerEvent(event); } @@ -1208,8 +916,7 @@ private void fireChainListeners(ManagerEvent event) * lost. */ - private void handleDisconnectEvent(DisconnectEvent disconnectEvent) - { + private void handleDisconnectEvent(DisconnectEvent disconnectEvent) { // reset version information as it might have changed while Asterisk // restarted version = null; @@ -1230,69 +937,55 @@ private void handleDisconnectEvent(DisconnectEvent disconnectEvent) * to the asterisk server is restored. */ - private void handleConnectEvent(ConnectEvent connectEvent) - { - try - { + private void handleConnectEvent(ConnectEvent connectEvent) { + try { initialize(); channelManager.initialize(); agentManager.initialize(); meetMeManager.initialize(); - if (!skipQueues) - { + if (!skipQueues) { queueManager.initialize(); } logger.info("Initializing done"); initialized = true; initializing = false; - } - catch (Exception e) - { + } 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 + // 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( @@ -1301,14 +994,12 @@ private void handleOriginateEvent(OriginateResponseEvent originateEvent) return; } - if (channel.wasInState(ChannelState.UP)) - { + if (channel.wasInState(ChannelState.UP)) { cb.onSuccess(channel); return; } - if (channel.wasBusy()) - { + if (channel.wasBusy()) { cb.onBusy(channel); return; } @@ -1317,16 +1008,14 @@ private void handleOriginateEvent(OriginateResponseEvent originateEvent) // special treatment of local channels: // the interesting things happen to the other side so we have a look // at that - if (otherChannel != null) - { + 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()) - { + if (otherChannel.wasBusy()) { cb.onBusy(channel); return; } @@ -1338,8 +1027,7 @@ 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; } @@ -1347,132 +1035,100 @@ private void handleOriginateEvent(OriginateResponseEvent originateEvent) // if nothing else matched we asume no answer cb.onNoAnswer(channel); - } - catch (Throwable t) - { + } catch (Throwable t) { logger.warn("Exception dispatching originate progress", t); } } @Override - public void shutdown() - { + public void shutdown() { if (eventConnection != null && (eventConnection.getState() == ManagerConnectionState.CONNECTED - || eventConnection.getState() == ManagerConnectionState.RECONNECTING)) - { - try - { + || eventConnection.getState() == ManagerConnectionState.RECONNECTING)) { + try { eventConnection.logoff(); - } - catch (Exception ignore) - { + } catch (Exception ignore) { } } - if (managerEventListenerProxy != null) - { - if (eventConnection != null) - { + if (managerEventListenerProxy != null) { + if (eventConnection != null) { eventConnection.removeEventListener(managerEventListenerProxy); } managerEventListenerProxy.shutdown(); } - if (eventConnection != null && eventListener != null) - { + if (eventConnection != null && eventListener != null) { eventConnection.removeEventListener(eventListener); } managerEventListenerProxy = null; eventListener = null; - if (initialized) - {// incredible, but it happened + if (initialized) {// incredible, but it happened handleDisconnectEvent(null); } // i }// shutdown - public List getPeerEntries() throws ManagerCommunicationException - { + 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) - { + 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 - { + 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); } } @@ -1481,14 +1137,12 @@ void fireNewQueueEntry(AsteriskQueueEntry entry) /* OCTAVIO LUNA */ @Override - public void forceQueuesMonitor(boolean force) - { + public void forceQueuesMonitor(boolean force) { queueManager.forceQueuesMonitor(force); } @Override - public boolean isQueuesMonitorForced() - { + 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 cc93521ba..141d0429f 100644 --- a/src/main/java/org/asteriskjava/live/internal/CallDetailRecordImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/CallDetailRecordImpl.java @@ -16,22 +16,21 @@ */ package org.asteriskjava.live.internal; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - import org.asteriskjava.live.AmaFlags; import org.asteriskjava.live.AsteriskChannel; import org.asteriskjava.live.CallDetailRecord; import org.asteriskjava.live.Disposition; import org.asteriskjava.manager.event.CdrEvent; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; + /** * 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,8 +50,7 @@ public class CallDetailRecordImpl implements CallDetailRecord private final AmaFlags amaFlags; private final String userField; - static - { + static { DISPOSITION_MAP = new HashMap<>(); DISPOSITION_MAP.put(CdrEvent.DISPOSITION_ANSWERED, Disposition.ANSWERED); DISPOSITION_MAP.put(CdrEvent.DISPOSITION_BUSY, Disposition.BUSY); @@ -67,8 +65,7 @@ public class CallDetailRecordImpl implements CallDetailRecord 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 cf97155f7..a7bf7e2f3 100644 --- a/src/main/java/org/asteriskjava/live/internal/ChannelManager.java +++ b/src/main/java/org/asteriskjava/live/internal/ChannelManager.java @@ -16,60 +16,29 @@ */ package org.asteriskjava.live.internal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.asteriskjava.live.AsteriskChannel; -import org.asteriskjava.live.CallerId; -import org.asteriskjava.live.ChannelState; -import org.asteriskjava.live.Extension; -import org.asteriskjava.live.HangupCause; -import org.asteriskjava.live.ManagerCommunicationException; -import org.asteriskjava.live.NoSuchChannelException; +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.AbstractChannelEvent; -import org.asteriskjava.manager.event.BridgeEvent; -import org.asteriskjava.manager.event.CdrEvent; -import org.asteriskjava.manager.event.DialEvent; -import org.asteriskjava.manager.event.DtmfEvent; -import org.asteriskjava.manager.event.HangupEvent; -import org.asteriskjava.manager.event.ManagerEvent; -import org.asteriskjava.manager.event.MonitorStartEvent; -import org.asteriskjava.manager.event.MonitorStopEvent; -import org.asteriskjava.manager.event.NewCallerIdEvent; -import org.asteriskjava.manager.event.NewChannelEvent; -import org.asteriskjava.manager.event.NewExtenEvent; -import org.asteriskjava.manager.event.NewStateEvent; -import org.asteriskjava.manager.event.ParkedCallEvent; -import org.asteriskjava.manager.event.ParkedCallGiveUpEvent; -import org.asteriskjava.manager.event.ParkedCallTimeOutEvent; -import org.asteriskjava.manager.event.RenameEvent; -import org.asteriskjava.manager.event.StatusEvent; -import org.asteriskjava.manager.event.UnparkedCallEvent; -import org.asteriskjava.manager.event.VarSetEvent; +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. * * @author srt * @version $Id$ */ -class ChannelManager -{ +class ChannelManager { private final Log logger = LogFactory.getLog(getClass()); /** @@ -84,7 +53,7 @@ class ChannelManager /** * A map of all active channel by their unique id. */ - final Map channels = new LinkedHashMap<>(); + final LockableMap channels = new LockableMap<>(new LinkedHashMap<>()); ScheduledThreadPoolExecutor traceScheduledExecutorService; @@ -93,74 +62,60 @@ class ChannelManager * * @param server the server this channel manager belongs to. */ - ChannelManager(AsteriskServerImpl server) - { + ChannelManager(AsteriskServerImpl server) { this.server = server; } - void initialize() throws ManagerCommunicationException - { + void initialize() throws ManagerCommunicationException { initialize(null); } - void initialize(List variables) throws ManagerCommunicationException - { + void initialize(List variables) throws ManagerCommunicationException { ResponseEvents re; 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() { + shutdown(); + logger.debug("ChannelManager has been disconnected from Asterisk."); } - void disconnected() - { - shutdown(); - logger.debug("ChannelManager has been disconnected from Asterisk."); - } - - private void shutdown() - { - if (traceScheduledExecutorService != null) - { + private void shutdown() { + if (traceScheduledExecutorService != null) { traceScheduledExecutorService.shutdown(); } - synchronized (channels) - { + try (LockCloser closer = channels.withLock()) { channels.clear(); } - - } + } /** * Returns a collection of all active AsteriskChannels. * * @return a collection of all active AsteriskChannels. */ - Collection getChannels() - { + Collection getChannels() { Collection copy; - synchronized (channels) - { + try (LockCloser closer = channels.withLock()) { copy = new ArrayList<>(channels.size() + 2); - for (AsteriskChannel channel : channels.values()) - { - if (channel.getState() != ChannelState.HUNGUP) - { + for (AsteriskChannel channel : channels.values()) { + if (channel.getState() != ChannelState.HUNGUP) { copy.add(channel); } } @@ -168,10 +123,8 @@ Collection getChannels() return copy; } - private void addChannel(AsteriskChannelImpl channel) - { - synchronized (channels) - { + private void addChannel(AsteriskChannelImpl channel) { + try (LockCloser closer = channels.withLock()) { channels.put(channel.getId(), channel); } } @@ -180,22 +133,17 @@ private void addChannel(AsteriskChannelImpl channel) * Removes channels that have been hung more than {@link #REMOVAL_THRESHOLD} * milliseconds. */ - private void removeOldChannels() - { + private void removeOldChannels() { Iterator i; - synchronized (channels) - { + try (LockCloser closer = channels.withLock()) { i = channels.values().iterator(); - while (i.hasNext()) - { + 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(); } } @@ -204,32 +152,23 @@ private void removeOldChannels() } private AsteriskChannelImpl addNewChannel(String uniqueId, final String name, Date dateOfCreation, String callerIdNumber, - String callerIdName, ChannelState state, String account) - { + 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) - { + if (SLEEP_TIME_BEFORE_GET_VAR > 0) { long start = System.currentTimeMillis(); long end = start + SLEEP_TIME_BEFORE_GET_VAR; - while (System.currentTimeMillis() < end) - { - try - { + while (System.currentTimeMillis() < end) { + try { channel.getVariable(Constants.VARIABLE_TRACE_ID); - } - catch (NoSuchChannelException | ManagerCommunicationException e) - { - try - { + } catch (NoSuchChannelException | ManagerCommunicationException e) { + try { Thread.sleep(1L); - } - catch (InterruptedException intEx) - { + } catch (InterruptedException intEx) { Thread.currentThread().interrupt(); } } @@ -242,28 +181,21 @@ private AsteriskChannelImpl addNewChannel(String uniqueId, final String name, Da addChannel(channel); // todo getChannelImplById -> LinkedHashMap, callbacks order - traceScheduledExecutorService.schedule(new Runnable() - { + traceScheduledExecutorService.schedule(new Runnable() { @Override - public void run() - { + 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"))) - { + || name.endsWith(";1"))) { final OriginateCallbackData callbackData = server.getOriginateCallbackDataByTraceId(traceId); - if (callbackData != null && callbackData.getChannel() == null) - { + if (callbackData != null && callbackData.getChannel() == null) { callbackData.setChannel(channel); - try - { + try { callbackData.getCallback().onDialing(channel); - } - catch (Throwable t) - { + } catch (Throwable t) { logger.warn("Exception dispatching originate progress. " + channel, t); } // t } // i @@ -275,73 +207,57 @@ public void run() 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 (Entry variable : variables.entrySet()) - { + 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); @@ -355,29 +271,23 @@ void handleStatusEvent(StatusEvent event) * * @param name the name of the requested channel. * @return the (most recent) channel if found, in any state, or null if none - * found. + * 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.values()) - { - if (name.equals(tmp.getName())) - { + 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)) - { + || (tmp.getDateOfCreation().equals(dateOfCreation) && tmp.getState() != ChannelState.HUNGUP)) { channel = tmp; dateOfCreation = channel.getDateOfCreation(); } @@ -394,8 +304,7 @@ AsteriskChannelImpl getChannelImplByName(String 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 @@ -406,17 +315,13 @@ AsteriskChannelImpl getChannelImplByNameAndActive(String name) AsteriskChannelImpl channel = null; - if (name == null) - { + if (name == null) { return null; } - synchronized (channels) - { - for (AsteriskChannelImpl tmp : channels.values()) - { - if (name.equals(tmp.getName()) && 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; } } @@ -424,15 +329,12 @@ AsteriskChannelImpl getChannelImplByNameAndActive(String name) return channel; } - AsteriskChannelImpl getChannelImplById(String uniqueId) - { - if (uniqueId == null) - { + AsteriskChannelImpl getChannelImplById(String uniqueId) { + if (uniqueId == null) { return null; } - synchronized (channels) - { + try (LockCloser closer = channels.withLock()) { return channels.get(uniqueId); } }// getChannelImplById @@ -446,62 +348,46 @@ AsteriskChannelImpl getChannelImplById(String uniqueId) * * @param localChannel one side * @return the other side, or null if not available or if the - * given channel is not a local channel. + * 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) != ';')) - { + || (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 - { + } 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())); @@ -509,14 +395,12 @@ void handleNewChannelEvent(NewChannelEvent event) } } - void handleNewExtenEvent(NewExtenEvent event) - { + void handleNewExtenEvent(NewExtenEvent event) { AsteriskChannelImpl channel; final Extension extension; channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { + if (channel == null) { logger.warn("handleNewExtenEvent: Ignored NewExtenEvent for unknown channel " + event.getChannel()); return; } @@ -524,27 +408,22 @@ void handleNewExtenEvent(NewExtenEvent event) 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); } } - private void idChanged(AsteriskChannelImpl channel, AbstractChannelEvent event) - { - if (channel != null) - { + 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)) - { + if (oldId != null && oldId.equals(newId)) { return; } logger.info("Changing unique_id for '" + channel.getName() + "' from " + oldId + " to " + newId + " < " + event); - synchronized (channels) - { + try (LockCloser closer = channels.withLock()) { channels.remove(oldId); channels.put(newId, channel); channel.idChanged(event.getDateReceived(), newId); @@ -552,19 +431,16 @@ private void idChanged(AsteriskChannelImpl channel, AbstractChannelEvent event) } }// idChanged - void handleNewStateEvent(NewStateEvent event) - { + void handleNewStateEvent(NewStateEvent event) { AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId()); - if (channel == null) - { + if (channel == null) { // NewStateEvent can occur for an existing channel that now has a // different unique id (originate with Local/) channel = getChannelImplByNameAndActive(event.getChannel()); idChanged(channel, event); - if (channel == null) - { + if (channel == null) { logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId()); // NewStateEvent can occur instead of a NewChannelEvent @@ -578,25 +454,21 @@ void handleNewStateEvent(NewStateEvent event) // 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) - { + 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(); } @@ -608,39 +480,32 @@ void handleNewStateEvent(NewStateEvent event) // 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())) - { + if (event.getChannel() != null && !event.getChannel().equals(channel.getName())) { logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'"); - synchronized (channel) - { + 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) - { + if (channel == null) { // NewCallerIdEvent can occur for an existing channel that now has a // different unique id (originate with Local/) channel = getChannelImplByNameAndActive(event.getChannel()); 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, @@ -648,30 +513,25 @@ void handleNewCallerIdEvent(NewCallerIdEvent event) } } - 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) - { + 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()); } @@ -679,27 +539,21 @@ 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) - { + if (sourceChannel == null) { logger.warn("handleDialEvent: Ignored DialEvent for unknown source channel " + event.getChannel() + " with unique id " + event.getUniqueId()); return; } - if (destinationChannel == null) - { - if (DialEvent.SUBEVENT_END.equalsIgnoreCase(event.getSubEvent())) - { + 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 - { + } else { logger.warn("handleDialEvent: Ignored DialEvent for unknown dst channel " + event.getDestination() + " with unique_id " + event.getDestUniqueId()); } @@ -709,109 +563,88 @@ void handleDialEvent(DialEvent event) 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) - { + if (channel1 == null) { logger.warn("handleBridgeEvent: Ignored BridgeEvent for unknown channel " + event.getChannel1()); return; } - if (channel2 == null) - { + 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) - { + 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) - { + 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 " + @@ -819,217 +652,181 @@ private String getTraceId(AsteriskChannel channel) return traceId; } - void handleParkedCallEvent(ParkedCallEvent event) - { + 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) - { + if (channel == null) { logger.info("Ignored ParkedCallEvent for unknown channel " + event.getParkeeChannel()); return; } - synchronized (channel) - { - Extension ext = new Extension(null, (event.getParkingSpace() != null) ? event.getParkingSpace() : event.getExten(), 1); + 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) - { + void handleParkedCallGiveUpEvent(ParkedCallGiveUpEvent event) { // Only bristuffed versions: AsteriskChannelImpl channel = // getChannelImplById(event.getUniqueId()); AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getParkeeChannel()); - if (channel == null) - { + 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) - { + try (LockCloser closer = channel.withLock()) { channel.setParkedAt(null, null); } logger.info("Channel " + channel.getName() + " is unparked (GiveUp) from " + wasParkedAt.getExtension()); } - void handleParkedCallTimeOutEvent(ParkedCallTimeOutEvent event) - { + void handleParkedCallTimeOutEvent(ParkedCallTimeOutEvent event) { // Only bristuffed versions: AsteriskChannelImpl channel = // getChannelImplById(event.getUniqueId()); final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getParkeeChannel()); - if (channel == null) - { + 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) - { + try (LockCloser closer = channel.withLock()) { channel.setParkedAt(null, null); } logger.info("Channel " + channel.getName() + " is unparked (Timeout) from " + wasParkedAt.getExtension()); } - void handleUnparkedCallEvent(UnparkedCallEvent event) - { + void handleUnparkedCallEvent(UnparkedCallEvent event) { // Only bristuffed versions: AsteriskChannelImpl channel = // getChannelImplById(event.getUniqueId()); final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getParkeeChannel()); - if (channel == null) - { + 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) - { + 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) - { + void handleMonitorStartEvent(MonitorStartEvent event) { final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getChannel()); - if (channel == null) - { + if (channel == null) { logger.info("Ignored MonitorStartEvent for unknown channel " + event.getChannel()); return; } boolean isMonitored = channel.isMonitored(); - if (isMonitored) - { + if (isMonitored) { logger.info("Ignored MonitorStartEvent as the channel was already monitored"); return; } - synchronized (channel) - { + try (LockCloser closer = channel.withLock()) { channel.setMonitored(true); } logger.info("Channel " + channel.getName() + " is monitored"); } - void handleMonitorStopEvent(MonitorStopEvent event) - { + void handleMonitorStopEvent(MonitorStopEvent event) { final AsteriskChannelImpl channel = getChannelImplByNameAndActive(event.getChannel()); - if (channel == null) - { + if (channel == null) { logger.info("Ignored MonitorStopEvent for unknown channel " + event.getChannel()); return; } boolean isMonitored = channel.isMonitored(); - if (!isMonitored) - { + if (!isMonitored) { logger.info("Ignored MonitorStopEvent as the channel was not monitored"); return; } - synchronized (channel) - { + 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 20239ad82..105bc6f22 100644 --- a/src/main/java/org/asteriskjava/live/internal/ConfigFileImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/ConfigFileImpl.java @@ -16,11 +16,11 @@ */ package org.asteriskjava.live.internal; +import org.asteriskjava.config.ConfigFile; + import java.util.List; import java.util.Map; -import org.asteriskjava.config.ConfigFile; - /** * 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/MeetMeManager.java b/src/main/java/org/asteriskjava/live/internal/MeetMeManager.java index ffe49497f..42f2230cc 100644 --- a/src/main/java/org/asteriskjava/live/internal/MeetMeManager.java +++ b/src/main/java/org/asteriskjava/live/internal/MeetMeManager.java @@ -16,16 +16,10 @@ */ package org.asteriskjava.live.internal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - 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; @@ -38,13 +32,19 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; +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; + /** * Manages MeetMe events on behalf of an AsteriskServer. * * @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+).*$"); @@ -55,44 +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()) - { + try (LockCloser closer = rooms.withLock()) { + for (MeetMeRoom room : rooms.values()) { + if (!room.isEmpty()) { result.add(room); } } @@ -100,8 +91,7 @@ Collection getMeetMeRooms() return result; } - void handleMeetMeEvent(AbstractMeetMeEvent event) - { + void handleMeetMeEvent(AbstractMeetMeEvent event) { String roomNumber; Integer userNumber; AsteriskChannelImpl channel; @@ -109,41 +99,33 @@ 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.getUser(); - if (userNumber == null) - { + 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"); } @@ -153,71 +135,56 @@ void handleMeetMeEvent(AbstractMeetMeEvent event) 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 + // 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; @@ -227,47 +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 + // 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 @@ -277,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 && roomUser != 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); } @@ -300,24 +254,20 @@ else if (channelUser == null && roomUser != null) Collection users = room.getUserImpls(); Collection usersToRemove = new ArrayList<>(); - for (MeetMeUserImpl user : users) - { - if (!userNumbers.contains(user.getUserNumber())) - { + 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; @@ -327,33 +277,28 @@ private MeetMeUserImpl getOrCreateUserImpl(AbstractMeetMeEvent event) roomNumber = event.getMeetMe(); room = getOrCreateRoomImpl(roomNumber); user = room.getUser(event.getUser()); - if (user != null) - { + 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); @@ -375,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); @@ -392,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 026d155d7..59da00312 100644 --- a/src/main/java/org/asteriskjava/live/internal/MeetMeRoomImpl.java +++ b/src/main/java/org/asteriskjava/live/internal/MeetMeRoomImpl.java @@ -16,106 +16,89 @@ */ 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) - { + 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 - { + private void sendMeetMeCommand(String command) throws ManagerCommunicationException { final StringBuilder sb = new StringBuilder(); sb.append(COMMAND_PREFIX); sb.append(" "); @@ -127,15 +110,13 @@ private void sendMeetMeCommand(String command) throws ManagerCommunicationExcept } @Override - public String toString() - { - StringBuilder sb; + public String toString() { + StringBuilder sb; int systemHashcode; 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 9b2b5f501..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,23 +112,19 @@ 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 - { + private void sendMeetMeUserCommand(String command) throws ManagerCommunicationException { StringBuilder sb = new StringBuilder(); sb.append(COMMAND_PREFIX); sb.append(" "); @@ -152,17 +136,15 @@ private void sendMeetMeUserCommand(String command) throws ManagerCommunicationEx server.sendAction(new CommandAction(sb.toString())); } - + @Override - public String toString() - { - StringBuilder sb; + public String toString() { + StringBuilder sb; int systemHashcode; 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 ce41982bc..2194fd78c 100644 --- a/src/main/java/org/asteriskjava/live/internal/QueueManager.java +++ b/src/main/java/org/asteriskjava/live/internal/QueueManager.java @@ -16,43 +16,28 @@ */ package org.asteriskjava.live.internal; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Map.Entry; - 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; -import org.asteriskjava.manager.event.JoinEvent; -import org.asteriskjava.manager.event.LeaveEvent; -import org.asteriskjava.manager.event.ManagerEvent; -import org.asteriskjava.manager.event.QueueEntryEvent; -import org.asteriskjava.manager.event.QueueMemberAddedEvent; -import org.asteriskjava.manager.event.QueueMemberEvent; -import org.asteriskjava.manager.event.QueueMemberPausedEvent; -import org.asteriskjava.manager.event.QueueMemberPenaltyEvent; -import org.asteriskjava.manager.event.QueueMemberRemovedEvent; -import org.asteriskjava.manager.event.QueueMemberStatusEvent; -import org.asteriskjava.manager.event.QueueParamsEvent; +import org.asteriskjava.manager.event.*; 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; @@ -65,50 +50,36 @@ class QueueManager * A map of ACD queues by there name. 101119 OLB: Modified to act as a LRU * Cache to optimize updates */ - private final Map queuesLRU = new LinkedHashMap<>(); + private final LockableMap queuesLRU = new LockableMap<>(new LinkedHashMap<>()); - QueueManager(AsteriskServerImpl server, ChannelManager channelManager) - { + QueueManager(AsteriskServerImpl server, ChannelManager channelManager) { this.server = server; this.channelManager = channelManager; } - 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) - { + } else if (event instanceof QueueEntryEvent) { handleQueueEntryEvent((QueueEntryEvent) event); } } @@ -117,63 +88,46 @@ else if (event instanceof QueueEntryEvent) /** * Method to ask for a Queue data update - * - * @author Octavio Luna + * * @param queue * @throws ManagerCommunicationException + * @author Octavio Luna */ - void updateQueue(String queue) throws ManagerCommunicationException - { + void updateQueue(String queue) throws ManagerCommunicationException { ResponseEvents re; - try - { + try { QueueStatusAction queueStatusAction = new QueueStatusAction(); queueStatusAction.setQueue(queue); re = server.sendEventGeneratingAction(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()) - { + for (ManagerEvent event : re.getEvents()) { // 101119 OLB: solo actualizamos el QUEUE por ahora - if (event instanceof QueueParamsEvent) - { + 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) - { + } else if (event instanceof QueueEntryEvent) { handleQueueEntryEvent((QueueEntryEvent) event); } } } - void disconnected() - { - synchronized (queuesLRU) - { - for (AsteriskQueueImpl queue : queuesLRU.values()) - { + void disconnected() { + try (LockCloser closer = queuesLRU.withLock()) { + for (AsteriskQueueImpl queue : queuesLRU.values()) { queue.cancelServiceLevelTimer(); } queuesLRU.clear(); @@ -182,39 +136,33 @@ void disconnected() /** * Gets (a copy of) the list of the queues. - * + * * @return a copy of the list of the queues. */ - Collection getQueues() - { + Collection getQueues() { refreshQueuesIfForced(); Collection copy; - synchronized (queuesLRU) - { + try (LockCloser closer = queuesLRU.withLock()) { copy = new ArrayList(queuesLRU.values()); } return copy; } - public List getQueuesUpdatedAfter(Date date) - { + public List getQueuesUpdatedAfter(Date date) { refreshQueuesIfForced(); List copy = new ArrayList<>(); - synchronized (queuesLRU) - { + try (LockCloser closer = queuesLRU.withLock()) { List> list = new ArrayList<>(queuesLRU.entrySet()); ListIterator> iter = list.listIterator(list.size()); Entry entry; - while (iter.hasPrevious()) - { + while (iter.hasPrevious()) { entry = iter.previous(); AsteriskQueueImpl astQueue = entry.getValue(); - if (astQueue.getLastUpdateMillis() <= date.getTime()) - { + if (astQueue.getLastUpdateMillis() <= date.getTime()) { break; } copy.add(astQueue); @@ -227,24 +175,21 @@ public List getQueuesUpdatedAfter(Date date) /** * Adds a queue to the internal map, keyed by name. - * + * * @param queue the AsteriskQueueImpl to be added */ - private void addQueue(AsteriskQueueImpl queue) - { - synchronized (queuesLRU) - { + private void addQueue(AsteriskQueueImpl queue) { + try (LockCloser closer = queuesLRU.withLock()) { queuesLRU.put(queue.getName(), queue); } } /** * Called during initialization to populate the list of queues. - * + * * @param event the event received */ - private void handleQueueParamsEvent(QueueParamsEvent event) - { + private void handleQueueParamsEvent(QueueParamsEvent event) { AsteriskQueueImpl queue; final String name = event.getQueue(); @@ -261,28 +206,22 @@ private void handleQueueParamsEvent(QueueParamsEvent event) queue = getInternalQueueByName(name); - if (queue == null) - { + 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 - { + } 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) - { - synchronized (queuesLRU) - { + 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)) - { + | queue.setServiceLevelPerf(serviceLevelPerf)) { queuesLRU.remove(queue.getName()); queuesLRU.put(queue.getName(), queue); @@ -294,40 +233,33 @@ private void handleQueueParamsEvent(QueueParamsEvent event) /** * Called during initialization to populate the members of the queues. - * + * * @param event the QueueMemberEvent received */ - private void handleQueueMemberEvent(QueueMemberEvent event) - { + private void handleQueueMemberEvent(QueueMemberEvent event) { final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); - if (queue == null) - { + if (queue == null) { logger.error("Ignored QueueEntryEvent for unknown queue " + event.getQueue()); return; } AsteriskQueueMemberImpl member = queue.getMember(event.getInterface()); - if (member == null) - { + 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 - { + } else { manageQueueMemberChange(queue, member, event); } } - private void manageQueueMemberChange(AsteriskQueueImpl queue, AsteriskQueueMemberImpl member, QueueMemberEvent 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())) - { + | member.lastCallChanged(event.getLastCall())) { queue.stampLastUpdate(); } } @@ -335,29 +267,48 @@ private void manageQueueMemberChange(AsteriskQueueImpl queue, AsteriskQueueMembe /** * 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) - { + private void handleQueueEntryEvent(QueueEntryEvent event) { final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); final AsteriskChannelImpl channel = channelManager.getChannelImplByName(event.getChannel()); - if (queue == null) - { + 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.debug("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; } @@ -375,32 +326,22 @@ private void handleQueueEntryEvent(QueueEntryEvent event) /** * Called from AsteriskServerImpl whenever a new entry appears in a queue. - * + * * @param event the JoinEvent received */ - void handleJoinEvent(JoinEvent event) - { + 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 @@ -415,28 +356,52 @@ void handleJoinEvent(JoinEvent event) /** * Called from AsteriskServerImpl whenever an enty leaves a queue. - * + * + * @param event - the LeaveEvent received + */ + void handleLeaveEvent(QueueCallerLeaveEvent 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()); + } + + /** + * Called from AsteriskServerImpl whenever an enty leaves a queue. + * * @param event - the LeaveEvent received */ - void handleLeaveEvent(LeaveEvent event) - { + void handleLeaveEvent(LeaveEvent 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) - { + if (existingQueueEntry == null) { logger.error("Ignored leave event for non existing queue entry in queue " + event.getQueue() + " for channel " + event.getChannel()); return; @@ -448,22 +413,19 @@ void handleLeaveEvent(LeaveEvent event) /** * Challange a QueueMemberStatusEvent. Called from AsteriskServerImpl * whenever a member state changes. - * + * * @param event that was triggered by Asterisk server. */ - void handleQueueMemberStatusEvent(QueueMemberStatusEvent event) - { + 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.getInterface()); - if (member == null) - { + if (member == null) { logger.error("Ignored QueueMemberStatusEvent for unknown member " + event.getInterface()); return; } @@ -472,19 +434,16 @@ void handleQueueMemberStatusEvent(QueueMemberStatusEvent event) queue.fireMemberStateChanged(member); } - void handleQueueMemberPausedEvent(QueueMemberPausedEvent event) - { + void handleQueueMemberPausedEvent(QueueMemberPausedEvent event) { 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.getInterface()); - if (member == null) - { + if (member == null) { logger.error("Ignored QueueMemberPausedEvent for unknown member " + event.getInterface()); return; } @@ -492,19 +451,16 @@ void handleQueueMemberPausedEvent(QueueMemberPausedEvent event) member.pausedChanged(event.getPaused()); } - void handleQueueMemberPenaltyEvent(QueueMemberPenaltyEvent event) - { + void handleQueueMemberPenaltyEvent(QueueMemberPenaltyEvent 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) - { + if (member == null) { logger.error("Ignored QueueMemberStatusEvent for unknown member " + event.getLocation()); return; } @@ -514,47 +470,39 @@ 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. + * with the given name. */ - AsteriskQueueImpl getQueueByName(String queueName) - { + AsteriskQueueImpl getQueueByName(String queueName) { refreshQueueIfForced(queueName); AsteriskQueueImpl queue = getInternalQueueByName(queueName); - if (queue == null) - { + if (queue == null) { logger.error("Requested queue '" + queueName + "' not found!"); } return queue; } - private AsteriskQueueImpl getInternalQueueByName(String queueName) - { + private AsteriskQueueImpl getInternalQueueByName(String queueName) { AsteriskQueueImpl queue; - synchronized (queuesLRU) - { + try (LockCloser closer = queuesLRU.withLock()) { queue = queuesLRU.get(queueName); } return queue; } - private void refreshQueueIfForced(String queueName) - { - if (queuesMonitorForced) - { + private void refreshQueueIfForced(String queueName) { + if (queuesMonitorForced) { updateQueue(queueName); } } - private void refreshQueuesIfForced() - { - if (queuesMonitorForced && (System.currentTimeMillis() - queueMonitorLastTimeReloaded) > queuesMonitorLeaseTime) - { + private void refreshQueuesIfForced() { + if (queuesMonitorForced && (System.currentTimeMillis() - queueMonitorLastTimeReloaded) > queuesMonitorLeaseTime) { initialize(); queueMonitorLastTimeReloaded = System.currentTimeMillis(); } @@ -562,21 +510,18 @@ private void refreshQueuesIfForced() /** * Challange a QueueMemberAddedEvent. - * + * * @param event - the generated QueueMemberAddedEvent. */ - public void handleQueueMemberAddedEvent(QueueMemberAddedEvent event) - { + public void handleQueueMemberAddedEvent(QueueMemberAddedEvent event) { final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); - if (queue == null) - { + if (queue == null) { logger.error("Ignored QueueMemberAddedEvent for unknown queue " + event.getQueue()); return; } AsteriskQueueMemberImpl member = queue.getMember(event.getInterface()); - if (member == null) - { + if (member == null) { member = new AsteriskQueueMemberImpl(server, queue, event.getInterface(), QueueMemberState.valueOf(event.getStatus()), event.getPaused(), event.getPenalty(), event.getMembership(), event.getCallsTaken(), event.getLastCall()); @@ -587,21 +532,18 @@ public void handleQueueMemberAddedEvent(QueueMemberAddedEvent event) /** * Challange a QueueMemberRemovedEvent. - * + * * @param event - the generated QueueMemberRemovedEvent. */ - public void handleQueueMemberRemovedEvent(QueueMemberRemovedEvent event) - { + public void handleQueueMemberRemovedEvent(QueueMemberRemovedEvent event) { final AsteriskQueueImpl queue = getInternalQueueByName(event.getQueue()); - if (queue == null) - { + if (queue == null) { logger.error("Ignored QueueMemberRemovedEvent for unknown queue " + event.getQueue()); return; } final AsteriskQueueMemberImpl member = queue.getMember(event.getInterface()); - if (member == null) - { + if (member == null) { logger.error("Ignored QueueMemberRemovedEvent for unknown agent name: " + event.getMemberName() + " location: " + event.getInterface() + " queue: " + event.getQueue()); return; @@ -610,13 +552,11 @@ public void handleQueueMemberRemovedEvent(QueueMemberRemovedEvent event) queue.removeMember(member); } - public void forceQueuesMonitor(boolean force) - { + public void forceQueuesMonitor(boolean force) { queuesMonitorForced = force; } - public boolean isQueuesMonitorForced() - { + 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/.gitignore b/src/main/java/org/asteriskjava/manager/.gitignore deleted file mode 100644 index 3ffd5d977..000000000 --- a/src/main/java/org/asteriskjava/manager/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -/AbstractManagerEventListener.class -/AsteriskMapping.class -/AuthenticationFailedException.class -/DefaultManagerConnection.class -/EventTimeoutException.class -/ExpectedResponse.class -/ManagerConnection.class -/ManagerConnectionFactory.class -/ManagerConnectionState.class -/ManagerEventListener.class -/ManagerEventListenerProxy$1.class -/ManagerEventListenerProxy.class -/PingThread.class -/ResponseEvents.class -/SendActionCallback.class -/TimeoutException.class -/NetAddress.class diff --git a/src/main/java/org/asteriskjava/manager/AbstractManagerEventListener.java b/src/main/java/org/asteriskjava/manager/AbstractManagerEventListener.java index 3e5bcb677..51930ad72 100644 --- a/src/main/java/org/asteriskjava/manager/AbstractManagerEventListener.java +++ b/src/main/java/org/asteriskjava/manager/AbstractManagerEventListener.java @@ -64,550 +64,598 @@ */ public abstract class AbstractManagerEventListener implements ManagerEventListener { - private static final Log LOGGER = LogFactory.getLog(AbstractManagerEventListener.class); + private static final Log LOGGER = LogFactory.getLog(AbstractManagerEventListener.class); - public void handleEvent(AgentCompleteEvent event) { - } + public void handleEvent(AgentCompleteEvent event) { + } - public void handleEvent(AgentConnectEvent event) { - } + public void handleEvent(AgentConnectEvent event) { + } - public void handleEvent(AgentDumpEvent event) { - } + public void handleEvent(AgentDumpEvent event) { + } - public void handleEvent(AgentRingNoAnswerEvent event) { - } + public void handleEvent(AgentRingNoAnswerEvent event) { + } - public void handleEvent(AttendedTransferEvent event) { - } + public void handleEvent(AttendedTransferEvent event) { + } - public void handleEvent(BlindTransferEvent event) { - } + public void handleEvent(BlindTransferEvent event) { + } - public void handleEvent(BridgeCreateEvent event) { - } + public void handleEvent(BridgeCreateEvent event) { + } - public void handleEvent(BridgeDestroyEvent event) { - } + public void handleEvent(BridgeDestroyEvent event) { + } - public void handleEvent(BridgeEnterEvent event) { - } + public void handleEvent(BridgeEnterEvent event) { + } - public void handleEvent(BridgeLeaveEvent event) { - } + public void handleEvent(BridgeLeaveEvent event) { + } - public void handleEvent(HangupEvent event) { - } + public void handleEvent(HangupEvent event) { + } - public void handleEvent(NewChannelEvent event) { - } + public void handleEvent(NewChannelEvent event) { + } - public void handleEvent(NewStateEvent event) { - } + public void handleEvent(NewStateEvent event) { + } - public void handleEvent(ConfbridgeEndEvent event) { - } + public void handleEvent(ConfbridgeEndEvent event) { + } - public void handleEvent(ConfbridgeJoinEvent event) { - } + public void handleEvent(ConfbridgeJoinEvent event) { + } - public void handleEvent(ConfbridgeLeaveEvent event) { - } + public void handleEvent(ConfbridgeLeaveEvent event) { + } - public void handleEvent(ConfbridgeStartEvent event) { - } + public void handleEvent(ConfbridgeStartEvent event) { + } - public void handleEvent(ConfbridgeTalkingEvent event) { - } + public void handleEvent(ConfbridgeTalkingEvent event) { + } - public void handleEvent(AntennaLevelEvent event) { - } + public void handleEvent(AntennaLevelEvent event) { + } - public void handleEvent(HangupRequestEvent event) { - } + public void handleEvent(HangupRequestEvent event) { + } - public void handleEvent(NewCallerIdEvent event) { - } + public void handleEvent(NewCallerIdEvent event) { + } - public void handleEvent(SoftHangupRequestEvent event) { - } + public void handleEvent(SoftHangupRequestEvent event) { + } - public void handleEvent(FaxDocumentStatusEvent event) { - } + public void handleEvent(FaxDocumentStatusEvent event) { + } - public void handleEvent(FaxReceivedEvent event) { - } + public void handleEvent(FaxReceivedEvent event) { + } - public void handleEvent(FaxStatusEvent event) { - } + public void handleEvent(FaxStatusEvent event) { + } - public void handleEvent(SendFaxEvent event) { - } + public void handleEvent(SendFaxEvent event) { + } - public void handleEvent(SendFaxStatusEvent event) { - } + public void handleEvent(SendFaxStatusEvent event) { + } - public void handleEvent(T38FaxStatusEvent event) { - } + public void handleEvent(T38FaxStatusEvent event) { + } - public void handleEvent(HoldEvent event) { - } + public void handleEvent(HoldEvent event) { + } - public void handleEvent(UnholdEvent event) { - } + public void handleEvent(UnholdEvent event) { + } - public void handleEvent(MeetMeJoinEvent event) { - } + public void handleEvent(MeetMeJoinEvent event) { + } - public void handleEvent(MeetMeLeaveEvent event) { - } + public void handleEvent(MeetMeLeaveEvent event) { + } - public void handleEvent(MeetMeMuteEvent event) { - } + public void handleEvent(MeetMeMuteEvent event) { + } - public void handleEvent(MeetMeTalkingEvent event) { - } + public void handleEvent(MeetMeTalkingEvent event) { + } - public void handleEvent(MeetMeTalkingRequestEvent event) { - } + public void handleEvent(MeetMeTalkingRequestEvent event) { + } - public void handleEvent(MonitorStartEvent event) { - } + public void handleEvent(MonitorStartEvent event) { + } - public void handleEvent(MonitorStopEvent event) { - } + public void handleEvent(MonitorStopEvent event) { + } - public void handleEvent(ParkedCallEvent event) { - } + public void handleEvent(ParkedCallEvent event) { + } - public void handleEvent(QueueMemberAddedEvent event) { - } + public void handleEvent(QueueMemberAddedEvent event) { + } - public void handleEvent(QueueMemberPausedEvent event) { - } + public void handleEvent(QueueMemberPausedEvent event) { + } - public void handleEvent(QueueMemberRemovedEvent event) { - } + public void handleEvent(QueueMemberRemovedEvent event) { + } - public void handleEvent(RtcpReceivedEvent event) { - } + public void handleEvent(QueueMemberRingInUseEvent event) { + } - public void handleEvent(RtcpSentEvent event) { - } + public void handleEvent(RtcpReceivedEvent event) { + } - public void handleEvent(RtpReceiverStatEvent event) { - } + public void handleEvent(RtcpSentEvent event) { + } - public void handleEvent(RtpSenderStatEvent event) { - } + public void handleEvent(RtpReceiverStatEvent event) { + } - public void handleEvent(AgentCallbackLoginEvent event) { - } + public void handleEvent(RtpSenderStatEvent event) { + } - public void handleEvent(AgentCallbackLogoffEvent event) { - } + public void handleEvent(AgentCallbackLoginEvent event) { + } - public void handleEvent(AgentCalledEvent event) { - } + public void handleEvent(AgentCallbackLogoffEvent event) { + } - public void handleEvent(AgentLoginEvent event) { - } + public void handleEvent(AgentCalledEvent event) { + } - public void handleEvent(AgentLogoffEvent event) { - } + public void handleEvent(AgentLoginEvent event) { + } - public void handleEvent(AgiExecEvent event) { - } + public void handleEvent(AgentLogoffEvent event) { + } - public void handleEvent(AgiExecEndEvent event) { - } + public void handleEvent(AgiExecEvent event) { + } - public void handleEvent(AgiExecStartEvent event) { - } + public void handleEvent(AgiExecEndEvent event) { + } - public void handleEvent(AlarmClearEvent event) { - } + public void handleEvent(AgiExecStartEvent event) { + } - public void handleEvent(AlarmEvent event) { - } + public void handleEvent(AlarmClearEvent event) { + } - public void handleEvent(BridgeEvent event) { - } + public void handleEvent(AlarmEvent event) { + } - public void handleEvent(LinkEvent event) { - } + public void handleEvent(BridgeEvent event) { + } - public void handleEvent(UnlinkEvent event) { - } + @SuppressWarnings("deprecation") + public void handleEvent(LinkEvent event) { + } - public void handleEvent(BridgeExecEvent event) { - } + @SuppressWarnings("deprecation") + public void handleEvent(UnlinkEvent event) { + } - public void handleEvent(BridgeMergeEvent event) { - } + public void handleEvent(BridgeExecEvent event) { + } - public void handleEvent(CdrEvent event) { - } + public void handleEvent(BridgeMergeEvent event) { + } - public void handleEvent(CelEvent event) { - } + public void handleEvent(CdrEvent event) { + } - public void handleEvent(ChallengeResponseFailedEvent event) { - } + public void handleEvent(CelEvent event) { + } - public void handleEvent(ChallengeSentEvent event) { - } + public void handleEvent(ChallengeResponseFailedEvent event) { + } - public void handleEvent(ChannelReloadEvent event) { - } + public void handleEvent(ChallengeSentEvent event) { + } - public void handleEvent(ChannelUpdateEvent event) { - } + public void handleEvent(ChannelReloadEvent event) { + } - public void handleEvent(ChanSpyStartEvent event) { - } + public void handleEvent(ChannelUpdateEvent event) { + } - public void handleEvent(ChanSpyStopEvent event) { - } + public void handleEvent(ChanSpyStartEvent event) { + } - public void handleEvent(ConnectEvent event) { - } + public void handleEvent(ChanSpyStopEvent event) { + } - public void handleEvent(ContactStatusEvent event) { - } + public void handleEvent(ConnectEvent event) { + } - public void handleEvent(DAHDIChannelEvent event) { - } + public void handleEvent(ContactStatusEvent event) { + } - public void handleEvent(DeviceStateChangeEvent event) { - } + public void handleEvent(DAHDIChannelEvent event) { + } - public void handleEvent(DialEvent event) { - } + public void handleEvent(DeviceStateChangeEvent event) { + } - public void handleEvent(DialBeginEvent event) { - } + public void handleEvent(DialEvent event) { + } - public void handleEvent(DialEndEvent event) { - } + public void handleEvent(DialBeginEvent event) { + } - public void handleEvent(DialStateEvent event) { - } + public void handleEvent(DialEndEvent event) { + } - public void handleEvent(DisconnectEvent event) { - } + public void handleEvent(DialStateEvent event) { + } - public void handleEvent(DndStateEvent event) { - } + public void handleEvent(DisconnectEvent event) { + } - public void handleEvent(DongleCallStateChangeEvent event) { - } + public void handleEvent(DndStateEvent event) { + } - public void handleEvent(DongleCENDEvent event) { - } + public void handleEvent(DongleCallStateChangeEvent event) { + } - public void handleEvent(DongleNewCMGREvent event) { - } + public void handleEvent(DongleCENDEvent event) { + } - public void handleEvent(DongleNewSMSBase64Event event) { - } + public void handleEvent(DongleNewCMGREvent event) { + } - public void handleEvent(DongleNewSMSEvent event) { - } + public void handleEvent(DongleNewSMSBase64Event event) { + } - public void handleEvent(DongleStatusEvent event) { - } + public void handleEvent(DongleNewSMSEvent event) { + } - public void handleEvent(DtmfEvent event) { - } + public void handleEvent(DongleStatusEvent event) { + } - public void handleEvent(DtmfBeginEvent event) { - } + public void handleEvent(DtmfEvent event) { + } - public void handleEvent(DtmfEndEvent event) { - } + public void handleEvent(DtmfBeginEvent event) { + } - public void handleEvent(ExtensionStatusEvent event) { - } + public void handleEvent(DtmfEndEvent event) { + } - public void handleEvent(FullyBootedEvent event) { - } + public void handleEvent(ExtensionStatusEvent event) { + } - public void handleEvent(HoldedCallEvent event) { - } + public void handleEvent(FullyBootedEvent event) { + } - public void handleEvent(InvalidPasswordEvent event) { - } + public void handleEvent(HoldedCallEvent event) { + } - public void handleEvent(JabberEventEvent event) { - } + public void handleEvent(InvalidPasswordEvent event) { + } - public void handleEvent(JitterBufStatsEvent event) { - } + public void handleEvent(JabberEventEvent event) { + } - public void handleEvent(LocalBridgeEvent event) { - } + public void handleEvent(JitterBufStatsEvent event) { + } - public void handleEvent(LocalOptimizationBeginEvent event) { - } + public void handleEvent(LocalBridgeEvent event) { + } - public void handleEvent(LocalOptimizationEndEvent event) { - } + public void handleEvent(LocalOptimizationBeginEvent event) { + } - public void handleEvent(LogChannelEvent event) { - } + public void handleEvent(LocalOptimizationEndEvent event) { + } - public void handleEvent(MasqueradeEvent event) { - } + public void handleEvent(LogChannelEvent event) { + } - public void handleEvent(MeetMeEndEvent event) { - } + public void handleEvent(MasqueradeEvent event) { + } - public void handleEvent(MessageWaitingEvent event) { - } + public void handleEvent(MeetMeEndEvent event) { + } - public void handleEvent(ModuleLoadReportEvent event) { - } + public void handleEvent(MessageWaitingEvent event) { + } - public void handleEvent(MusicOnHoldEvent event) { - } + public void handleEvent(ModuleLoadReportEvent event) { + } - public void handleEvent(MusicOnHoldStartEvent event) { - } + public void handleEvent(MusicOnHoldEvent event) { + } - public void handleEvent(MusicOnHoldStopEvent event) { - } + public void handleEvent(MusicOnHoldStartEvent event) { + } - public void handleEvent(NewAccountCodeEvent event) { - } + public void handleEvent(MusicOnHoldStopEvent event) { + } - public void handleEvent(NewConnectedLineEvent event) { - } + public void handleEvent(NewAccountCodeEvent event) { + } - public void handleEvent(NewExtenEvent event) { - } + public void handleEvent(NewConnectedLineEvent event) { + } - public void handleEvent(PeerStatusEvent event) { - } + public void handleEvent(NewExtenEvent event) { + } - public void handleEvent(PickupEvent event) { - } + public void handleEvent(PeerStatusEvent event) { + } - public void handleEvent(PriEventEvent event) { - } + public void handleEvent(PickupEvent event) { + } - public void handleEvent(ProtocolIdentifierReceivedEvent event) { - } + public void handleEvent(PriEventEvent event) { + } - public void handleEvent(QueueEvent event) { - } + public void handleEvent(ProtocolIdentifierReceivedEvent event) { + } - public void handleEvent(JoinEvent event) { - } + public void handleEvent(QueueEvent event) { + } - public void handleEvent(LeaveEvent event) { - } + public void handleEvent(JoinEvent event) { + } - public void handleEvent(QueueCallerAbandonEvent event) { - } + public void handleEvent(LeaveEvent event) { + } - public void handleEvent(QueueCallerJoinEvent event) { - } + public void handleEvent(QueueCallerAbandonEvent event) { + } - public void handleEvent(QueueCallerLeaveEvent event) { - } + public void handleEvent(QueueCallerJoinEvent event) { + } - public void handleEvent(QueueMemberPenaltyEvent event) { - } + public void handleEvent(QueueCallerLeaveEvent event) { + } - public void handleEvent(ReceiveFaxEvent event) { - } + public void handleEvent(QueueMemberPenaltyEvent event) { + } - public void handleEvent(RegistryEvent event) { - } + public void handleEvent(ReceiveFaxEvent event) { + } - public void handleEvent(ReloadEvent event) { - } + public void handleEvent(RegistryEvent event) { + } - public void handleEvent(RenameEvent event) { - } + public void handleEvent(ReloadEvent event) { + } - public void handleEvent(ResponseEvent event) { - } + public void handleEvent(RenameEvent event) { + } - public void handleEvent(AgentsCompleteEvent event) { - } + public void handleEvent(ResponseEvent event) { + } - public void handleEvent(AgentsEvent event) { - } + public void handleEvent(AgentsCompleteEvent event) { + } - public void handleEvent(AsyncAgiEvent event) { - } + public void handleEvent(AgentsEvent event) { + } - public void handleEvent(ConfbridgeListCompleteEvent event) { - } + public void handleEvent(AsyncAgiEvent event) { + } - public void handleEvent(ConfbridgeListEvent event) { - } + public void handleEvent(ConfbridgeListCompleteEvent event) { + } - public void handleEvent(ConfbridgeListRoomsCompleteEvent event) { - } + public void handleEvent(ConfbridgeListEvent event) { + } - public void handleEvent(ConfbridgeListRoomsEvent event) { - } + public void handleEvent(ConfbridgeListRoomsCompleteEvent event) { + } - public void handleEvent(CoreShowChannelEvent event) { - } + public void handleEvent(ConfbridgeListRoomsEvent event) { + } - public void handleEvent(CoreShowChannelsCompleteEvent event) { - } + public void handleEvent(CoreShowChannelEvent event) { + } - public void handleEvent(DahdiShowChannelsCompleteEvent event) { - } + public void handleEvent(CoreShowChannelsCompleteEvent event) { + } - public void handleEvent(DahdiShowChannelsEvent event) { - } + public void handleEvent(DahdiShowChannelsCompleteEvent event) { + } - public void handleEvent(DbGetResponseEvent event) { - } + public void handleEvent(DahdiShowChannelsEvent event) { + } - public void handleEvent(DongleDeviceEntryEvent event) { - } + public void handleEvent(DbGetResponseEvent event) { + } - public void handleEvent(DongleShowDevicesCompleteEvent event) { - } + public void handleEvent(DongleDeviceEntryEvent event) { + } - public void handleEvent(EndpointList event) { - } + public void handleEvent(DongleShowDevicesCompleteEvent event) { + } - public void handleEvent(EndpointListComplete event) { - } + public void handleEvent(EndpointList event) { + } - public void handleEvent(ListDialplanEvent event) { - } + public void handleEvent(EndpointListComplete event) { + } - public void handleEvent(OriginateResponseEvent event) { - } + public void handleEvent(ListDialplanEvent event) { + } - public void handleEvent(ParkedCallsCompleteEvent event) { - } + public void handleEvent(OriginateResponseEvent event) { + } - public void handleEvent(PeerEntryEvent event) { - } + public void handleEvent(ParkedCallsCompleteEvent event) { + } - public void handleEvent(PeerlistCompleteEvent event) { - } + public void handleEvent(PeerEntryEvent event) { + } - public void handleEvent(PeersEvent event) { - } + public void handleEvent(PeerlistCompleteEvent event) { + } - public void handleEvent(QueueEntryEvent event) { - } + public void handleEvent(PeersEvent event) { + } - public void handleEvent(QueueMemberEvent event) { - } + public void handleEvent(QueueEntryEvent event) { + } - public void handleEvent(QueueParamsEvent event) { - } + public void handleEvent(QueueMemberEvent event) { + } - public void handleEvent(QueueStatusCompleteEvent event) { - } + public void handleEvent(QueueParamsEvent event) { + } - public void handleEvent(QueueSummaryCompleteEvent event) { - } + public void handleEvent(QueueStatusCompleteEvent event) { + } - public void handleEvent(QueueSummaryEvent event) { - } + public void handleEvent(QueueSummaryCompleteEvent event) { + } - public void handleEvent(RegistrationsCompleteEvent event) { - } + public void handleEvent(QueueSummaryEvent event) { + } - public void handleEvent(RegistryEntryEvent event) { - } + public void handleEvent(RegistrationsCompleteEvent event) { + } - public void handleEvent(ShowDialplanCompleteEvent event) { - } + public void handleEvent(RegistryEntryEvent event) { + } - public void handleEvent(SkypeBuddyEntryEvent event) { - } + public void handleEvent(ShowDialplanCompleteEvent event) { + } - public void handleEvent(SkypeBuddyListCompleteEvent event) { - } + public void handleEvent(SkypeBuddyEntryEvent event) { + } - public void handleEvent(SkypeLicenseEvent event) { - } + public void handleEvent(SkypeBuddyListCompleteEvent event) { + } - public void handleEvent(SkypeLicenseListCompleteEvent event) { - } + public void handleEvent(SkypeLicenseEvent event) { + } - public void handleEvent(StatusCompleteEvent event) { - } + public void handleEvent(SkypeLicenseListCompleteEvent event) { + } - public void handleEvent(StatusEvent event) { - } + public void handleEvent(StatusCompleteEvent event) { + } - public void handleEvent(VoicemailUserEntryCompleteEvent event) { - } + public void handleEvent(StatusEvent event) { + } - public void handleEvent(VoicemailUserEntryEvent event) { - } + public void handleEvent(VoicemailUserEntryCompleteEvent event) { + } - public void handleEvent(ZapShowChannelsCompleteEvent event) { - } + public void handleEvent(VoicemailUserEntryEvent event) { + } - public void handleEvent(ZapShowChannelsEvent event) { - } + public void handleEvent(ZapShowChannelsCompleteEvent event) { + } - public void handleEvent(ShutdownEvent event) { - } + public void handleEvent(ZapShowChannelsEvent event) { + } - public void handleEvent(SkypeAccountStatusEvent event) { - } + public void handleEvent(ShutdownEvent event) { + } - public void handleEvent(SkypeBuddyStatusEvent event) { - } + public void handleEvent(SkypeAccountStatusEvent event) { + } - public void handleEvent(SkypeChatMessageEvent event) { - } + public void handleEvent(SkypeBuddyStatusEvent event) { + } - public void handleEvent(SuccessfulAuthEvent event) { - } + public void handleEvent(SkypeChatMessageEvent event) { + } - public void handleEvent(TransferEvent event) { - } + public void handleEvent(SuccessfulAuthEvent event) { + } - public void handleEvent(UserEvent event) { - } + public void handleEvent(AuthMethodNotAllowedEvent event) { + } - public void handleEvent(PausedEvent event) { - } + public void handleEvent(FailedACLEvent event) { + } - public void handleEvent(UnpausedEvent event) { - } + public void handleEvent(InvalidTransportEvent event) { + } - public void handleEvent(VarSetEvent event) { - } + public void handleEvent(LoadAverageLimitEvent event) { + } - /** - * Dispatches to the appropriate handleEvent(...) method. - * - * @param event the event to handle - */ - @Override - public void onManagerEvent(ManagerEvent event) { + public void handleEvent(MemoryLimitEvent 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); - } + public void handleEvent(RequestNotAllowedEvent event) { + } - LOGGER.error("The event " + event.getClass() - + " couldn't be mapped to a method in AbstractManagerEventListener.java, someone should add it!"); - } + 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 + */ + @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 55d2e1ce9..a1ac701b9 100644 --- a/src/main/java/org/asteriskjava/manager/AsteriskMapping.java +++ b/src/main/java/org/asteriskjava/manager/AsteriskMapping.java @@ -1,23 +1,26 @@ package org.asteriskjava.manager; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - import java.lang.annotation.Retention; 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 @interface AsteriskMapping { String value(); -} \ No newline at end of file +} 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 18b65fc4c..e7c10501e 100644 --- a/src/main/java/org/asteriskjava/manager/DefaultManagerConnection.java +++ b/src/main/java/org/asteriskjava/manager/DefaultManagerConnection.java @@ -16,10 +16,6 @@ */ package org.asteriskjava.manager; -import java.io.IOException; -import java.net.InetAddress; -import java.nio.charset.Charset; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.manager.action.EventGeneratingAction; import org.asteriskjava.manager.action.ManagerAction; @@ -27,6 +23,10 @@ import org.asteriskjava.manager.internal.ManagerConnectionImpl; import org.asteriskjava.manager.response.ManagerResponse; +import java.io.IOException; +import java.net.InetAddress; +import java.nio.charset.Charset; + /** * Default implemention of the * {@link org.asteriskjava.manager.ManagerConnection} interface. @@ -43,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(); } @@ -67,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); @@ -79,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); @@ -100,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); } @@ -113,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); } @@ -127,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); } @@ -138,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); } @@ -149,14 +141,12 @@ 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) - { + public void setEncoding(Charset encoding) { impl.setEncoding(encoding); } @@ -171,8 +161,7 @@ public void setEncoding(Charset encoding) * @deprecated use {@link #setDefaultResponseTimeout(long)} instead */ @Deprecated - public void setDefaultTimeout(long defaultTimeout) - { + public void setDefaultTimeout(long defaultTimeout) { impl.setDefaultResponseTimeout(defaultTimeout); } @@ -186,8 +175,7 @@ public void setDefaultTimeout(long defaultTimeout) * @param defaultResponseTimeout default response timeout in milliseconds * @since 0.2 */ - public void setDefaultResponseTimeout(long defaultResponseTimeout) - { + public void setDefaultResponseTimeout(long defaultResponseTimeout) { impl.setDefaultResponseTimeout(defaultResponseTimeout); } @@ -201,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); } @@ -212,11 +199,10 @@ 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) - { + public void setSleepTime(long sleepTime) { } @@ -226,161 +212,132 @@ public void setSleepTime(long sleepTime) *

      * 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(); } @Override - public Charset getEncoding() - { + public Charset getEncoding() { return impl.getEncoding(); } - public AsteriskVersion getVersion() - { + 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< ? extends ManagerEvent> 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 - { + 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 - { + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { return impl.sendAction(action); } public ManagerResponse sendAction(ManagerAction action, long timeout) - throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException - { + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { return impl.sendAction(action, timeout); } public void sendAction(ManagerAction action, SendActionCallback callbackHandler) - throws IOException, IllegalArgumentException, IllegalStateException - { + throws IOException, IllegalArgumentException, IllegalStateException { impl.sendAction(action, callbackHandler); } public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) - throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException - { + throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException { return impl.sendEventGeneratingAction(action); } public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) - throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException - { + throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException { return impl.sendEventGeneratingAction(action, timeout); } @Override public void sendEventGeneratingAction(EventGeneratingAction action, - SendEventGeneratingActionCallback callback) - throws IOException, IllegalArgumentException, IllegalStateException - { + SendEventGeneratingActionCallback callback) + throws IOException, IllegalArgumentException, IllegalStateException { impl.sendEventGeneratingAction(action, callback); } - public void addEventListener(final ManagerEventListener listener) - { + 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("]"); @@ -388,8 +345,7 @@ public String toString() } @Override - public void deregisterEventClass(Class< ? extends ManagerEvent> eventClass) - { + 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 06bd2cda2..da5c836c6 100644 --- a/src/main/java/org/asteriskjava/manager/ExpectedResponse.java +++ b/src/main/java/org/asteriskjava/manager/ExpectedResponse.java @@ -1,12 +1,12 @@ package org.asteriskjava.manager; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; +import org.asteriskjava.manager.response.ManagerResponse; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import org.asteriskjava.manager.response.ManagerResponse; +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 @@ -17,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 2f768d1b4..1fdbc8e42 100644 --- a/src/main/java/org/asteriskjava/manager/ManagerConnection.java +++ b/src/main/java/org/asteriskjava/manager/ManagerConnection.java @@ -16,15 +16,16 @@ */ package org.asteriskjava.manager; -import java.io.IOException; -import java.net.InetAddress; -import java.nio.charset.Charset; 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. @@ -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. * @@ -114,7 +114,7 @@ public interface ManagerConnection * 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(); @@ -171,11 +171,11 @@ public interface ManagerConnection * * @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 */ - void registerUserEventClass(Class< ? extends ManagerEvent> userEventClass); + void registerUserEventClass(Class userEventClass); /** * The timeout to use when connecting the the Asterisk server. @@ -201,19 +201,20 @@ public interface ManagerConnection * 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. + * reconnecting to ther asterisk serve even if the reconnection attempt + * threw an AuthenticationFailedException, false otherwise. */ void setKeepAliveAfterAuthenticationFailure(boolean keepAliveAfterAuthenticationFailure); @@ -221,13 +222,13 @@ public interface ManagerConnection * 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 */ @@ -238,19 +239,19 @@ public interface ManagerConnection * 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; @@ -267,7 +268,7 @@ public interface ManagerConnection * 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(); @@ -284,12 +285,12 @@ public interface ManagerConnection * * @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) */ @@ -300,16 +301,16 @@ ManagerResponse sendAction(ManagerAction action) * 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) @@ -323,14 +324,14 @@ ManagerResponse sendAction(ManagerAction action, long timeout) * 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; @@ -355,16 +356,16 @@ void sendAction(ManagerAction action, SendActionCallback callback) * * @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. + * 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. + * 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 @@ -391,20 +392,20 @@ ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) * {@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. + * 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. + * 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 @@ -425,7 +426,8 @@ ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long time void sendEventGeneratingAction( EventGeneratingAction action, SendEventGeneratingActionCallback callback) - throws IOException, IllegalArgumentException, IllegalStateException; + throws IOException, IllegalArgumentException, IllegalStateException; + /** * Registers an event listener that is called whenever an * {@link org.asteriskjava.manager.event.ManagerEvent} is receiced from the @@ -435,7 +437,7 @@ void sendEventGeneratingAction( * were registered. * * @param eventListener the listener to call whenever a manager event is - * received + * received * @see #removeEventListener(ManagerEventListener) */ void addEventListener(ManagerEventListener eventListener); @@ -450,5 +452,5 @@ void sendEventGeneratingAction( */ void removeEventListener(ManagerEventListener eventListener); - void deregisterEventClass(Class< ? extends ManagerEvent> eventClass); + 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 2813cfbba..12050c8e8 100644 --- a/src/main/java/org/asteriskjava/manager/ManagerEventListenerProxy.java +++ b/src/main/java/org/asteriskjava/manager/ManagerEventListenerProxy.java @@ -1,14 +1,10 @@ package org.asteriskjava.manager; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - 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.

      @@ -27,38 +23,40 @@ * ... * connection.addEventListener(new ManagerEventListenerProxy(myListener)); * - * + * * @author srt * @author fink * @since 0.3 */ public class ManagerEventListenerProxy implements ManagerEventListener { - private final ThreadPoolExecutor executor; + private final ThreadPoolExecutor executor; private final ManagerEventListener target; /** * 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) { - 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!"); - } + 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); - } - }); + @Override + public void onManagerEvent(final ManagerEvent event) { + executor.execute(new Runnable() { + @Override + public void run() { + target.onManagerEvent(event); + } + }); }//onManagerEvent @@ -66,13 +64,13 @@ public void shutdown() { executor.shutdown(); } - public static class Access { - private Access() { - - } - - public static int getThreadQueueSize (ManagerEventListenerProxy proxy) { - return proxy.executor.getQueue().size(); - } - }//Access + 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 ee5edf9b4..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.HashSet; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; - +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 3f2f9f542..0e315621c 100644 --- a/src/main/java/org/asteriskjava/manager/SendActionCallback.java +++ b/src/main/java/org/asteriskjava/manager/SendActionCallback.java @@ -22,16 +22,15 @@ /** * 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 index 09feda162..528e7d643 100644 --- a/src/main/java/org/asteriskjava/manager/SendEventGeneratingActionCallback.java +++ b/src/main/java/org/asteriskjava/manager/SendEventGeneratingActionCallback.java @@ -8,12 +8,11 @@ * {@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 -{ +public interface SendEventGeneratingActionCallback { /** * Called to notify that * {@link ManagerConnection#sendEventGeneratingAction(org.asteriskjava.manager.action.EventGeneratingAction, SendEventGeneratingActionCallback)} @@ -24,8 +23,7 @@ public interface SendEventGeneratingActionCallback * 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. + * @param responseEvents the response at whatever state it was when action ended. */ public void onResponse(ResponseEvents responseEvents); -} \ No newline at end of file +} 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/.gitignore b/src/main/java/org/asteriskjava/manager/action/.gitignore deleted file mode 100644 index e7f72c23a..000000000 --- a/src/main/java/org/asteriskjava/manager/action/.gitignore +++ /dev/null @@ -1,99 +0,0 @@ -/AbsoluteTimeoutAction.class -/AbstractManagerAction.class -/AbstractMeetMeMuteAction.class -/AgentCallbackLoginAction.class -/AgentLogoffAction.class -/AgentsAction.class -/AgiAction.class -/AtxferAction.class -/BridgeAction.class -/ChallengeAction.class -/ChangeMonitorAction.class -/CommandAction.class -/ConfbridgeKickAction.class -/ConfbridgeListAction.class -/ConfbridgeListRoomsAction.class -/ConfbridgeLockAction.class -/ConfbridgeMuteAction.class -/ConfbridgeSetSingleVideoSrcAction.class -/ConfbridgeStartRecordAction.class -/ConfbridgeStopRecordAction.class -/ConfbridgeUnlockAction.class -/ConfbridgeUnmuteAction.class -/CoreSettingsAction.class -/CoreShowChannelsAction.class -/CoreStatusAction.class -/DahdiShowChannelsAction.class -/DbDelAction.class -/DbDelTreeAction.class -/DbGetAction.class -/DbPutAction.class -/DongleSendSMSAction.class -/DongleShowDevicesAction.class -/EventGeneratingAction.class -/EventsAction.class -/ExtensionStateAction.class -/FilterAction.class -/GetConfigAction.class -/GetVarAction.class -/HangupAction.class -/IaxPeerListAction.class -/JabberSendAction.class -/ListCommandsAction.class -/LocalOptimizeAwayAction.class -/LoginAction.class -/LogoffAction.class -/MailboxCountAction.class -/MailboxStatusAction.class -/ManagerAction.class -/MeetMeMuteAction.class -/MeetMeUnmuteAction.class -/MixMonitorMuteAction.class -/ModuleCheckAction.class -/ModuleLoadAction.class -/MonitorAction.class -/OriginateAction.class -/ParkAction.class -/ParkedCallsAction.class -/PauseMixMonitorAction.class -/PauseMonitorAction.class -/PingAction.class -/PlayDtmfAction.class -/QueueAddAction.class -/QueueLogAction.class -/QueuePauseAction.class -/QueuePenaltyAction.class -/QueueRemoveAction.class -/QueueResetAction.class -/QueueStatusAction.class -/QueueSummaryAction.class -/RedirectAction.class -/SendTextAction.class -/SetCdrUserFieldAction.class -/SetVarAction.class -/ShowDialplanAction.class -/SipNotifyAction.class -/SipPeersAction.class -/SipShowPeerAction.class -/SipShowRegistryAction.class -/SkypeAccountPropertyAction.class -/SkypeAddBuddyAction.class -/SkypeBuddiesAction.class -/SkypeBuddyAction.class -/SkypeChatSendAction.class -/SkypeLicenseListAction.class -/SkypeLicenseStatusAction.class -/SkypeRemoveBuddyAction.class -/StatusAction.class -/StopMonitorAction.class -/UnpauseMonitorAction.class -/UpdateConfigAction.class -/UserEventAction.class -/VoicemailUsersListAction.class -/ZapDialOffhookAction.class -/ZapDndOffAction.class -/ZapDndOnAction.class -/ZapHangupAction.class -/ZapRestartAction.class -/ZapShowChannelsAction.class -/ZapTransferAction.class 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 386934f0a..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() - { - StringBuilder sb; + public String toString() { + StringBuilder sb; Map getters; 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 de2bfa66f..014cefd15 100644 --- a/src/main/java/org/asteriskjava/manager/action/AgiAction.java +++ b/src/main/java/org/asteriskjava/manager/action/AgiAction.java @@ -27,13 +27,12 @@ *
      * 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 index 1d5b72785..a52b21cbd 100644 --- a/src/main/java/org/asteriskjava/manager/action/DahdiShowChannelsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/DahdiShowChannelsAction.java @@ -23,16 +23,15 @@ * 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. - * - * @see org.asteriskjava.manager.event.DahdiShowChannelsEvent - * @see org.asteriskjava.manager.event.DahdiShowChannelsCompleteEvent + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.event.DahdiShowChannelsEvent + * @see org.asteriskjava.manager.event.DahdiShowChannelsCompleteEvent */ public class DahdiShowChannelsAction extends AbstractManagerAction implements - EventGeneratingAction -{ + EventGeneratingAction { /** * Serializable version identifier */ @@ -41,8 +40,7 @@ public class DahdiShowChannelsAction extends AbstractManagerAction /** * Creates a new DahdiShowChannelsAction. */ - public DahdiShowChannelsAction() - { + public DahdiShowChannelsAction() { } @@ -50,13 +48,11 @@ public DahdiShowChannelsAction() * Returns the name of this action, i.e. "DahdiShowChannels". */ @Override - public String getAction() - { + public String getAction() { return "DahdiShowChannels"; } - public Class getActionCompleteEventClass() - { + 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 index 2a37c2b35..a0dde3f58 100644 --- a/src/main/java/org/asteriskjava/manager/action/DongleSendSMSAction.java +++ b/src/main/java/org/asteriskjava/manager/action/DongleSendSMSAction.java @@ -1,45 +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; +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; - } -} \ No newline at end of file + 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 index 1f9fd7abe..c2418b717 100644 --- a/src/main/java/org/asteriskjava/manager/action/DongleShowDevicesAction.java +++ b/src/main/java/org/asteriskjava/manager/action/DongleShowDevicesAction.java @@ -1,4 +1,3 @@ - package org.asteriskjava.manager.action; import org.asteriskjava.manager.event.DongleShowDevicesCompleteEvent; @@ -7,8 +6,7 @@ public class DongleShowDevicesAction extends AbstractManagerAction implements - EventGeneratingAction -{ + EventGeneratingAction { /** * Serializable version identifier */ @@ -17,8 +15,7 @@ public class DongleShowDevicesAction extends AbstractManagerAction /** * Creates a new DahdiShowChannelsAction. */ - public DongleShowDevicesAction() - { + public DongleShowDevicesAction() { } @@ -26,13 +23,11 @@ public DongleShowDevicesAction() * Returns the name of this action, i.e. "DahdiShowChannels". */ @Override - public String getAction() - { + public String getAction() { return "DongleShowDevices"; } - public Class getActionCompleteEventClass() - { + 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 index d81436134..ec4ddcc32 100644 --- a/src/main/java/org/asteriskjava/manager/action/FilterAction.java +++ b/src/main/java/org/asteriskjava/manager/action/FilterAction.java @@ -19,28 +19,27 @@ /** * 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. - * + *

      + * 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) - * + * 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 -{ +public class FilterAction extends AbstractManagerAction { static final long serialVersionUID = 5537508784388696503L; private String operation = "Add";//No other option other than Add at the moment. @@ -49,18 +48,16 @@ public class FilterAction extends AbstractManagerAction /** * Creates a new FilterAction. */ - public FilterAction() - { + public FilterAction() { } /** * Creates a new FilterAction with the filter specified * - * @param filter the whitelist or blacklist filter to be added. + * @param filter the whitelist or blacklist filter to be added. * @since ??? */ - public FilterAction(String filter) - { + public FilterAction(String filter) { this.filter = filter; } @@ -68,8 +65,7 @@ public FilterAction(String filter) * Returns the name of this action, i.e. "Filter". */ @Override - public String getAction() - { + public String getAction() { return "Filter"; } @@ -78,28 +74,25 @@ public String getAction() * * @return the filter operation which is "Add" by default */ - public String getOperation() - { + public String getOperation() { return operation; - } - + } + /** * Returns the filter. * * @return the filter. */ - public String getFilter() - { + public String getFilter() { return filter; } /** - * Sets the filter. + * Sets the filter. * - * @param filter add the whitelist or blacklist event to be filtered. + * @param filter add the whitelist or blacklist event to be filtered. */ - public void setFilter(String filter) - { + 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 180a509b1..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,8 +107,7 @@ public void setChannel(String channel) * @return the hangup cause. * @since 1.0.0 */ - public Integer getCause() - { + public Integer getCause() { return cause; } @@ -113,8 +118,12 @@ public Integer getCause() * @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 index b06a25bb6..d307c53d5 100644 --- a/src/main/java/org/asteriskjava/manager/action/LocalOptimizeAwayAction.java +++ b/src/main/java/org/asteriskjava/manager/action/LocalOptimizeAwayAction.java @@ -23,8 +23,7 @@ * * @author SYON Communications Inc. */ -public class LocalOptimizeAwayAction extends AbstractManagerAction -{ +public class LocalOptimizeAwayAction extends AbstractManagerAction { /** * Serializable version identifier. */ @@ -34,8 +33,7 @@ public class LocalOptimizeAwayAction extends AbstractManagerAction /** * Creates a new empty LocalOptimizeAwayAction. */ - public LocalOptimizeAwayAction() - { + public LocalOptimizeAwayAction() { } @@ -44,18 +42,16 @@ public LocalOptimizeAwayAction() * * @param channel Name of the channel for clears the flag. */ - public LocalOptimizeAwayAction(String channel) - { - this.channel = channel; + public LocalOptimizeAwayAction(String channel) { + this.channel = channel; } /** * Returns the name of this action, i.e. "LocalOptimizeAway". */ @Override - public String getAction() - { - return "LocalOptimizeAway"; + public String getAction() { + return "LocalOptimizeAway"; } /** @@ -63,9 +59,8 @@ public String getAction() * * @return Name of the channel for clears the flag. */ - public String getChannel() - { - return channel; + public String getChannel() { + return channel; } /** @@ -73,9 +68,8 @@ public String getChannel() * * @param channel Name of the channel for clears the flag. */ - public void setChannel(String channel) - { - this.channel = channel; + 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 e7007544d..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 {@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 index 8b459de19..646f95a4a 100644 --- a/src/main/java/org/asteriskjava/manager/action/MWIDeleteAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MWIDeleteAction.java @@ -16,38 +16,32 @@ */ package org.asteriskjava.manager.action; -public class MWIDeleteAction extends AbstractManagerAction -{ +public class MWIDeleteAction extends AbstractManagerAction { static final long serialVersionUID = 1L; private String mailbox; /** * Creates a new MWIDeleteAction. */ - public MWIDeleteAction() - { + public MWIDeleteAction() { } - public MWIDeleteAction(String mailbox) - { + public MWIDeleteAction(String mailbox) { this.mailbox = mailbox; } - public String getMailbox() - { + public String getMailbox() { return mailbox; } - public void setMailbox(String mailbox) - { + public void setMailbox(String mailbox) { this.mailbox = mailbox; } @Override - public String getAction() - { + 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 index cb2aa9ad6..a9adfe154 100644 --- a/src/main/java/org/asteriskjava/manager/action/MWIUpdateAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MWIUpdateAction.java @@ -16,8 +16,7 @@ */ package org.asteriskjava.manager.action; -public class MWIUpdateAction extends AbstractManagerAction -{ +public class MWIUpdateAction extends AbstractManagerAction { static final long serialVersionUID = 1L; private String mailbox; private int oldMessages; @@ -26,52 +25,43 @@ public class MWIUpdateAction extends AbstractManagerAction /** * Creates a new MWIUpdateAction. */ - public MWIUpdateAction() - { + public MWIUpdateAction() { } - public MWIUpdateAction(String mailbox, int oldMessages, int newMessages) - { + public MWIUpdateAction(String mailbox, int oldMessages, int newMessages) { this.mailbox = mailbox; this.oldMessages = oldMessages; this.newMessages = newMessages; } - public String getMailbox() - { + public String getMailbox() { return mailbox; } - public void setMailbox(String mailbox) - { + public void setMailbox(String mailbox) { this.mailbox = mailbox; } - public int getOldMessages() - { + public int getOldMessages() { return oldMessages; } - public void setOldMessages(int oldMessages) - { + public void setOldMessages(int oldMessages) { this.oldMessages = oldMessages; } - public int getNewMessages() - { + public int getNewMessages() { return newMessages; } - public void setNewMessages(int newMessages) - { + public void setNewMessages(int newMessages) { this.newMessages = newMessages; } @Override - public String getAction() - { + 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 index b9f65b78f..b13218c65 100644 --- a/src/main/java/org/asteriskjava/manager/action/MessageSendAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MessageSendAction.java @@ -10,8 +10,7 @@ * @version $Id$ * @since 1.0.0 */ -public class MessageSendAction extends AbstractManagerAction -{ +public class MessageSendAction extends AbstractManagerAction { private static final long serialVersionUID = -6554282385166411723L; private String to; @@ -21,8 +20,7 @@ public class MessageSendAction extends AbstractManagerAction private Map variables; @Override - public String getAction() - { + public String getAction() { return "MessageSend"; } @@ -33,22 +31,19 @@ public String getAction() * value. * @since 1.0.0 */ - public Map getVariables() - { + public Map getVariables() { return variables; } /** * Sets an variable on the originated call. * - * @param name the name of the variable to set. + * @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) - { + public void setVariable(String name, String value) { + if (variables == null) { variables = new LinkedHashMap<>(); } @@ -57,91 +52,85 @@ public void setVariable(String name, String value) /** * Retrives destination of message - * + * * @return String in format like sip:userid */ - public String getTo() - { + public String getTo() { return to; } /** * Set destination of message - * + * * @param to String in format like sip:userid */ - public void setTo(String to) - { + public void setTo(String to) { this.to = to; } /** * get From String - * + * * @return String in form like sip:asterisk@server-ip */ - public String getFrom() - { + public String getFrom() { return from; } /** - * set From String + * set From String + * * @param String from in form like sip:asterisk@server-ip */ - public void setFrom(String from) - { + 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() - { + 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) - { + public void setBody(String body) { this.body = body; } /** * Retrieves content encoded in base64 - * - * @code new String(Base64.decode(getBase64body(), Formatting (for ex "UTF-8")) + * * @return Base64 encoded String + * @code new String(Base64.decode(getBase64body(), Formatting (for ex "UTF-8")) */ - public String getBase64body() - { + 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")); + * 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 + * + * @param base64body */ - public void setBase64body(String 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 index a66023ff2..fa7bc94c5 100644 --- a/src/main/java/org/asteriskjava/manager/action/MixMonitorAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MixMonitorAction.java @@ -21,7 +21,7 @@ /** * Start a MixMonitor on the specified channel. - * + *

      * Available since Asterisk 11 * * @see org.asteriskjava.manager.response.MixMonitorResponse @@ -30,8 +30,7 @@ * @see MixMonitorMuteAction */ @ExpectedResponse(MixMonitorResponse.class) -public class MixMonitorAction extends AbstractManagerAction -{ +public class MixMonitorAction extends AbstractManagerAction { private static final long serialVersionUID = 1L; private String channel; private String file; @@ -41,8 +40,7 @@ public class MixMonitorAction extends AbstractManagerAction /** * Creates a new empty MixMonitorAction */ - public MixMonitorAction() - { + public MixMonitorAction() { super(); } @@ -50,10 +48,9 @@ public MixMonitorAction() * Creates a new MixMonitorAction that starts monitoring the given channel * using a default filename. * - * @param channel the name of the channel to monitor + * @param channel the name of the channel to monitor */ - public MixMonitorAction(String channel) - { + public MixMonitorAction(String channel) { this(channel, null, null, null); } @@ -61,11 +58,10 @@ public MixMonitorAction(String channel) * 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 + * @param channel the name of the channel to monitor + * @param filename the filename to use for the recording */ - public MixMonitorAction(String channel, String filename) - { + public MixMonitorAction(String channel, String filename) { this(channel, filename, null, null); } @@ -73,12 +69,11 @@ public MixMonitorAction(String channel, String filename) * 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 + * @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) - { + public MixMonitorAction(String channel, String filename, String options) { this(channel, filename, options, null); } @@ -86,16 +81,15 @@ public MixMonitorAction(String channel, String filename, String options) * 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 + * @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) - { + public MixMonitorAction(String channel, String filename, String options, String command) { this.channel = channel; this.file = filename; this.options = options; @@ -108,8 +102,7 @@ public MixMonitorAction(String channel, String filename, String options, String * @return the name of the AMI action that this class implements */ @Override - public String getAction() - { + public String getAction() { return "MixMonitor"; } @@ -118,8 +111,7 @@ public String getAction() * * @return the Asterisk channel name */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -128,8 +120,7 @@ public String getChannel() * * @param channel the Asterisk channel name */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -138,8 +129,7 @@ public void setChannel(String channel) * * @return the recording filename */ - public String getFile() - { + public String getFile() { return file; } @@ -148,8 +138,7 @@ public String getFile() * * @param filename the recording filename */ - public void setFile(String filename) - { + public void setFile(String filename) { this.file = filename; } @@ -158,8 +147,7 @@ public void setFile(String filename) * * @return the MixMonitor options */ - public String getOptions() - { + public String getOptions() { return options; } @@ -170,34 +158,31 @@ public String getOptions() * * @param options the MixMonitor options */ - public void setOptions(String 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() - { + 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) - { + 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 index 0be1bc764..1110c239c 100644 --- a/src/main/java/org/asteriskjava/manager/action/MixMonitorMuteAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MixMonitorMuteAction.java @@ -17,126 +17,128 @@ /** * 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; +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"; + } - /** - * 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; + } - /** - * 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; + } - /** - * 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; + } - /** - * 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; + } - /** - * 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; + } - /** - * 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; + } - /** - * 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 index e206fe345..0b49c16b0 100644 --- a/src/main/java/org/asteriskjava/manager/action/MuteAudioAction.java +++ b/src/main/java/org/asteriskjava/manager/action/MuteAudioAction.java @@ -22,129 +22,116 @@ * 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$ - } - +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; - } - + */ + public String getChannel() { + return this.channel; + } + /** * Returns the audio direction which is to be muted/unmuted. - */ - public Direction getDirection() - { - return this.direction; - } - + */ + public Direction getDirection() { + return this.direction; + } + /** * Returns the state controls whether we are muting or unmuting the channel. - */ - public State getState() - { - return this.state; - } + */ + 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; } @@ -152,7 +139,7 @@ public void setChannel(String channel) { /** * Sets the audio direction which is to be muted/unmuted.

      * This property is mandatory. - */ + */ public void setDirection(Direction direction) { this.direction = direction; } @@ -160,9 +147,9 @@ public void setDirection(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 4d3ab62c3..964e2b77e 100644 --- a/src/main/java/org/asteriskjava/manager/action/OriginateAction.java +++ b/src/main/java/org/asteriskjava/manager/action/OriginateAction.java @@ -16,19 +16,13 @@ */ package org.asteriskjava.manager.action; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - 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 @@ -52,8 +46,7 @@ * @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()); @@ -90,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"; } @@ -100,8 +92,7 @@ public String getAction() * * @return the account code to use for the originated call. */ - public String getAccount() - { + public String getAccount() { return account; } @@ -113,16 +104,14 @@ public String getAccount() * * @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; } @@ -134,8 +123,7 @@ public String getCallerId() * * @param callerId the caller id to set on the outgoing channel. */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerId = callerId; } @@ -147,8 +135,7 @@ public void setCallerId(String callerId) * @return the calling presentation for the outgoing channel. * @see #setCallingPres(Integer) */ - public Integer getCallingPres() - { + public Integer getCallingPres() { return callingPres; } @@ -167,7 +154,7 @@ public Integer getCallingPres() *

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

            * Bits Meaning
            *  7 6
      @@ -176,9 +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
      @@ -187,30 +174,28 @@ 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; } @@ -219,16 +204,14 @@ public String getChannel() *

      * 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; } @@ -238,16 +221,14 @@ public String getContext() * 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; } @@ -257,16 +238,14 @@ public String getExten() * 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; } @@ -274,48 +253,42 @@ 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; } @@ -331,23 +304,17 @@ public Long getTimeout() * @deprecated use {@link #setTimeout(Long)} instead. */ @Deprecated - public void setTimeout(Integer timeout) - { - if (timeout != null) - { - if (timeout < 1000) - { + 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) - { + 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 - { + } else { this.timeout = null; } } @@ -362,16 +329,12 @@ public void setTimeout(Integer timeout) * * @param timeout the timeout in milliseconds */ - public void setTimeout(Long timeout) - { - if (timeout != null) - { - if (timeout < 1000) - { + 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) - { + if (timeout < 10000) { logger.warn( "A timeout of less than 100000 will cause the originate to fail if not answered within 10 seconds!"); } @@ -391,29 +354,23 @@ public void setTimeout(Long timeout) * @deprecated use {@link #setVariables(Map)} instead. */ @Deprecated - public void setVariable(String variable) - { + 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()) - { + 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]); } } @@ -422,14 +379,12 @@ public void setVariable(String variable) /** * Sets an variable on the originated call. * - * @param name the name of the variable to set. + * @param name the name of the variable to set. * @param value the value of the variable to set. * @since 0.3 */ - public void setVariable(String name, String value) - { - if (variables == null) - { + public void setVariable(String name, String value) { + if (variables == null) { variables = new LinkedHashMap<>(); } @@ -440,11 +395,10 @@ 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. + * value. * @since 0.2 */ - public Map getVariables() - { + public Map getVariables() { return variables; } @@ -452,17 +406,13 @@ public Map getVariables() * Sets the variables to set on the originated call. * * @param variables a Map containing the variable names as key and their - * values as value. + * values as value. * @since 0.2 */ - public void setVariables(Map variables) - { - if (this.variables != null) - { + public void setVariables(Map variables) { + if (this.variables != null) { this.variables.putAll(variables); - } - else - { + } else { this.variables = variables; } } @@ -470,8 +420,7 @@ public void setVariables(Map variables) /** * Returns true if this is a fast origination. */ - public Boolean getAsync() - { + public Boolean getAsync() { return async; } @@ -479,24 +428,21 @@ 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) - { + public void setEarlyMedia(Boolean earlyMedia) { this.earlyMedia = earlyMedia; } /** * @return the earlyMedia */ - public Boolean getEarlyMedia() - { + public Boolean getEarlyMedia() { return earlyMedia; } @@ -506,8 +452,7 @@ public Boolean getEarlyMedia() * @return the codecs to use for the call. * @since 1.0.0 */ - public String getCodecs() - { + public String getCodecs() { return codecs; } @@ -519,8 +464,7 @@ public String getCodecs() * @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; } @@ -532,62 +476,47 @@ public void setCodecs(String codecs) * @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(); StringBuilder buffer = new StringBuilder(iter.next()); - while (iter.hasNext()) - { + while (iter.hasNext()) { buffer.append(",").append(iter.next()); } this.codecs = buffer.toString(); } - public Class< ? extends ResponseEvent> getActionCompleteEventClass() - { + public Class getActionCompleteEventClass() { return OriginateResponseEvent.class; } - public void addSipHeader(VariableInheritance inheritance, String header) - { - if (!preventDuplicateSipHeaders.contains(header)) - { + public void addSipHeader(VariableInheritance inheritance, String header) { + if (!preventDuplicateSipHeaders.contains(header)) { setVariable(inheritance.getPrefix() + "SIPADDHEADER" + (headerCounter++), header); preventDuplicateSipHeaders.add(header); - if (headerCounter > 50) - { + if (headerCounter > 50) { logger.warn("I think only 50 headers are allowed by asterisk?"); } - } - else - { + } else { logger.error("Already added the sip header " + header); } } - public void addPjSipHeader(VariableInheritance inheritance, String header) - { - if (header != null) - { + public void addPjSipHeader(VariableInheritance inheritance, String header) { + if (header != null) { String[] parts = header.split(":"); - if (parts.length == 2) - { + if (parts.length == 2) { String varName = "PJSIP_HEADER" + "(add," + parts[0] + ")"; String varValue = parts[1]; - if (!preventDuplicateSipHeaders.contains(header)) - { + if (!preventDuplicateSipHeaders.contains(header)) { setVariable(varName, varValue); preventDuplicateSipHeaders.add(header); - } - else - { + } else { logger.error("Already added the sip header " + header); } } @@ -596,26 +525,22 @@ public void addPjSipHeader(VariableInheritance inheritance, String header) /** * this will be the channels uniqueID - * + * * @param channelId */ - public void setChannelId(String channelId) - { + public void setChannelId(String channelId) { this.channelId = channelId; } - public String getChannelId() - { + public String getChannelId() { return channelId; } - public void setOtherChannelId(String otherChannelId) - { + public void setOtherChannelId(String otherChannelId) { this.otherChannelId = otherChannelId; } - public String getOtherChannelId() - { + 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 index 6c261dcb8..40dd386b8 100644 --- a/src/main/java/org/asteriskjava/manager/action/PJSIPNotifyAction.java +++ b/src/main/java/org/asteriskjava/manager/action/PJSIPNotifyAction.java @@ -27,122 +27,109 @@ *

      * 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 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(); - } + public PJSIPNotifyAction() { + super(); + } - @Override - public String getAction() - { - return "PJSIPNotify"; - } + @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 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 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; - } + /** + * 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 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 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; - } + /** + * 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<>(); - } + /** + * 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); - } + this.variables.put(name, value); + } - /** - * Set all variables. See {@link #setVariable(String, String)}. - * - * @param variables - */ - public void setVariables(Map variables) - { - this.variables = variables; - } + /** + * 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; - } + /** + * 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 index c4948961c..bc899dc48 100644 --- a/src/main/java/org/asteriskjava/manager/action/PJSipShowContactsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/PJSipShowContactsAction.java @@ -20,22 +20,21 @@ import org.asteriskjava.manager.event.ResponseEvent; /** - * Retrieves a list of all defined SIP peers. + * Retrieves a list of all defined PJSIP contacts. *

      - * For each peer that is found a PeerEntryEvent is sent by Asterisk containing - * the details. When all peers have been reported a PeerlistCompleteEvent is + * 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 1.2 Permission required: write=system + * Available since Asterisk 16 Permission required: write=system * * @author srt * @version $Id$ - * @see org.asteriskjava.manager.event.PeerEntryEvent - * @see org.asteriskjava.manager.event.PeerlistCompleteEvent + * @see org.asteriskjava.manager.event.ContactList + * @see org.asteriskjava.manager.event.ContactListComplete * @since 0.2 */ -public class PJSipShowContactsAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class PJSipShowContactsAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serial version identifier. */ @@ -44,19 +43,16 @@ public class PJSipShowContactsAction extends AbstractManagerAction implements Ev /** * Creates a new SipPeersAction. */ - public PJSipShowContactsAction() - { + public PJSipShowContactsAction() { } @Override - public String getAction() - { + public String getAction() { return "PJSIPShowContacts"; } - public Class< ? extends ResponseEvent> getActionCompleteEventClass() - { + 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 index f33aa8eaf..71c738724 100644 --- a/src/main/java/org/asteriskjava/manager/action/PJSipShowEndpointsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/PJSipShowEndpointsAction.java @@ -26,16 +26,15 @@ * the details. When all peers have been reported a PeerlistCompleteEvent is * sent. *

      - * Available since Asterisk 1.2 Permission required: write=system + * 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 0.2 + * @since 12 */ -public class PJSipShowEndpointsAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class PJSipShowEndpointsAction extends AbstractManagerAction implements EventGeneratingAction { /** * Serial version identifier. */ @@ -44,19 +43,16 @@ public class PJSipShowEndpointsAction extends AbstractManagerAction implements E /** * Creates a new SipPeersAction. */ - public PJSipShowEndpointsAction() - { + public PJSipShowEndpointsAction() { } @Override - public String getAction() - { + public String getAction() { return "PJSIPShowEndpoints"; } - public Class< ? extends ResponseEvent> getActionCompleteEventClass() - { + 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 index 501a09e0a..31992b30c 100644 --- a/src/main/java/org/asteriskjava/manager/action/PauseMixMonitorAction.java +++ b/src/main/java/org/asteriskjava/manager/action/PauseMixMonitorAction.java @@ -16,63 +16,64 @@ */ 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. + * 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 - * @since 0.3 * @version $Id$ + * @since 0.3 */ -public class PauseMixMonitorAction extends AbstractManagerAction{ - - private static final long serialVersionUID = -7438670441797420390L; - - private String channel; +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) { + 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; - } + @Override + public String getAction() { + return "MixMonitorMute"; + } + + public String getChannel() { + return channel; + } - public void setChannel(String channel) { - this.channel = channel; - } + public void setChannel(String channel) { + this.channel = channel; + } - public Integer getState() { - return state; - } + public Integer getState() { + return state; + } - public void setState(Integer state) { - this.state = state; - } + public void setState(Integer state) { + this.state = state; + } - public String getDirection() { - return direction; - } + public String getDirection() { + return direction; + } - public void setDirection(String direction) { - this.direction = 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 cda358b14..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 */ @@ -41,19 +40,17 @@ public class QueuePauseAction extends AbstractManagerAction /** * 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; } @@ -61,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; @@ -75,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; } @@ -89,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; @@ -104,81 +98,74 @@ 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; } @@ -188,9 +175,8 @@ public void setPaused(Boolean paused) * * @return Name of the local reason for clears the flag. */ - public String getReason() - { - return reason; + public String getReason() { + return reason; } /** @@ -199,8 +185,7 @@ public String getReason() * * @param reason Name of the local reason for clears the flag. */ - public void setReason(String reason) - { - this.reason = reason; + 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 40dfff5d6..c1a5520ec 100644 --- a/src/main/java/org/asteriskjava/manager/action/QueueSummaryAction.java +++ b/src/main/java/org/asteriskjava/manager/action/QueueSummaryAction.java @@ -11,15 +11,14 @@ *

      * This action has been added by * http://bugs.digium.com/view.php?id=8035. - * - * @see QueueSummaryEvent - * @see QueueSummaryCompleteEvent + * * @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 c67d86c0d..0632ed4ec 100644 --- a/src/main/java/org/asteriskjava/manager/action/RedirectAction.java +++ b/src/main/java/org/asteriskjava/manager/action/RedirectAction.java @@ -29,12 +29,11 @@ * 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 */ @@ -52,23 +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; @@ -83,16 +80,15 @@ public RedirectAction(String channel, String context, String exten, Integer prio * 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 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; @@ -107,20 +103,19 @@ public RedirectAction(String channel, String extraChannel, String context, Strin * 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 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) - { + String extraContext, String extraExten, Integer extraPriority) { this.channel = channel; this.extraChannel = extraChannel; this.context = context; @@ -129,8 +124,7 @@ public RedirectAction(String channel, String extraChannel, String context, Strin this.extraContext = extraContext; this.extraExten = extraExten; this.extraPriority = extraPriority; - if (channel.equalsIgnoreCase(extraChannel)) - { + if (channel.equalsIgnoreCase(extraChannel)) { throw new RuntimeException("ExtraChannel = channel ... bad things will happen to asterisk"); } } @@ -139,112 +133,100 @@ public RedirectAction(String channel, String extraChannel, String context, Strin * 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)) - { + 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; } @@ -252,11 +234,10 @@ public void setPriority(Integer priority) * 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; } @@ -264,11 +245,10 @@ public String getExtraContext() * 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; } @@ -276,11 +256,10 @@ public void setExtraContext(String extraContext) * 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; } @@ -288,11 +267,10 @@ public String getExtraExten() * 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; } @@ -300,11 +278,10 @@ public void setExtraExten(String extraExten) * 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; } @@ -312,11 +289,10 @@ public Integer getExtraPriority() * 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 0d222f447..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. http://www.asteriasgi.com * @author srt * @version $Id$ */ -public class SetVarAction extends AbstractManagerAction -{ +public class SetVarAction extends AbstractManagerAction { /** * Serial version identifier */ @@ -49,35 +48,32 @@ public class SetVarAction extends AbstractManagerAction /** * 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 e7d8ab04b..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,10 +83,8 @@ 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) - { + public void setVariable(String name, String value) { + if (variables == null) { variables = new LinkedHashMap<>(); } @@ -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 47cfb2094..212ea7e89 100644 --- a/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java @@ -25,7 +25,7 @@ * the details. When all peers have been reported a PeerlistCompleteEvent is * sent.

      * Available since Asterisk 1.2 - * + *

      * Permission required: write=system * * @author srt @@ -34,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. */ @@ -44,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 53eef2ad2..e3367485e 100644 --- a/src/main/java/org/asteriskjava/manager/action/SkypeAccountPropertyAction.java +++ b/src/main/java/org/asteriskjava/manager/action/SkypeAccountPropertyAction.java @@ -25,8 +25,7 @@ * * @since 1.0.0 */ -public class SkypeAccountPropertyAction extends AbstractManagerAction -{ +public class SkypeAccountPropertyAction extends AbstractManagerAction { /** * Serializable version identifier */ @@ -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() - { + 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); } - 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 b32b85e9e..a3e728d58 100644 --- a/src/main/java/org/asteriskjava/manager/action/StatusAction.java +++ b/src/main/java/org/asteriskjava/manager/action/StatusAction.java @@ -16,12 +16,12 @@ */ package org.asteriskjava.manager.action; -import java.util.Iterator; -import java.util.List; - import org.asteriskjava.manager.event.ResponseEvent; import org.asteriskjava.manager.event.StatusCompleteEvent; +import java.util.Iterator; +import java.util.List; + /** * The StatusAction requests the state of all active channels. Alternativly (as of Asterisk 1.6) * you can also pass a channel name to only retrive the status of one specific channel.

      @@ -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(); StringBuilder buffer = new StringBuilder(iter.next()); - while (iter.hasNext()) - { + 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 index 79d172279..5e5047f19 100644 --- a/src/main/java/org/asteriskjava/manager/action/StopMixMonitorAction.java +++ b/src/main/java/org/asteriskjava/manager/action/StopMixMonitorAction.java @@ -18,15 +18,14 @@ /** * Stop the specified MixMonitor on the specified channel. - * + *

      * Available since Asterisk 11 * * @see MixMonitorAction * @see PauseMixMonitorAction * @see MixMonitorMuteAction */ -public class StopMixMonitorAction extends AbstractManagerAction -{ +public class StopMixMonitorAction extends AbstractManagerAction { private static final long serialVersionUID = 1L; private String channel; private String mixMonitorId; @@ -34,8 +33,7 @@ public class StopMixMonitorAction extends AbstractManagerAction /** * Creates a new empty StopMixMonitorAction */ - public StopMixMonitorAction() - { + public StopMixMonitorAction() { super(); } @@ -43,10 +41,9 @@ public StopMixMonitorAction() * Creates a StopMixMonitorAction that stops all MixMonitors on the * specified channel. * - * @param channel the name of the channel + * @param channel the name of the channel */ - public StopMixMonitorAction(String channel) - { + public StopMixMonitorAction(String channel) { this(channel, null); } @@ -54,11 +51,10 @@ public StopMixMonitorAction(String channel) * 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 + * @param channel the name of the channel + * @param mixMonitorId the ID of the MixMonitor to stop */ - public StopMixMonitorAction(String channel, String mixMonitorId) - { + public StopMixMonitorAction(String channel, String mixMonitorId) { this.channel = channel; this.mixMonitorId = mixMonitorId; } @@ -69,8 +65,7 @@ public StopMixMonitorAction(String channel, String mixMonitorId) * @return the name of the AMI action that this class implements */ @Override - public String getAction() - { + public String getAction() { return "StopMixMonitor"; } @@ -79,8 +74,7 @@ public String getAction() * * @return the Asterisk channel name */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -89,8 +83,7 @@ public String getChannel() * * @param channel the Asterisk channel name */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -99,8 +92,7 @@ public void setChannel(String channel) * * @return the MixMonitor ID */ - public String getMixMonitorId() - { + public String getMixMonitorId() { return mixMonitorId; } @@ -109,8 +101,7 @@ public String getMixMonitorId() * * @param mixMonitorId the MixMonitor ID */ - public void setMixMonitorId(String mixMonitorId) - { + public void setMixMonitorId(String mixMonitorId) { this.mixMonitorId = mixMonitorId; } -} \ No newline at end of file +} 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 057eabd71..f3fd0ad43 100644 --- a/src/main/java/org/asteriskjava/manager/action/UpdateConfigAction.java +++ b/src/main/java/org/asteriskjava/manager/action/UpdateConfigAction.java @@ -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,19 +68,17 @@ public class UpdateConfigAction extends AbstractManagerAction /** * Creates a new UpdateConfigAction. */ - public UpdateConfigAction() - { + public UpdateConfigAction() { this.actionCounter = 0; 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; @@ -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 index 369f439e1..27c233b86 100644 --- a/src/main/java/org/asteriskjava/manager/action/VariableInheritance.java +++ b/src/main/java/org/asteriskjava/manager/action/VariableInheritance.java @@ -1,18 +1,15 @@ package org.asteriskjava.manager.action; -public enum VariableInheritance -{ +public enum VariableInheritance { NONE(""), SINGLE("_"), DOUBLE("__"); private String prefix; - VariableInheritance(String prefix) - { + VariableInheritance(String prefix) { this.prefix = prefix; } - String getPrefix() - { + 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 1b896995e..247c97350 100644 --- a/src/main/java/org/asteriskjava/manager/action/VoicemailUsersListAction.java +++ b/src/main/java/org/asteriskjava/manager/action/VoicemailUsersListAction.java @@ -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 181513d28..9ba259fc9 100644 --- a/src/main/java/org/asteriskjava/manager/action/ZapShowChannelsAction.java +++ b/src/main/java/org/asteriskjava/manager/action/ZapShowChannelsAction.java @@ -23,16 +23,15 @@ * 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/.gitignore b/src/main/java/org/asteriskjava/manager/event/.gitignore deleted file mode 100644 index b1180ee41..000000000 --- a/src/main/java/org/asteriskjava/manager/event/.gitignore +++ /dev/null @@ -1,179 +0,0 @@ -/AbstractAgentEvent.class -/AbstractChannelEvent.class -/AbstractChannelStateEvent.class -/AbstractFaxEvent.class -/AbstractMeetMeEvent.class -/AbstractMonitorEvent.class -/AbstractParkedCallEvent.class -/AbstractQueueMemberEvent.class -/AbstractRtcpEvent.class -/AbstractRtpStatEvent.class -/AgentCallbackLoginEvent.class -/AgentCallbackLogoffEvent.class -/AgentCalledEvent.class -/AgentCompleteEvent.class -/AgentConnectEvent.class -/AgentDumpEvent.class -/AgentLoginEvent.class -/AgentLogoffEvent.class -/AgentRingNoAnswerEvent.class -/AgentsCompleteEvent.class -/AgentsEvent.class -/AgiExecEvent.class -/AlarmClearEvent.class -/AlarmEvent.class -/AsyncAgiEvent.class -/BridgeEvent.class -/BridgeExecEvent.class -/CdrEvent.class -/ChanSpyStartEvent.class -/ChanSpyStopEvent.class -/ChannelReloadEvent.class -/ChannelUpdateEvent.class -/ConfbridgeEndEvent.class -/ConfbridgeJoinEvent.class -/ConfbridgeLeaveEvent.class -/ConfbridgeListCompleteEvent.class -/ConfbridgeListEvent.class -/ConfbridgeListRoomsCompleteEvent.class -/ConfbridgeListRoomsEvent.class -/ConfbridgeStartEvent.class -/ConfbridgeTalkingEvent.class -/ConnectEvent.class -/CoreShowChannelEvent.class -/CoreShowChannelsCompleteEvent.class -/DAHDIChannelEvent.class -/DahdiShowChannelsCompleteEvent.class -/DahdiShowChannelsEvent.class -/DbGetResponseEvent.class -/DialEvent.class -/DisconnectEvent.class -/DndStateEvent.class -/DongleCENDEvent.class -/DongleCallStateChangeEvent.class -/DongleDeviceEntryEvent.class -/DongleNewCMGREvent.class -/DongleNewSMSBase64Event.class -/DongleNewSMSEvent.class -/DongleShowDevicesCompleteEvent.class -/DongleStatusEvent.class -/DtmfEvent.class -/ExtensionStatusEvent.class -/FaxDocumentStatusEvent.class -/FaxReceivedEvent.class -/FaxStatusEvent.class -/FullyBootedEvent.class -/HangupEvent.class -/HangupRequestEvent.class -/HoldEvent.class -/HoldedCallEvent.class -/JabberEventEvent.class -/JitterBufStatsEvent.class -/JoinEvent.class -/LeaveEvent.class -/LinkEvent.class -/ListDialplanEvent.class -/LogChannelEvent.class -/ManagerEvent.class -/MasqueradeEvent.class -/MeetMeEndEvent.class -/MeetMeJoinEvent.class -/MeetMeLeaveEvent.class -/MeetMeMuteEvent.class -/MeetMeStopTalkingEvent.class -/MeetMeTalkingEvent.class -/MeetMeTalkingRequestEvent.class -/MessageWaitingEvent.class -/ModuleLoadReportEvent.class -/MonitorStartEvent.class -/MonitorStopEvent.class -/MusicOnHoldEvent.class -/NewAccountCodeEvent.class -/NewCallerIdEvent.class -/NewChannelEvent.class -/NewExtenEvent.class -/NewStateEvent.class -/OriginateFailureEvent.class -/OriginateResponseEvent.class -/OriginateSuccessEvent.class -/ParkedCallEvent.class -/ParkedCallGiveUpEvent.class -/ParkedCallTimeOutEvent.class -/ParkedCallsCompleteEvent.class -/PeerEntryEvent.class -/PeerStatusEvent.class -/PeerlistCompleteEvent.class -/PriEventEvent.class -/ProtocolIdentifierReceivedEvent.class -/QueueCallerAbandonEvent.class -/QueueEntryEvent.class -/QueueEvent.class -/QueueMemberAddedEvent.class -/QueueMemberEvent.class -/QueueMemberPausedEvent.class -/QueueMemberPenaltyEvent.class -/QueueMemberRemovedEvent.class -/QueueMemberStatusEvent.class -/QueueParamsEvent.class -/QueueStatusCompleteEvent.class -/QueueSummaryCompleteEvent.class -/QueueSummaryEvent.class -/ReceiveFaxEvent.class -/RegistrationsCompleteEvent.class -/RegistryEntryEvent.class -/RegistryEvent.class -/ReloadEvent.class -/RenameEvent.class -/ResponseEvent.class -/RtcpReceivedEvent.class -/RtcpSentEvent.class -/RtpReceiverStatEvent.class -/RtpSenderStatEvent.class -/SendFaxEvent.class -/SendFaxStatusEvent.class -/ShowDialplanCompleteEvent.class -/ShutdownEvent.class -/SkypeAccountStatusEvent.class -/SkypeBuddyEntryEvent.class -/SkypeBuddyListCompleteEvent.class -/SkypeBuddyStatusEvent.class -/SkypeChatMessageEvent.class -/SkypeLicenseEvent.class -/SkypeLicenseListCompleteEvent.class -/SoftHangupRequestEvent.class -/StatusCompleteEvent.class -/StatusEvent.class -/T38FaxStatusEvent.class -/TransferEvent.class -/UnholdEvent.class -/UnlinkEvent.class -/UnparkedCallEvent.class -/UserEvent.class -/VarSetEvent.class -/VoicemailUserEntryCompleteEvent.class -/VoicemailUserEntryEvent.class -/ZapShowChannelsCompleteEvent.class -/ZapShowChannelsEvent.class -/AbstractBridgeEvent.class -/AgiExecEndEvent.class -/AgiExecStartEvent.class -/AsyncAgiEndEvent.class -/AsyncAgiExecEvent.class -/AsyncAgiStartEvent.class -/BlindTransferEvent.class -/BridgeCreateEvent.class -/BridgeDestroyEvent.class -/BridgeEnterEvent.class -/BridgeLeaveEvent.class -/ChallengeSentEvent.class -/DeviceStateChangeEvent.class -/DialBeginEvent.class -/DialEndEvent.class -/DtmfBeginEvent.class -/DtmfEndEvent.class -/InvalidPasswordEvent.class -/MusicOnHoldStartEvent.class -/MusicOnHoldStopEvent.class -/NewConnectedLineEvent.class -/SuccessfulAuthEvent.class -/ChallengeResponseFailedEvent.class diff --git a/src/main/java/org/asteriskjava/manager/event/AbstractAgentEvent.java b/src/main/java/org/asteriskjava/manager/event/AbstractAgentEvent.java index 2d6a6a6b2..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,13 +83,11 @@ 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; } @@ -108,13 +98,11 @@ public void setMember(String member) * * @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 index a727ea969..9a1353405 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractBridgeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractBridgeEvent.java @@ -3,10 +3,9 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public abstract class AbstractBridgeEvent extends ManagerEvent -{ +public abstract class AbstractBridgeEvent extends ManagerEvent { /** - * + * */ private static final long serialVersionUID = 1L; private String bridgeUniqueId; @@ -16,90 +15,82 @@ public abstract class AbstractBridgeEvent extends ManagerEvent private String bridgeName; private String bridgeTechnology; private String accountCode; - private String bridgevideosourcemode; + private String bridgeVideoSource; + private String bridgeVideoSourceMode; - AbstractBridgeEvent(Object source) - { + AbstractBridgeEvent(Object source) { super(source); } - public String getBridgeUniqueId() - { + public String getBridgeUniqueId() { return bridgeUniqueId; } - public void setBridgeUniqueId(String bridgeUniqueId) - { + public void setBridgeUniqueId(String bridgeUniqueId) { this.bridgeUniqueId = bridgeUniqueId; } - public String getBridgeType() - { + public String getBridgeType() { return bridgeType; } - public void setBridgeType(String bridgeType) - { + public void setBridgeType(String bridgeType) { this.bridgeType = bridgeType; } - public Integer getBridgeNumChannels() - { + public Integer getBridgeNumChannels() { return bridgeNumChannels; } - public void setBridgeNumChannels(Integer bridgeNumChannels) - { + public void setBridgeNumChannels(Integer bridgeNumChannels) { this.bridgeNumChannels = bridgeNumChannels; } - public String getBridgeCreator() - { + public String getBridgeCreator() { return bridgeCreator; } - public void setBridgeCreator(String bridgeCreator) - { + public void setBridgeCreator(String bridgeCreator) { this.bridgeCreator = bridgeCreator; } - public String getBridgeName() - { + public String getBridgeName() { return bridgeName; } - public void setBridgeName(String bridgeName) - { + public void setBridgeName(String bridgeName) { this.bridgeName = bridgeName; } - public String getBridgeTechnology() - { + public String getBridgeTechnology() { return bridgeTechnology; } - public void setBridgeTechnology(String bridgeTechnology) - { + public void setBridgeTechnology(String bridgeTechnology) { this.bridgeTechnology = bridgeTechnology; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - public String getBridgevideosourcemode() - { - return bridgevideosourcemode; + public String getBridgeVideoSource() { + return bridgeVideoSource; } - public void setBridgevideosourcemode(String bridgevideosourcemode) - { - this.bridgevideosourcemode = bridgevideosourcemode; + 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 f31bfc45e..198991978 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractChannelEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractChannelEvent.java @@ -18,12 +18,11 @@ /** * 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. */ @@ -41,38 +40,33 @@ public abstract class AbstractChannelEvent extends ManagerEvent */ 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; } @@ -81,24 +75,22 @@ public final void setUniqueId(String uniqueId) * has been set. * * @return the Caller*ID - * @deprecated * @see #getCallerIdNum() + * @deprecated */ @Deprecated - public final String getCallerId() - { + 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) - { + public final void setCallerId(String callerId) { setCallerIdNum(callerId); } @@ -109,39 +101,33 @@ public final void setCallerId(String callerId) * @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. - * + * * @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() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String 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 abb46d710..b441be2f5 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractChannelStateEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractChannelStateEvent.java @@ -23,15 +23,13 @@ * @author srt * @version $Id$ */ -public abstract class AbstractChannelStateEvent extends AbstractChannelEvent -{ +public abstract class AbstractChannelStateEvent extends AbstractChannelEvent { /** * Serializable version identifier. */ static final long serialVersionUID = 0L; - protected AbstractChannelStateEvent(Object source) - { + protected AbstractChannelStateEvent(Object source) { super(source); } @@ -41,12 +39,11 @@ protected AbstractChannelStateEvent(Object source) * * @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()}. + * even better switch to numeric values as returned by + * {@link #getChannelState()}. */ @Deprecated - public String getState() - { + public String getState() { return getChannelStateDesc(); } @@ -57,8 +54,7 @@ public String getState() * * @param state the new state of the channel as a descriptive text. */ - public void setState(String 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 index 0240e90a2..c9a3c82f8 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractConfbridgeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractConfbridgeEvent.java @@ -1,7 +1,6 @@ package org.asteriskjava.manager.event; -public abstract class AbstractConfbridgeEvent extends AbstractChannelEvent -{ +public abstract class AbstractConfbridgeEvent extends AbstractChannelEvent { private static final long serialVersionUID = 3893862793876858636L; private String bridgeType; private String bridgeNumChannels; @@ -16,120 +15,105 @@ public abstract class AbstractConfbridgeEvent extends AbstractChannelEvent String admin; - public AbstractConfbridgeEvent(Object source) - { + public AbstractConfbridgeEvent(Object source) { super(source); } /** * @return the admin */ - public String getAdmin() - { + public String getAdmin() { return admin; } /** * @param admin the admin to set */ - public void setAdmin(String admin) - { + public void setAdmin(String admin) { this.admin = admin; } /** * @return the bridgeType */ - public String getBridgeType() - { + public String getBridgeType() { return bridgeType; } /** * @param bridgeType the bridgeType to set */ - public void setBridgeType(String bridgeType) - { + public void setBridgeType(String bridgeType) { this.bridgeType = bridgeType; } /** * @return the bridgeNumChannels */ - public String getBridgeNumChannels() - { + public String getBridgeNumChannels() { return bridgeNumChannels; } /** * @param bridgeNumChannels the bridgeNumChannels to set */ - public void setBridgeNumChannels(String bridgeNumChannels) - { + public void setBridgeNumChannels(String bridgeNumChannels) { this.bridgeNumChannels = bridgeNumChannels; } /** * @return the bridgeUniqueId */ - public String getBridgeUniqueId() - { + public String getBridgeUniqueId() { return bridgeUniqueId; } /** * @param bridgeUniqueId the bridgeUniqueId to set */ - public void setBridgeUniqueId(String bridgeUniqueId) - { + public void setBridgeUniqueId(String bridgeUniqueId) { this.bridgeUniqueId = bridgeUniqueId; } /** * @return the bridgeTechnology */ - public String getBridgeTechnology() - { + public String getBridgeTechnology() { return bridgeTechnology; } /** * @param bridgeTechnology the bridgeTechnology to set */ - public void setBridgeTechnology(String bridgeTechnology) - { + public void setBridgeTechnology(String bridgeTechnology) { this.bridgeTechnology = bridgeTechnology; } /** * @return the bridgeName */ - public String getBridgeName() - { + public String getBridgeName() { return bridgeName; } /** * @param bridgeName the bridgeName to set */ - public void setBridgeName(String bridgeName) - { + public void setBridgeName(String bridgeName) { this.bridgeName = bridgeName; } /** * @return the bridgeCreator */ - public String getBridgeCreator() - { + public String getBridgeCreator() { return bridgeCreator; } /** * @param bridgeCreator the bridgeCreator to set */ - public void setBridgeCreator(String bridgeCreator) - { + public void setBridgeCreator(String bridgeCreator) { this.bridgeCreator = bridgeCreator; } @@ -138,8 +122,7 @@ public void setBridgeCreator(String bridgeCreator) * * @param conference the id of the conference the participant left. */ - public final void setConference(String conference) - { + public final void setConference(String conference) { this.conference = conference; } @@ -148,38 +131,31 @@ public final void setConference(String conference) * * @return the id of the conference the participant left. */ - public final String getConference() - { + public final String getConference() { return conference; } - public String getBridgeVideoSourceMode() - { + public String getBridgeVideoSourceMode() { return bridgeVideoSourceMode; } - public void setBridgeVideoSourceMode(String bridgeVideoSourceMode) - { + public void setBridgeVideoSourceMode(String bridgeVideoSourceMode) { this.bridgeVideoSourceMode = bridgeVideoSourceMode; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String 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 index 7b8b8c93a..8ab2e517c 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractHoldEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractHoldEvent.java @@ -16,8 +16,7 @@ * @version $Id$ * @since 1.0.0.10 */ -public class AbstractHoldEvent extends ManagerEvent -{ +public class AbstractHoldEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -36,18 +35,17 @@ public class AbstractHoldEvent extends ManagerEvent private String uniqueId; private Boolean status; - + private String linkedId; private String language; - + /** * Creates a new HoldEvent. * * @param source */ - public AbstractHoldEvent(Object source) - { + public AbstractHoldEvent(Object source) { super(source); } @@ -56,8 +54,7 @@ public AbstractHoldEvent(Object source) * * @return channel the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -66,8 +63,7 @@ public String getChannel() * * @param channel the name of the channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -76,8 +72,7 @@ public void setChannel(String channel) * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -86,8 +81,7 @@ public String getUniqueId() * * @param uniqueId the unique id of the channel. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -95,11 +89,10 @@ public void setUniqueId(String uniqueId) * Returns whether this is a hold or unhold event. * * @return true if this a hold event, false if - * it's an unhold event. + * it's an unhold event. * @since 1.0.0 */ - public Boolean getStatus() - { + public Boolean getStatus() { return status; } @@ -107,11 +100,10 @@ public Boolean getStatus() * Returns whether this is a hold or unhold event. * * @param status true if this a hold event, false - * if it's an unhold event. + * if it's an unhold event. * @since 1.0.0 */ - public void setStatus(Boolean status) - { + public void setStatus(Boolean status) { this.status = status; } @@ -119,11 +111,10 @@ public void setStatus(Boolean status) * Returns whether this is a hold event. * * @return true if this a hold event, false if - * it's an unhold event. + * it's an unhold event. * @since 1.0.0 */ - public boolean isHold() - { + public boolean isHold() { return status != null && status; } @@ -131,41 +122,34 @@ public boolean isHold() * Returns whether this is an unhold event. * * @return true if this an unhold event, false if - * it's a hold event. + * it's a hold event. * @since 1.0.0 */ - public boolean isUnhold() - { + public boolean isUnhold() { return status != null && !status; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String 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 9a5efd0b6..cc969b029 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractMeetMeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractMeetMeEvent.java @@ -21,23 +21,24 @@ * 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; +public abstract class AbstractMeetMeEvent extends ManagerEvent { + private static final long serialVersionUID = 2L; private String channel; private String uniqueId; private String meetMe; private Integer user; + private String language; + private String accountCode; + private String linkedId; /** * @param source */ - protected AbstractMeetMeEvent(Object source) - { + protected AbstractMeetMeEvent(Object source) { super(source); } @@ -45,11 +46,10 @@ protected AbstractMeetMeEvent(Object source) * 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; } @@ -57,11 +57,10 @@ public String getChannel() * 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; } @@ -69,11 +68,10 @@ public void setChannel(String 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; } @@ -81,31 +79,28 @@ public String getUniqueId() * 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; } @@ -114,23 +109,21 @@ public void setMeetMe(String meetMe) *

      * 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() - { + 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) - { + public void setUserNum(Integer userNum) { this.setUser(userNum); } @@ -138,21 +131,59 @@ public void setUserNum(Integer 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 getUser() - { + 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 setUser(Integer 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 502e53eb6..373eae815 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractParkedCallEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractParkedCallEvent.java @@ -23,8 +23,7 @@ * @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 uniqueId; // Previously: Channel @@ -43,6 +42,7 @@ public abstract class AbstractParkedCallEvent extends ManagerEvent private String parkeeExten; private Integer parkeePriority; private String parkeeUniqueid; + private String parkeeLinkedid; // Previously: From private String parkerDialString; private String parkingLot; @@ -51,8 +51,7 @@ public abstract class AbstractParkedCallEvent extends ManagerEvent private Long parkingTimeout; private Long parkingDuration; - protected AbstractParkedCallEvent(Object source) - { + protected AbstractParkedCallEvent(Object source) { super(source); } @@ -61,8 +60,7 @@ protected AbstractParkedCallEvent(Object source) * getParkerDialString() instead */ @Deprecated - public String getFrom() - { + public String getFrom() { return getParkerDialString(); } @@ -70,8 +68,7 @@ public String getFrom() * Sets the name of the channel that parked the call. */ @Deprecated - public void setFrom(String from) - { + public void setFrom(String from) { this.setParkerDialString(from); } @@ -83,8 +80,7 @@ public void setFrom(String from) * @return the parking lot. * @since 1.0.0 */ - public String getParkingLot() - { + public String getParkingLot() { return parkingLot; } @@ -93,8 +89,7 @@ public String getParkingLot() * * @param parkingLot the parking lot. */ - public void setParkingLot(String parkingLot) - { + public void setParkingLot(String parkingLot) { this.parkingLot = parkingLot; } @@ -110,222 +105,180 @@ public void setParkingLot(String parkingLot) * * @return the unique id of the parked channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @Deprecated - public void setChannel(String channel) - { + public void setChannel(String channel) { this.setParkeeChannel(channel); } /** * use getParkeeChannel() instead - * + * * @return */ @Deprecated - public String getChannel() - { + public String getChannel() { return this.getParkeeChannel(); } - public String getParkeeChannel() - { + public String getParkeeChannel() { return parkeeChannel; } - public void setParkeeChannel(String parkeeChannel) - { + public void setParkeeChannel(String parkeeChannel) { this.parkeeChannel = parkeeChannel; } - public Integer getParkeeChannelState() - { + public Integer getParkeeChannelState() { return parkeeChannelState; } - public void setParkeeChannelState(Integer parkeeChannelState) - { + public void setParkeeChannelState(Integer parkeeChannelState) { this.parkeeChannelState = parkeeChannelState; } - public String getParkeeChannelStateDesc() - { + public String getParkeeChannelStateDesc() { return parkeeChannelStateDesc; } - public void setParkeeChannelStateDesc(String parkeeChannelStateDesc) - { + public void setParkeeChannelStateDesc(String parkeeChannelStateDesc) { this.parkeeChannelStateDesc = parkeeChannelStateDesc; } - public String getParkeeCallerIDNum() - { + public String getParkeeCallerIDNum() { return parkeeCallerIDNum; } - public void setParkeeCallerIDNum(String parkeeCallerIDNum) - { + public void setParkeeCallerIDNum(String parkeeCallerIDNum) { this.parkeeCallerIDNum = parkeeCallerIDNum; } - public String getParkeeCallerIDName() - { + public String getParkeeCallerIDName() { return parkeeCallerIDName; } - public void setParkeeCallerIDName(String parkeeCallerIDName) - { + public void setParkeeCallerIDName(String parkeeCallerIDName) { this.parkeeCallerIDName = parkeeCallerIDName; } - public String getParkeeConnectedLineNum() - { + public String getParkeeConnectedLineNum() { return parkeeConnectedLineNum; } - public void setParkeeConnectedLineNum(String parkeeConnectedLineNum) - { + public void setParkeeConnectedLineNum(String parkeeConnectedLineNum) { this.parkeeConnectedLineNum = parkeeConnectedLineNum; } - public String getParkeeConnectedLineName() - { + public String getParkeeConnectedLineName() { return parkeeConnectedLineName; } - public void setParkeeConnectedLineName(String parkeeConnectedLineName) - { + public void setParkeeConnectedLineName(String parkeeConnectedLineName) { this.parkeeConnectedLineName = parkeeConnectedLineName; } - public String getParkeeLanguage() - { + public String getParkeeLanguage() { return parkeeLanguage; } - public void setParkeeLanguage(String parkeeLanguage) - { + public void setParkeeLanguage(String parkeeLanguage) { this.parkeeLanguage = parkeeLanguage; } - public String getParkeeAccountCode() - { + public String getParkeeAccountCode() { return parkeeAccountCode; } - public void setParkeeAccountCode(String parkeeAccountCode) - { + public void setParkeeAccountCode(String parkeeAccountCode) { this.parkeeAccountCode = parkeeAccountCode; } - public String getParkeeContext() - { + public String getParkeeContext() { return parkeeContext; } - public void setParkeeContext(String parkeeContext) - { + public void setParkeeContext(String parkeeContext) { this.parkeeContext = parkeeContext; } - public String getParkeeExten() - { + public String getParkeeExten() { return parkeeExten; } - public void setParkeeExten(String parkeeExten) - { + public void setParkeeExten(String parkeeExten) { this.parkeeExten = parkeeExten; } - public Integer getParkeePriority() - { + public Integer getParkeePriority() { return parkeePriority; } - public void setParkeePriority(Integer parkeePriority) - { + public void setParkeePriority(Integer parkeePriority) { this.parkeePriority = parkeePriority; } - public String getParkeeUniqueid() - { + public String getParkeeUniqueid() { return parkeeUniqueid; } - public void setParkeeUniqueid(String parkeeUniqueid) - { + public void setParkeeUniqueid(String parkeeUniqueid) { this.parkeeUniqueid = parkeeUniqueid; } - public String getParkerDialString() - { - return parkerDialString; + public String getParkeeLinkedid() { + return parkeeLinkedid; } - public void setParkerDialString(String parkerDialString) - { - this.parkerDialString = parkerDialString; + public void setParkeeLinkedid(String parkeeLinkedid) { + this.parkeeLinkedid = parkeeLinkedid; } - public String getParkinglot() - { - return parkingLot; + public String getParkerDialString() { + return parkerDialString; } - public void setParkinglot(String parkinglot) - { - this.parkingLot = parkinglot; + public void setParkerDialString(String parkerDialString) { + this.parkerDialString = parkerDialString; } - public String getParkingSpace() - { + public String getParkingSpace() { return parkingSpace; } - public void setParkingSpace(String parkingSpace) - { + public void setParkingSpace(String parkingSpace) { this.parkingSpace = parkingSpace; } - public Long getParkingTimeout() - { + public Long getParkingTimeout() { return parkingTimeout; } - public void setParkingTimeout(Long parkingTimeout) - { + public void setParkingTimeout(Long parkingTimeout) { this.parkingTimeout = parkingTimeout; } - public Long getParkingDuration() - { + public Long getParkingDuration() { return parkingDuration; } - public void setParkingDuration(Long parkingDuration) - { + public void setParkingDuration(Long parkingDuration) { this.parkingDuration = parkingDuration; } @Deprecated - public String getCallerId() - { + public String getCallerId() { return getParkeeCallerIDNum(); } @Deprecated - public void setCallerId(String callerId) - { + 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 3ad13f6c9..b03360fab 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractQueueMemberEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractQueueMemberEvent.java @@ -18,13 +18,12 @@ /** * 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 */ @@ -38,49 +37,44 @@ public abstract class AbstractQueueMemberEvent extends ManagerEvent /** * @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() - { + 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) - { + final public void setInterface(String _interface) { this._interface = _interface; } @@ -88,28 +82,23 @@ final public void setInterface(String _interface) * Returns the name of the member's interface.

      * E.g. the channel name or agent group. * - * @deprecated since Asterisk 12 - * * @return the name of the member's interface. + * @deprecated since Asterisk 12 */ @Deprecated - final public String getLocation() - { + final public String getLocation() { return _interface; } /** * Sets the name of the member's interface. * - * @deprecated since Asterisk 12 - * * @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 + final public void setLocation(String _interface) { + if ((_interface != null) && (!"null".equals(_interface))) { // Location is not in use since asterisk 12 this._interface = _interface; } } @@ -118,12 +107,11 @@ final public void setLocation(String _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; } @@ -131,32 +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() - { + public String getPausedReason() { return pausedReason; } - public void setPausedReason(String pausedReason) - { + public void setPausedReason(String pausedReason) { this.pausedReason = pausedReason; } - public String getInCall() - { + public String getInCall() { return inCall; } - public void setInCall(String 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 482e209f5..7e137214d 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractRtcpEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractRtcpEvent.java @@ -27,16 +27,14 @@ * @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); } @@ -46,13 +44,11 @@ public AbstractRtcpEvent(Object source) * * @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; } @@ -61,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; } @@ -76,94 +70,72 @@ 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; } - + //things like RTT can be float/double in the event message in newer asterisk versions - if(s.contains(".")) - { + if (s.contains(".")) { return secStringToDouble(s).longValue(); } - if (s.endsWith("(sec)")) - { + 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())); } 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; } 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 index d62a092b2..73097dd9d 100644 --- a/src/main/java/org/asteriskjava/manager/event/AbstractUnParkedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AbstractUnParkedEvent.java @@ -19,8 +19,7 @@ /** * Enro 2015-03: Asterisk 13 Support */ -public class AbstractUnParkedEvent extends AbstractParkedCallEvent -{ +public class AbstractUnParkedEvent extends AbstractParkedCallEvent { /** * Serializable version identifier */ @@ -38,132 +37,125 @@ public class AbstractUnParkedEvent extends AbstractParkedCallEvent private String parkerExten; private String parkerPriority; private String parkerUniqueid; + private String parkerLinkedid; + private String parkerLanguage; /** * @param source */ - public AbstractUnParkedEvent(Object source) - { + public AbstractUnParkedEvent(Object source) { super(source); } - public String getParkerChannel() - { + public String getParkerChannel() { return parkerChannel; } - public void setParkerChannel(String parkerChannel) - { + public void setParkerChannel(String parkerChannel) { this.parkerChannel = parkerChannel; } - public Integer getParkerChannelState() - { + public Integer getParkerChannelState() { return parkerChannelState; } - public void setParkerChannelState(Integer parkerChannelState) - { + public void setParkerChannelState(Integer parkerChannelState) { this.parkerChannelState = parkerChannelState; } - public String getParkerChannelStateDesc() - { + public String getParkerChannelStateDesc() { return parkerChannelStateDesc; } - public void setParkerChannelStateDesc(String parkerChannelStateDesc) - { + public void setParkerChannelStateDesc(String parkerChannelStateDesc) { this.parkerChannelStateDesc = parkerChannelStateDesc; } - public String getParkerCallerIDNum() - { + public String getParkerCallerIDNum() { return parkerCallerIDNum; } - public void setParkerCallerIDNum(String parkerCallerIDNum) - { + public void setParkerCallerIDNum(String parkerCallerIDNum) { this.parkerCallerIDNum = parkerCallerIDNum; } - public String getParkerCallerIDName() - { + public String getParkerCallerIDName() { return parkerCallerIDName; } - public void setParkerCallerIDName(String parkerCallerIDName) - { + public void setParkerCallerIDName(String parkerCallerIDName) { this.parkerCallerIDName = parkerCallerIDName; } - public String getParkerConnectedLineNum() - { + public String getParkerConnectedLineNum() { return parkerConnectedLineNum; } - public void setParkerConnectedLineNum(String parkerConnectedLineNum) - { + public void setParkerConnectedLineNum(String parkerConnectedLineNum) { this.parkerConnectedLineNum = parkerConnectedLineNum; } - public String getParkerConnectedLineName() - { + public String getParkerConnectedLineName() { return parkerConnectedLineName; } - public void setParkerConnectedLineName(String parkerConnectedLineName) - { + public void setParkerConnectedLineName(String parkerConnectedLineName) { this.parkerConnectedLineName = parkerConnectedLineName; } - public String getParkerAccountCode() - { + public String getParkerAccountCode() { return parkerAccountCode; } - public void setParkerAccountCode(String parkerAccountCode) - { + public void setParkerAccountCode(String parkerAccountCode) { this.parkerAccountCode = parkerAccountCode; } - public String getParkerContext() - { + public String getParkerContext() { return parkerContext; } - public void setParkerContext(String parkerContext) - { + public void setParkerContext(String parkerContext) { this.parkerContext = parkerContext; } - public String getParkerExten() - { + public String getParkerExten() { return parkerExten; } - public void setParkerExten(String parkerExten) - { + public void setParkerExten(String parkerExten) { this.parkerExten = parkerExten; } - public String getParkerPriority() - { + public String getParkerPriority() { return parkerPriority; } - public void setParkerPriority(String parkerPriority) - { + public void setParkerPriority(String parkerPriority) { this.parkerPriority = parkerPriority; } - public String getParkerUniqueid() - { + public String getParkerUniqueid() { return parkerUniqueid; } - public void setParkerUniqueid(String 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 8b9fde797..29b863d29 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentCalledEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentCalledEvent.java @@ -27,13 +27,12 @@ * @author srt * @version $Id$ */ -public class AgentCalledEvent extends ManagerEvent -{ +public class AgentCalledEvent extends ManagerEvent { /** * Serializable version identifier. */ private static final long serialVersionUID = 2L; - + private String queue; private String agentCalled; private String channelCalling; @@ -56,21 +55,20 @@ public class AgentCalledEvent extends ManagerEvent 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); } @@ -82,13 +80,11 @@ public AgentCalledEvent(Object source) * @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; } @@ -98,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; } @@ -107,10 +102,9 @@ public String getAgentCalled() * Sets the member interface of the agent that has been called. * * @param agentCalled the member interface of the agent that has been - * called. + * called. */ - public void setAgentCalled(String agentCalled) - { + public void setAgentCalled(String agentCalled) { this.agentCalled = agentCalled; } @@ -124,14 +118,12 @@ public void setAgentCalled(String agentCalled) * @deprecated use {@lkink #getMemberName()} instead (asterisk 13) */ @Deprecated - public String getAgentName() - { + public String getAgentName() { return memberName; } @Deprecated - public void setAgentName(String agentName) - { + public void setAgentName(String agentName) { this.memberName = agentName; } @@ -141,8 +133,7 @@ public void setAgentName(String agentName) * * @return the name of the caller's channel. */ - public String getChannelCalling() - { + public String getChannelCalling() { return channelCalling; } @@ -151,8 +142,7 @@ 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; } @@ -164,13 +154,11 @@ public void setChannelCalling(String channelCalling) * @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; } @@ -181,8 +169,7 @@ public void setDestinationChannel(String destinationChannel) * @deprecated as of 1.0.0, use {@link #getCallerIdNum()} instead. */ @Deprecated - public String getCallerId() - { + public String getCallerId() { return callerIdNum; } @@ -191,18 +178,15 @@ public String getCallerId() * * @param callerId the Caller ID number of the caller's channel. */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerIdNum = callerId; } - public String getExtension() - { + public String getExtension() { return exten; } - public void setExtension(String extension) - { + public void setExtension(String extension) { this.exten = extension; } @@ -215,13 +199,11 @@ public void setExtension(String extension) * @return the unique id of the caller's channel. * @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; } @@ -231,13 +213,11 @@ public void setUniqueId(String uniqueId) * Available since Asterisk 13 replace agentName *

      */ - public String getMemberName() - { + public String getMemberName() { return memberName; } - public void setMemberName(String memberName) - { + public void setMemberName(String memberName) { this.memberName = memberName; } @@ -250,8 +230,7 @@ public void setMemberName(String memberName) * @return the channel variables. * @since 1.0.0 */ - public Map getVariables() - { + public Map getVariables() { return variables; } @@ -263,276 +242,237 @@ 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; } /** * @return the destExten */ - public String getDestExten() - { + public String getDestExten() { return destExten; } /** * @param destExten the destExten to set */ - public void setDestExten(String destExten) - { + public void setDestExten(String destExten) { this.destExten = destExten; } /** * @return the destChannelStateDesc */ - public String getDestChannelStateDesc() - { + public String getDestChannelStateDesc() { return destChannelStateDesc; } /** * @param destChannelStateDesc the destChannelStateDesc to set */ - public void setDestChannelStateDesc(String destChannelStateDesc) - { + public void setDestChannelStateDesc(String destChannelStateDesc) { this.destChannelStateDesc = destChannelStateDesc; } /** * @return the destUniqueId */ - public String getDestUniqueId() - { + public String getDestUniqueId() { return destUniqueId; } /** * @param destUniqueId the destUniqueId to set */ - public void setDestUniqueId(String destUniqueId) - { + public void setDestUniqueId(String destUniqueId) { this.destUniqueId = destUniqueId; } /** * @return the destConnectedLineNum */ - public String getDestConnectedLineNum() - { + public String getDestConnectedLineNum() { return destConnectedLineNum; } /** * @param destConnectedLineNum the destConnectedLineNum to set */ - public void setDestConnectedLineNum(String destConnectedLineNum) - { + public void setDestConnectedLineNum(String destConnectedLineNum) { this.destConnectedLineNum = destConnectedLineNum; } /** * @return the destCallerIdName */ - public String getDestCallerIdName() - { + public String getDestCallerIdName() { return destCallerIdName; } /** * @param destCallerIdName the destCallerIdName to set */ - public void setDestCallerIdName(String destCallerIdName) - { + public void setDestCallerIdName(String destCallerIdName) { this.destCallerIdName = destCallerIdName; } /** * @return the destCallerIdNum */ - public String getDestCallerIdNum() - { + public String getDestCallerIdNum() { return destCallerIdNum; } /** * @param destCallerIdNum the destCallerIdNum to set */ - public void setDestCallerIdNum(String destCallerIdNum) - { + public void setDestCallerIdNum(String destCallerIdNum) { this.destCallerIdNum = destCallerIdNum; } /** * @return the destContext */ - public String getDestContext() - { + public String getDestContext() { return destContext; } /** * @param destContext the destContext to set */ - public void setDestContext(String destContext) - { + public void setDestContext(String destContext) { this.destContext = destContext; } /** * @return the destPriority */ - public String getDestPriority() - { + public String getDestPriority() { return destPriority; } /** * @param destPriority the destPriority to set */ - public void setDestPriority(String destPriority) - { + public void setDestPriority(String destPriority) { this.destPriority = destPriority; } /** * @return the destChannel */ - public String getDestChannel() - { + public String getDestChannel() { return destChannel; } /** * @param destChannel the destChannel to set */ - public void setDestChannel(String destChannel) - { + public void setDestChannel(String destChannel) { this.destChannel = destChannel; } /** * @return the destChannelState */ - public String getDestChannelState() - { + public String getDestChannelState() { return destChannelState; } /** * @param destChannelState the destChannelState to set */ - public void setDestChannelState(String destChannelState) - { + public void setDestChannelState(String destChannelState) { this.destChannelState = destChannelState; } /** * @return the iface */ - public String getInterface() - { + public String getInterface() { return iface; } /** * @param iface the iface to set */ - public void setInterface(String iface) - { + public void setInterface(String iface) { this.iface = iface; } /** * @return the channel */ - public String getChannel() - { + public String getChannel() { return channel; } /** * @param channel the channel to set */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } /** * @return the destConnectedLineName */ - public String getDestConnectedLineName() - { + public String getDestConnectedLineName() { return destConnectedLineName; } /** * @param destConnectedLineName the destConnectedLineName to set */ - public void setDestConnectedLineName(String destConnectedLineName) - { + public void setDestConnectedLineName(String destConnectedLineName) { this.destConnectedLineName = destConnectedLineName; } - public String getDestAccountCode() - { + public String getDestAccountCode() { return destAccountCode; } - public void setDestAccountCode(String destAccountCode) - { + public void setDestAccountCode(String destAccountCode) { this.destAccountCode = destAccountCode; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getDestLanguage() - { + public String getDestLanguage() { return destLanguage; } - public void setDestLanguage(String destLanguage) - { + public void setDestLanguage(String destLanguage) { this.destLanguage = destLanguage; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getDestLinkedId() - { + public String getDestLinkedId() { return destLinkedId; } - public void setDestLinkedId(String destLinkedId) - { + public void setDestLinkedId(String destLinkedId) { this.destLinkedId = destLinkedId; } - public String getAccountcode() - { - return accountcode; - } + public String getAccountcode() { + return accountcode; + } - public void setAccountcode(String accountcode) - { - this.accountcode = 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 22b0c925e..77521f8e6 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentCompleteEvent.java @@ -23,13 +23,12 @@ * 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. */ @@ -51,7 +50,7 @@ public class AgentCompleteEvent extends AbstractAgentEvent private String destChannel; private String destChannelState; private String iface; - + private String destAccountCode; private String language; private String destLanguage; @@ -59,323 +58,280 @@ public class AgentCompleteEvent extends AbstractAgentEvent private String destLinkedId; private String accountCode; - public AgentCompleteEvent(Object source) - { + 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() - { + public String getDestExten() { return destExten; } /** * @param destExten the destExten to set */ - public void setDestExten(String destExten) - { + public void setDestExten(String destExten) { this.destExten = destExten; } /** * @return the destChannelStateDesc */ - public String getDestChannelStateDesc() - { + public String getDestChannelStateDesc() { return destChannelStateDesc; } /** * @param destChannelStateDesc the destChannelStateDesc to set */ - public void setDestChannelStateDesc(String destChannelStateDesc) - { + public void setDestChannelStateDesc(String destChannelStateDesc) { this.destChannelStateDesc = destChannelStateDesc; } /** * @return the destUniqueId */ - public String getDestUniqueId() - { + public String getDestUniqueId() { return destUniqueId; } /** * @param destUniqueId the destUniqueId to set */ - public void setDestUniqueId(String destUniqueId) - { + public void setDestUniqueId(String destUniqueId) { this.destUniqueId = destUniqueId; } /** * @return the destConnectedLineNum */ - public String getDestConnectedLineNum() - { + public String getDestConnectedLineNum() { return destConnectedLineNum; } /** * @param destConnectedLineNum the destConnectedLineNum to set */ - public void setDestConnectedLineNum(String destConnectedLineNum) - { + public void setDestConnectedLineNum(String destConnectedLineNum) { this.destConnectedLineNum = destConnectedLineNum; } /** * @return the destConnectedLineName */ - public String getDestConnectedLineName() - { + public String getDestConnectedLineName() { return destConnectedLineName; } /** * @param destConnectedLineName the destConnectedLineName to set */ - public void setDestConnectedLineName(String destConnectedLineName) - { + public void setDestConnectedLineName(String destConnectedLineName) { this.destConnectedLineName = destConnectedLineName; } /** * @return the destCallerIdName */ - public String getDestCallerIdName() - { + public String getDestCallerIdName() { return destCallerIdName; } /** * @param destCallerIdName the destCallerIdName to set */ - public void setDestCallerIdName(String destCallerIdName) - { + public void setDestCallerIdName(String destCallerIdName) { this.destCallerIdName = destCallerIdName; } /** * @return the destCallerIdNum */ - public String getDestCallerIdNum() - { + public String getDestCallerIdNum() { return destCallerIdNum; } /** * @param destCallerIdNum the destCallerIdNum to set */ - public void setDestCallerIdNum(String destCallerIdNum) - { + public void setDestCallerIdNum(String destCallerIdNum) { this.destCallerIdNum = destCallerIdNum; } /** * @return the destContext */ - public String getDestContext() - { + public String getDestContext() { return destContext; } /** * @param destContext the destContext to set */ - public void setDestContext(String destContext) - { + public void setDestContext(String destContext) { this.destContext = destContext; } /** * @return the destPriority */ - public String getDestPriority() - { + public String getDestPriority() { return destPriority; } /** * @param destPriority the destPriority to set */ - public void setDestPriority(String destPriority) - { + public void setDestPriority(String destPriority) { this.destPriority = destPriority; } /** * @return the destChannel */ - public String getDestChannel() - { + public String getDestChannel() { return destChannel; } /** * @param destChannel the destChannel to set */ - public void setDestChannel(String destChannel) - { + public void setDestChannel(String destChannel) { this.destChannel = destChannel; } /** * @return the destChannelState */ - public String getDestChannelState() - { + public String getDestChannelState() { return destChannelState; } /** * @param destChannelState the destChannelState to set */ - public void setDestChannelState(String destChannelState) - { + public void setDestChannelState(String destChannelState) { this.destChannelState = destChannelState; } /** * @return the iface */ - public String getInterface() - { + public String getInterface() { return iface; } /** * @param iface the iface to set */ - public void setInterface(String iface) - { + public void setInterface(String iface) { this.iface = iface; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getDestAccountCode() - { + public String getDestAccountCode() { return destAccountCode; } - public void setDestAccountCode(String destAccountCode) - { + public void setDestAccountCode(String destAccountCode) { this.destAccountCode = destAccountCode; } - public String getDestLanguage() - { + public String getDestLanguage() { return destLanguage; } - public void setDestLanguage(String destLanguage) - { + public void setDestLanguage(String destLanguage) { this.destLanguage = destLanguage; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getDestLinkedId() - { + public String getDestLinkedId() { return destLinkedId; } - public void setDestLinkedId(String destLinkedId) - { + public void setDestLinkedId(String destLinkedId) { this.destLinkedId = destLinkedId; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String 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 7cb712b16..1611041b6 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentConnectEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentConnectEvent.java @@ -22,13 +22,12 @@ * 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. */ @@ -55,31 +54,28 @@ public class AgentConnectEvent extends AbstractAgentEvent private String destLinkedId; private String destLanguage; private String language; - + private String accountcode; - public AgentConnectEvent(Object source) - { + 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; } @@ -89,23 +85,21 @@ public void setHoldTime(Long holdtime) * 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; } @@ -116,268 +110,230 @@ public void setBridgedChannel(String bridgedChannel) * Available since Asterisk 1.6. * * @return the amount of time the agent's channel was ringing before - * answered in seconds. + * 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() - { + public String getDestExten() { return destExten; } /** * @param destExten the destExten to set */ - public void setDestExten(String destExten) - { + public void setDestExten(String destExten) { this.destExten = destExten; } /** * @return the destChannelStateDesc */ - public String getDestChannelStateDesc() - { + public String getDestChannelStateDesc() { return destChannelStateDesc; } /** * @param destChannelStateDesc the destChannelStateDesc to set */ - public void setDestChannelStateDesc(String destChannelStateDesc) - { + public void setDestChannelStateDesc(String destChannelStateDesc) { this.destChannelStateDesc = destChannelStateDesc; } /** * @return the destUniqueId */ - public String getDestUniqueId() - { + public String getDestUniqueId() { return destUniqueId; } /** * @param destUniqueId the destUniqueId to set */ - public void setDestUniqueId(String destUniqueId) - { + public void setDestUniqueId(String destUniqueId) { this.destUniqueId = destUniqueId; } /** * @return the destConnectedLineNum */ - public String getDestConnectedLineNum() - { + public String getDestConnectedLineNum() { return destConnectedLineNum; } /** * @param destConnectedLineNum the destConnectedLineNum to set */ - public void setDestConnectedLineNum(String destConnectedLineNum) - { + public void setDestConnectedLineNum(String destConnectedLineNum) { this.destConnectedLineNum = destConnectedLineNum; } /** * @return the destConnectedLineName */ - public String getDestConnectedLineName() - { + public String getDestConnectedLineName() { return destConnectedLineName; } /** * @param destConnectedLineName the destConnectedLineName to set */ - public void setDestConnectedLineName(String destConnectedLineName) - { + public void setDestConnectedLineName(String destConnectedLineName) { this.destConnectedLineName = destConnectedLineName; } /** * @return the destCallerIdName */ - public String getDestCallerIdName() - { + public String getDestCallerIdName() { return destCallerIdName; } /** * @param destCallerIdName the destCallerIdName to set */ - public void setDestCallerIdName(String destCallerIdName) - { + public void setDestCallerIdName(String destCallerIdName) { this.destCallerIdName = destCallerIdName; } /** * @return the destCallerIdNum */ - public String getDestCallerIdNum() - { + public String getDestCallerIdNum() { return destCallerIdNum; } /** * @param destCallerIdNum the destCallerIdNum to set */ - public void setDestCallerIdNum(String destCallerIdNum) - { + public void setDestCallerIdNum(String destCallerIdNum) { this.destCallerIdNum = destCallerIdNum; } /** * @return the destContext */ - public String getDestContext() - { + public String getDestContext() { return destContext; } /** * @param destContext the destContext to set */ - public void setDestContext(String destContext) - { + public void setDestContext(String destContext) { this.destContext = destContext; } /** * @return the destPriority */ - public String getDestPriority() - { + public String getDestPriority() { return destPriority; } /** * @param destPriority the destPriority to set */ - public void setDestPriority(String destPriority) - { + public void setDestPriority(String destPriority) { this.destPriority = destPriority; } /** * @return the destChannel */ - public String getDestChannel() - { + public String getDestChannel() { return destChannel; } /** * @param destChannel the destChannel to set */ - public void setDestChannel(String destChannel) - { + public void setDestChannel(String destChannel) { this.destChannel = destChannel; } /** * @return the destChannelState */ - public String getDestChannelState() - { + public String getDestChannelState() { return destChannelState; } /** * @param destChannelState the destChannelState to set */ - public void setDestChannelState(String destChannelState) - { + public void setDestChannelState(String destChannelState) { this.destChannelState = destChannelState; } /** * @return the iface */ - public String getInterface() - { + public String getInterface() { return iface; } /** * @param iface the iface to set */ - public void setInterface(String iface) - { + public void setInterface(String iface) { this.iface = iface; } - - public String getDestAccountCode() - { + + public String getDestAccountCode() { return destAccountCode; } - public void setDestAccountCode(String destAccountCode) - { + public void setDestAccountCode(String destAccountCode) { this.destAccountCode = destAccountCode; } - - public String getLinkedId() - { + + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getDestLinkedId() - { + public String getDestLinkedId() { return destLinkedId; } - public void setDestLinkedId(String destLinkedId) - { + public void setDestLinkedId(String destLinkedId) { this.destLinkedId = destLinkedId; } - public String getDestLanguage() - { + public String getDestLanguage() { return destLanguage; } - public void setDestLanguage(String destLanguage) - { + public void setDestLanguage(String destLanguage) { this.destLanguage = destLanguage; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getAccountcode() - { - return accountcode; - } + public String getAccountcode() { + return accountcode; + } - public void setAccountcode(String accountcode) - { - this.accountcode = 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 ca946236f..d34f4c3a7 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentRingNoAnswerEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentRingNoAnswerEvent.java @@ -28,8 +28,7 @@ * @version $Id$ * @since 1.0.0 */ -public class AgentRingNoAnswerEvent extends AbstractAgentEvent -{ +public class AgentRingNoAnswerEvent extends AbstractAgentEvent { private static final long serialVersionUID = 2L; private Long ringtime; @@ -46,17 +45,16 @@ public class AgentRingNoAnswerEvent extends AbstractAgentEvent 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) - { + + public AgentRingNoAnswerEvent(Object source) { super(source); } @@ -65,267 +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; } /** * @return the destExten */ - public String getDestExten() - { + public String getDestExten() { return destExten; } /** * @param destExten the destExten to set */ - public void setDestExten(String destExten) - { + public void setDestExten(String destExten) { this.destExten = destExten; } /** * @return the destChannelStateDesc */ - public String getDestChannelStateDesc() - { + public String getDestChannelStateDesc() { return destChannelStateDesc; } /** * @param destChannelStateDesc the destChannelStateDesc to set */ - public void setDestChannelStateDesc(String destChannelStateDesc) - { + public void setDestChannelStateDesc(String destChannelStateDesc) { this.destChannelStateDesc = destChannelStateDesc; } /** * @return the destUniqueId */ - public String getDestUniqueId() - { + public String getDestUniqueId() { return destUniqueId; } /** * @param destUniqueId the destUniqueId to set */ - public void setDestUniqueId(String destUniqueId) - { + public void setDestUniqueId(String destUniqueId) { this.destUniqueId = destUniqueId; } /** * @return the destConnectedLineNum */ - public String getDestConnectedLineNum() - { + public String getDestConnectedLineNum() { return destConnectedLineNum; } /** * @param destConnectedLineNum the destConnectedLineNum to set */ - public void setDestConnectedLineNum(String destConnectedLineNum) - { + public void setDestConnectedLineNum(String destConnectedLineNum) { this.destConnectedLineNum = destConnectedLineNum; } /** * @return the destConnectedLineName */ - public String getDestConnectedLineName() - { + public String getDestConnectedLineName() { return destConnectedLineName; } /** * @param destConnectedLineName the destConnectedLineName to set */ - public void setDestConnectedLineName(String destConnectedLineName) - { + public void setDestConnectedLineName(String destConnectedLineName) { this.destConnectedLineName = destConnectedLineName; } /** * @return the destCallerIdName */ - public String getDestCallerIdName() - { + public String getDestCallerIdName() { return destCallerIdName; } /** * @param destCallerIdName the destCallerIdName to set */ - public void setDestCallerIdName(String destCallerIdName) - { + public void setDestCallerIdName(String destCallerIdName) { this.destCallerIdName = destCallerIdName; } /** * @return the destCallerIdNum */ - public String getDestCallerIdNum() - { + public String getDestCallerIdNum() { return destCallerIdNum; } /** * @param destCallerIdNum the destCallerIdNum to set */ - public void setDestCallerIdNum(String destCallerIdNum) - { + public void setDestCallerIdNum(String destCallerIdNum) { this.destCallerIdNum = destCallerIdNum; } /** * @return the destContext */ - public String getDestContext() - { + public String getDestContext() { return destContext; } /** * @param destContext the destContext to set */ - public void setDestContext(String destContext) - { + public void setDestContext(String destContext) { this.destContext = destContext; } /** * @return the destPriority */ - public String getDestPriority() - { + public String getDestPriority() { return destPriority; } /** * @param destPriority the destPriority to set */ - public void setDestPriority(String destPriority) - { + public void setDestPriority(String destPriority) { this.destPriority = destPriority; } /** * @return the destChannel */ - public String getDestChannel() - { + public String getDestChannel() { return destChannel; } /** * @param destChannel the destChannel to set */ - public void setDestChannel(String destChannel) - { + public void setDestChannel(String destChannel) { this.destChannel = destChannel; } /** * @return the destChannelState */ - public String getDestChannelState() - { + public String getDestChannelState() { return destChannelState; } /** * @param destChannelState the destChannelState to set */ - public void setDestChannelState(String destChannelState) - { + public void setDestChannelState(String destChannelState) { this.destChannelState = destChannelState; } /** * @return the iface */ - public String getInterface() - { + public String getInterface() { return iface; } /** * @param iface the iface to set */ - public void setInterface(String iface) - { + public void setInterface(String iface) { this.iface = iface; } - public String getDestAccountCode() - { + public String getDestAccountCode() { return destAccountCode; } - public void setDestAccountCode(String destAccountCode) - { + public void setDestAccountCode(String destAccountCode) { this.destAccountCode = destAccountCode; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getDestLanguage() - { + public String getDestLanguage() { return destLanguage; } - public void setDestLanguage(String destLanguage) - { + public void setDestLanguage(String destLanguage) { this.destLanguage = destLanguage; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getDestLinkedId() - { + public String getDestLinkedId() { return destLinkedId; } - public void setDestLinkedId(String destLinkedId) - { + public void setDestLinkedId(String destLinkedId) { this.destLinkedId = destLinkedId; } - public String getAccountcode() - { - return accountcode; - } + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = 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 b48cde5bd..c4ab8553b 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgentsCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgentsCompleteEvent.java @@ -20,14 +20,13 @@ * 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 */ @@ -35,33 +34,28 @@ public class AgentsCompleteEvent extends ResponseEvent private Integer listItems; private String eventList; - + /** * @param source */ - public AgentsCompleteEvent(Object source) - { + public AgentsCompleteEvent(Object source) { super(source); } - public Integer getListItems() - { + public Integer getListItems() { return listItems; } - public void setListItems(Integer listItems) - { + public void setListItems(Integer listItems) { this.listItems = listItems; } - 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/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 index 7d757b7b5..5a2910883 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgiExecEndEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgiExecEndEvent.java @@ -3,16 +3,34 @@ /** * Created by plhk on 1/15/15. */ -public class AgiExecEndEvent extends AgiExecEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; - - public AgiExecEndEvent(Object source) - { - super(source); - setSubEvent(SUB_EVENT_END); - } +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 4fc78bf87..aa44573e3 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgiExecEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgiExecEvent.java @@ -17,228 +17,207 @@ * @version $Id$ * @since 1.0.0 */ -public class AgiExecEvent extends ManagerEvent -{ - /** - * Serializable version identifier. - */ - static final long serialVersionUID = 0L; - - /** - * Execution of an AGI command has started. - */ - public static final String SUB_EVENT_START = "Start"; - - /** - * Execution of an AGI command has finished. - */ - public static final String SUB_EVENT_END = "End"; - - private String channel; - private String subEvent; - private String commandId; - 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) - { - super(source); - } - - /** - * Returns the name of the channel this event occurred on. - * - * @return the name of the channel this event occurred on. - */ - public String getChannel() - { - return channel; - } - - /** - * Sets the name of the channel this event occurred on. - * - * @param channel the name of the channel this event occurred on. - */ - public void setChannel(String channel) - { - this.channel = channel; - } - - /** - * Returns the sub event type. This is either "Start" or "End". - * - * @return the sub event type. - * @see #SUB_EVENT_START - * @see #SUB_EVENT_END - */ - public String getSubEvent() - { - return subEvent; - } - - /** - * Sets the sub event type. - * - * @param subEvent the sub event type. - */ - 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. - * - * @return the command id. - */ - public String getCommandId() - { - return commandId; - } - - /** - * Sets the command id. - * - * @param commandId the command id. - */ - public void setCommandId(String commandId) - { - this.commandId = commandId; - } - - /** - * Returns the AGI command. - * - * @return the AGI command. - */ - public String getCommand() - { - return command; - } - - /** - * Sets the AGI command. - * - * @param command the AGI command. - */ - public void setCommand(String command) - { - this.command = command; - } - - /** - * Returns the result code. - * - * @return the result code. - */ - public Integer getResultCode() - { - return resultCode; - } - - /** - * Sets the result code. - * - * @param resultCode the result code. - */ - 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.

      - * Possible values are: - *

        - *
      • Failure (corresponds to result code -1)
      • - *
      • Success (corresponds to result code 200)
      • - *
      • KeepAlive (corresponds to result code 210)
      • - *
      • Command not permitted on a dead channel (corresponds to result code 511)
      • - *
      • Usage (corresponds to result code 520)
      • - *
      - * - * @return a string respresentation of the result. - */ - public String getResult() - { - return result; - } - - /** - * Sets the string respresentation of the result. - * - * @param result a string respresentation of the 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() - { - return isSubEvent(SUB_EVENT_START); - } - - /** - * Checks is this an end sub event. - * - * @return true if this is an "End" sub event, false otherwise. - */ - public boolean isEnd() - { - return isSubEvent(SUB_EVENT_END); - } - - private boolean isSubEvent(String subEvent) - { - return this.subEvent != null && this.subEvent.equalsIgnoreCase(subEvent); - } +public class AgiExecEvent extends ManagerEvent { + /** + * Serializable version identifier. + */ + static final long serialVersionUID = 0L; + + /** + * Execution of an AGI command has started. + */ + public static final String SUB_EVENT_START = "Start"; + + /** + * Execution of an AGI command has finished. + */ + public static final String SUB_EVENT_END = "End"; + + private String channel; + private String subEvent; + private String commandId; + 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) { + super(source); + } + + /** + * Returns the name of the channel this event occurred on. + * + * @return the name of the channel this event occurred on. + */ + public String getChannel() { + return channel; + } + + /** + * Sets the name of the channel this event occurred on. + * + * @param channel the name of the channel this event occurred on. + */ + public void setChannel(String channel) { + this.channel = channel; + } + + /** + * Returns the sub event type. This is either "Start" or "End". + * + * @return the sub event type. + * @see #SUB_EVENT_START + * @see #SUB_EVENT_END + */ + public String getSubEvent() { + return subEvent; + } + + /** + * Sets the sub event type. + * + * @param subEvent the sub event type. + */ + 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. + * + * @return the command id. + */ + public String getCommandId() { + return commandId; + } + + /** + * Sets the command id. + * + * @param commandId the command id. + */ + public void setCommandId(String commandId) { + this.commandId = commandId; + } + + /** + * Returns the AGI command. + * + * @return the AGI command. + */ + public String getCommand() { + return command; + } + + /** + * Sets the AGI command. + * + * @param command the AGI command. + */ + public void setCommand(String command) { + this.command = command; + } + + /** + * Returns the result code. + * + * @return the result code. + */ + public Integer getResultCode() { + return resultCode; + } + + /** + * Sets the result code. + * + * @param resultCode the result code. + */ + 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.

      + * Possible values are: + *

        + *
      • Failure (corresponds to result code -1)
      • + *
      • Success (corresponds to result code 200)
      • + *
      • KeepAlive (corresponds to result code 210)
      • + *
      • Command not permitted on a dead channel (corresponds to result code 511)
      • + *
      • Usage (corresponds to result code 520)
      • + *
      + * + * @return a string respresentation of the result. + */ + public String getResult() { + return result; + } + + /** + * Sets the string respresentation of the result. + * + * @param result a string respresentation of the 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() { + return isSubEvent(SUB_EVENT_START); + } + + /** + * Checks is this an end sub event. + * + * @return true if this is an "End" sub event, false otherwise. + */ + public boolean isEnd() { + return isSubEvent(SUB_EVENT_END); + } + + private boolean isSubEvent(String subEvent) { + return this.subEvent != null && this.subEvent.equalsIgnoreCase(subEvent); + } } diff --git a/src/main/java/org/asteriskjava/manager/event/AgiExecStartEvent.java b/src/main/java/org/asteriskjava/manager/event/AgiExecStartEvent.java index a2d483cc3..6b2a4e5a9 100644 --- a/src/main/java/org/asteriskjava/manager/event/AgiExecStartEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AgiExecStartEvent.java @@ -3,16 +3,34 @@ /** * Created by plhk on 1/15/15. */ -public class AgiExecStartEvent extends AgiExecEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; - - public AgiExecStartEvent(Object source) - { - super(source); - setSubEvent(SUB_EVENT_START); - } +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 index bdf91332c..537eb4ced 100644 --- a/src/main/java/org/asteriskjava/manager/event/AntennaLevelEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AntennaLevelEvent.java @@ -2,23 +2,23 @@ public class AntennaLevelEvent extends AbstractChannelEvent { - /** - * - */ - private static final long serialVersionUID = 7687745700915865011L; + /** + * + */ + private static final long serialVersionUID = 7687745700915865011L; - private String signal; - - public AntennaLevelEvent(Object source) { - super(source); - } + private String signal; - public String getSignal() { - return signal; - } + public AntennaLevelEvent(Object source) { + super(source); + } - public void setSignal(String signal) { - this.signal = signal; - } + 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..fa8f8cd8a --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/AorDetail.java @@ -0,0 +1,188 @@ +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; + + 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; + } + +} diff --git a/src/main/java/org/asteriskjava/manager/event/AsyncAgiEndEvent.java b/src/main/java/org/asteriskjava/manager/event/AsyncAgiEndEvent.java index 944f79340..070394dad 100644 --- a/src/main/java/org/asteriskjava/manager/event/AsyncAgiEndEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AsyncAgiEndEvent.java @@ -3,16 +3,14 @@ /** * Created by plhk on 1/15/15. */ -public class AsyncAgiEndEvent extends AsyncAgiEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; +public class AsyncAgiEndEvent extends AsyncAgiEvent { + /** + * + */ + private static final long serialVersionUID = 1L; - public AsyncAgiEndEvent(Object source) - { - super(source); - setSubEvent(SUB_EVENT_END); - } + 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 ac25a9be2..deeff2bf8 100644 --- a/src/main/java/org/asteriskjava/manager/event/AsyncAgiEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AsyncAgiEvent.java @@ -7,7 +7,6 @@ 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.
    • @@ -24,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. */ @@ -55,8 +53,7 @@ public void setUniqueId(String uniqueId) { * * @param source */ - public AsyncAgiEvent(Object source) - { + public AsyncAgiEvent(Object source) { super(source); } @@ -65,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; } @@ -75,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; } @@ -85,8 +80,7 @@ public void setChannel(String channel) * * @return the sub event type. */ - public String getSubEvent() - { + public String getSubEvent() { return subEvent; } @@ -95,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; } @@ -107,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; } @@ -117,8 +109,7 @@ public String getCommandId() * * @param commandId the command id. */ - public void setCommandId(String commandId) - { + public void setCommandId(String commandId) { this.commandId = commandId; } @@ -134,8 +125,7 @@ public void setCommandId(String commandId) * * @return the URL encoded result. */ - public String getResult() - { + public String getResult() { return result; } @@ -144,8 +134,7 @@ public String getResult() * * @return the decoded result. */ - public List decodeResult() - { + public List decodeResult() { return decode(getResult()); } @@ -154,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; } @@ -177,8 +165,7 @@ public void setResult(String result) * * @return the URL encoded AGI environment. */ - public String getEnv() - { + public String getEnv() { return env; } @@ -186,30 +173,24 @@ 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) - { + private List decode(String s) { final List result = new ArrayList<>(); - if (s == null) - { + if (s == null) { return result; } - try - { + try { final String decodedString = URLDecoder.decode(s, "UTF-8"); result.addAll(Arrays.asList(decodedString.split("\n"))); - } - catch (UnsupportedEncodingException e) - { + } catch (UnsupportedEncodingException e) { throw new RuntimeException("This JDK does not support UTF-8 encoding", e); } @@ -221,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; } @@ -231,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); } @@ -241,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); } @@ -251,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 index adde1cca7..161188d73 100644 --- a/src/main/java/org/asteriskjava/manager/event/AsyncAgiExecEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AsyncAgiExecEvent.java @@ -3,16 +3,14 @@ /** * Created by plhk on 1/15/15. */ -public class AsyncAgiExecEvent extends AsyncAgiEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; +public class AsyncAgiExecEvent extends AsyncAgiEvent { + /** + * + */ + private static final long serialVersionUID = 1L; - public AsyncAgiExecEvent(Object source) - { - super(source); - setSubEvent(SUB_EVENT_EXEC); - } + 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 index 1e924079a..fabfd4575 100644 --- a/src/main/java/org/asteriskjava/manager/event/AsyncAgiStartEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AsyncAgiStartEvent.java @@ -3,16 +3,14 @@ /** * Created by plhk on 1/15/15. */ -public class AsyncAgiStartEvent extends AsyncAgiEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; +public class AsyncAgiStartEvent extends AsyncAgiEvent { + /** + * + */ + private static final long serialVersionUID = 1L; - public AsyncAgiStartEvent(Object source) - { - super(source); - setSubEvent(SUB_EVENT_START); - } + 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 index 07778bf76..a5a9b31ac 100644 --- a/src/main/java/org/asteriskjava/manager/event/AttendedTransferEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/AttendedTransferEvent.java @@ -2,7 +2,7 @@ /** * Raised when attended transfer is complete - * + *

      * https://wiki.asterisk.org/wiki/display/AST/Asterisk+13+ManagerEvent_AttendedTransfer */ public class AttendedTransferEvent extends AbstractBridgeEvent { @@ -112,1008 +112,807 @@ public class AttendedTransferEvent extends AbstractBridgeEvent { private String secondTransfererLinkedId; private String origTransfererLanguage; - public AttendedTransferEvent(Object source) - { + public AttendedTransferEvent(Object source) { super(source); } - public String getOrigTransfererChannel() - { + public String getOrigTransfererChannel() { return origTransfererChannel; } - public void setOrigTransfererChannel(String origTransfererChannel) - { + public void setOrigTransfererChannel(String origTransfererChannel) { this.origTransfererChannel = origTransfererChannel; } - public String getOrigTransfererChannelState() - { + public String getOrigTransfererChannelState() { return origTransfererChannelState; } - public void setOrigTransfererChannelState(String origTransfererChannelState) - { + public void setOrigTransfererChannelState(String origTransfererChannelState) { this.origTransfererChannelState = origTransfererChannelState; } - public String getOrigTransfererChannelStateDesc() - { + public String getOrigTransfererChannelStateDesc() { return origTransfererChannelStateDesc; } - public void setOrigTransfererChannelStateDesc(String origTransfererChannelStateDesc) - { + public void setOrigTransfererChannelStateDesc(String origTransfererChannelStateDesc) { this.origTransfererChannelStateDesc = origTransfererChannelStateDesc; } - public String getOrigTransfererCallerIDNum() - { + public String getOrigTransfererCallerIDNum() { return origTransfererCallerIDNum; } - public void setOrigTransfererCallerIDNum(String origTransfererCallerIDNum) - { + public void setOrigTransfererCallerIDNum(String origTransfererCallerIDNum) { this.origTransfererCallerIDNum = origTransfererCallerIDNum; } - public String getOrigTransfererCallerIDName() - { + public String getOrigTransfererCallerIDName() { return origTransfererCallerIDName; } - public void setOrigTransfererCallerIDName(String origTransfererCallerIDName) - { + public void setOrigTransfererCallerIDName(String origTransfererCallerIDName) { this.origTransfererCallerIDName = origTransfererCallerIDName; } - public String getOrigTransfererConnectedLineNum() - { + public String getOrigTransfererConnectedLineNum() { return origTransfererConnectedLineNum; } - public void setOrigTransfererConnectedLineNum(String origTransfererConnectedLineNum) - { + public void setOrigTransfererConnectedLineNum(String origTransfererConnectedLineNum) { this.origTransfererConnectedLineNum = origTransfererConnectedLineNum; } - public String getOrigTransfererConnectedLineName() - { + public String getOrigTransfererConnectedLineName() { return origTransfererConnectedLineName; } - public void setOrigTransfererConnectedLineName(String origTransfererConnectedLineName) - { + public void setOrigTransfererConnectedLineName(String origTransfererConnectedLineName) { this.origTransfererConnectedLineName = origTransfererConnectedLineName; } - public String getOrigTransfererAccountCode() - { + public String getOrigTransfererAccountCode() { return origTransfererAccountCode; } - public void setOrigTransfererAccountCode(String origTransfererAccountCode) - { + public void setOrigTransfererAccountCode(String origTransfererAccountCode) { this.origTransfererAccountCode = origTransfererAccountCode; } - public String getOrigTransfererContext() - { + public String getOrigTransfererContext() { return origTransfererContext; } - public void setOrigTransfererContext(String origTransfererContext) - { + public void setOrigTransfererContext(String origTransfererContext) { this.origTransfererContext = origTransfererContext; } - public String getOrigTransfererExten() - { + public String getOrigTransfererExten() { return origTransfererExten; } - public void setOrigTransfererExten(String origTransfererExten) - { + public void setOrigTransfererExten(String origTransfererExten) { this.origTransfererExten = origTransfererExten; } - public String getOrigTransfererPriority() - { + public String getOrigTransfererPriority() { return origTransfererPriority; } - public void setOrigTransfererPriority(String origTransfererPriority) - { + public void setOrigTransfererPriority(String origTransfererPriority) { this.origTransfererPriority = origTransfererPriority; } - public String getOrigTransfererUniqueid() - { + public String getOrigTransfererUniqueid() { return origTransfererUniqueid; } - public void setOrigTransfererUniqueid(String origTransfererUniqueid) - { + public void setOrigTransfererUniqueid(String origTransfererUniqueid) { this.origTransfererUniqueid = origTransfererUniqueid; } - public String getOrigBridgeUniqueid() - { + public String getOrigBridgeUniqueid() { return origBridgeUniqueid; } - public void setOrigBridgeUniqueid(String origBridgeUniqueid) - { + public void setOrigBridgeUniqueid(String origBridgeUniqueid) { this.origBridgeUniqueid = origBridgeUniqueid; } - public String getOrigBridgeType() - { + public String getOrigBridgeType() { return origBridgeType; } - public void setOrigBridgeType(String origBridgeType) - { + public void setOrigBridgeType(String origBridgeType) { this.origBridgeType = origBridgeType; } - public String getOrigBridgeTechnology() - { + public String getOrigBridgeTechnology() { return origBridgeTechnology; } - public void setOrigBridgeTechnology(String origBridgeTechnology) - { + public void setOrigBridgeTechnology(String origBridgeTechnology) { this.origBridgeTechnology = origBridgeTechnology; } - public String getOrigBridgeCreator() - { + public String getOrigBridgeCreator() { return origBridgeCreator; } - public void setOrigBridgeCreator(String origBridgeCreator) - { + public void setOrigBridgeCreator(String origBridgeCreator) { this.origBridgeCreator = origBridgeCreator; } - public String getOrigBridgeName() - { + public String getOrigBridgeName() { return origBridgeName; } - public void setOrigBridgeName(String origBridgeName) - { + public void setOrigBridgeName(String origBridgeName) { this.origBridgeName = origBridgeName; } - public String getOrigBridgeNumChannels() - { + public String getOrigBridgeNumChannels() { return origBridgeNumChannels; } - public void setOrigBridgeNumChannels(String origBridgeNumChannels) - { + public void setOrigBridgeNumChannels(String origBridgeNumChannels) { this.origBridgeNumChannels = origBridgeNumChannels; } - public String getSecondTransfererChannel() - { + public String getSecondTransfererChannel() { return secondTransfererChannel; } - public void setSecondTransfererChannel(String secondTransfererChannel) - { + public void setSecondTransfererChannel(String secondTransfererChannel) { this.secondTransfererChannel = secondTransfererChannel; } - public String getSecondTransfererChannelState() - { + public String getSecondTransfererChannelState() { return secondTransfererChannelState; } - public void setSecondTransfererChannelState(String secondTransfererChannelState) - { + public void setSecondTransfererChannelState(String secondTransfererChannelState) { this.secondTransfererChannelState = secondTransfererChannelState; } - public String getSecondTransfererChannelStateDesc() - { + public String getSecondTransfererChannelStateDesc() { return secondTransfererChannelStateDesc; } - public void setSecondTransfererChannelStateDesc(String secondTransfererChannelStateDesc) - { + public void setSecondTransfererChannelStateDesc(String secondTransfererChannelStateDesc) { this.secondTransfererChannelStateDesc = secondTransfererChannelStateDesc; } - public String getSecondTransfererCallerIDNum() - { + public String getSecondTransfererCallerIDNum() { return secondTransfererCallerIDNum; } - public void setSecondTransfererCallerIDNum(String secondTransfererCallerIDNum) - { + public void setSecondTransfererCallerIDNum(String secondTransfererCallerIDNum) { this.secondTransfererCallerIDNum = secondTransfererCallerIDNum; } - public String getSecondTransfererCallerIDName() - { + public String getSecondTransfererCallerIDName() { return secondTransfererCallerIDName; } - public void setSecondTransfererCallerIDName(String secondTransfererCallerIDName) - { + public void setSecondTransfererCallerIDName(String secondTransfererCallerIDName) { this.secondTransfererCallerIDName = secondTransfererCallerIDName; } - public String getSecondTransfererConnectedLineNum() - { + public String getSecondTransfererConnectedLineNum() { return secondTransfererConnectedLineNum; } - public void setSecondTransfererConnectedLineNum(String secondTransfererConnectedLineNum) - { + public void setSecondTransfererConnectedLineNum(String secondTransfererConnectedLineNum) { this.secondTransfererConnectedLineNum = secondTransfererConnectedLineNum; } - public String getSecondTransfererConnectedLineName() - { + public String getSecondTransfererConnectedLineName() { return secondTransfererConnectedLineName; } - public void setSecondTransfererConnectedLineName(String secondTransfererConnectedLineName) - { + public void setSecondTransfererConnectedLineName(String secondTransfererConnectedLineName) { this.secondTransfererConnectedLineName = secondTransfererConnectedLineName; } - public String getSecondTransfererAccountCode() - { + public String getSecondTransfererAccountCode() { return secondTransfererAccountCode; } - public void setSecondTransfererAccountCode(String secondTransfererAccountCode) - { + public void setSecondTransfererAccountCode(String secondTransfererAccountCode) { this.secondTransfererAccountCode = secondTransfererAccountCode; } - public String getSecondTransfererContext() - { + public String getSecondTransfererContext() { return secondTransfererContext; } - public void setSecondTransfererContext(String secondTransfererContext) - { + public void setSecondTransfererContext(String secondTransfererContext) { this.secondTransfererContext = secondTransfererContext; } - public String getSecondTransfererExten() - { + public String getSecondTransfererExten() { return secondTransfererExten; } - public void setSecondTransfererExten(String secondTransfererExten) - { + public void setSecondTransfererExten(String secondTransfererExten) { this.secondTransfererExten = secondTransfererExten; } - public String getSecondTransfererPriority() - { + public String getSecondTransfererPriority() { return secondTransfererPriority; } - public void setSecondTransfererPriority(String secondTransfererPriority) - { + public void setSecondTransfererPriority(String secondTransfererPriority) { this.secondTransfererPriority = secondTransfererPriority; } - public String getSecondTransfererUniqueid() - { + public String getSecondTransfererUniqueid() { return secondTransfererUniqueid; } - public void setSecondTransfererUniqueid(String secondTransfererUniqueid) - { + public void setSecondTransfererUniqueid(String secondTransfererUniqueid) { this.secondTransfererUniqueid = secondTransfererUniqueid; } - public String getSecondBridgeUniqueid() - { + public String getSecondBridgeUniqueid() { return secondBridgeUniqueid; } - public void setSecondBridgeUniqueid(String secondBridgeUniqueid) - { + public void setSecondBridgeUniqueid(String secondBridgeUniqueid) { this.secondBridgeUniqueid = secondBridgeUniqueid; } - public String getSecondBridgeType() - { + public String getSecondBridgeType() { return secondBridgeType; } - public void setSecondBridgeType(String secondBridgeType) - { + public void setSecondBridgeType(String secondBridgeType) { this.secondBridgeType = secondBridgeType; } - public String getSecondBridgeTechnology() - { + public String getSecondBridgeTechnology() { return secondBridgeTechnology; } - public void setSecondBridgeTechnology(String secondBridgeTechnology) - { + public void setSecondBridgeTechnology(String secondBridgeTechnology) { this.secondBridgeTechnology = secondBridgeTechnology; } - public String getSecondBridgeCreator() - { + public String getSecondBridgeCreator() { return secondBridgeCreator; } - public void setSecondBridgeCreator(String secondBridgeCreator) - { + public void setSecondBridgeCreator(String secondBridgeCreator) { this.secondBridgeCreator = secondBridgeCreator; } - public String getSecondBridgeName() - { + public String getSecondBridgeName() { return secondBridgeName; } - public void setSecondBridgeName(String secondBridgeName) - { + public void setSecondBridgeName(String secondBridgeName) { this.secondBridgeName = secondBridgeName; } - public String getSecondBridgeNumChannels() - { + public String getSecondBridgeNumChannels() { return secondBridgeNumChannels; } - public void setSecondBridgeNumChannels(String secondBridgeNumChannels) - { + public void setSecondBridgeNumChannels(String secondBridgeNumChannels) { this.secondBridgeNumChannels = secondBridgeNumChannels; } - public String getDestType() - { + public String getDestType() { return destType; } - public void setDestType(String destType) - { + public void setDestType(String destType) { this.destType = destType; } - public String getDestBridgeUniqueid() - { + public String getDestBridgeUniqueid() { return destBridgeUniqueid; } - public void setDestBridgeUniqueid(String destBridgeUniqueid) - { + public void setDestBridgeUniqueid(String destBridgeUniqueid) { this.destBridgeUniqueid = destBridgeUniqueid; } - public String getDestApp() - { + public String getDestApp() { return destApp; } - public void setDestApp(String destApp) - { + public void setDestApp(String destApp) { this.destApp = destApp; } - public String getLocalOneChannel() - { + public String getLocalOneChannel() { return localOneChannel; } - public void setLocalOneChannel(String localOneChannel) - { + public void setLocalOneChannel(String localOneChannel) { this.localOneChannel = localOneChannel; } - public String getLocalOneChannelState() - { + public String getLocalOneChannelState() { return localOneChannelState; } - public void setLocalOneChannelState(String localOneChannelState) - { + public void setLocalOneChannelState(String localOneChannelState) { this.localOneChannelState = localOneChannelState; } - public String getLocalOneChannelStateDesc() - { + public String getLocalOneChannelStateDesc() { return localOneChannelStateDesc; } - public void setLocalOneChannelStateDesc(String localOneChannelStateDesc) - { + public void setLocalOneChannelStateDesc(String localOneChannelStateDesc) { this.localOneChannelStateDesc = localOneChannelStateDesc; } - public String getLocalOneCallerIDNum() - { + public String getLocalOneCallerIDNum() { return localOneCallerIDNum; } - public void setLocalOneCallerIDNum(String localOneCallerIDNum) - { + public void setLocalOneCallerIDNum(String localOneCallerIDNum) { this.localOneCallerIDNum = localOneCallerIDNum; } - public String getLocalOneCallerIDName() - { + public String getLocalOneCallerIDName() { return localOneCallerIDName; } - public void setLocalOneCallerIDName(String localOneCallerIDName) - { + public void setLocalOneCallerIDName(String localOneCallerIDName) { this.localOneCallerIDName = localOneCallerIDName; } - public String getLocalOneConnectedLineNum() - { + public String getLocalOneConnectedLineNum() { return localOneConnectedLineNum; } - public void setLocalOneConnectedLineNum(String localOneConnectedLineNum) - { + public void setLocalOneConnectedLineNum(String localOneConnectedLineNum) { this.localOneConnectedLineNum = localOneConnectedLineNum; } - public String getLocalOneConnectedLineName() - { + public String getLocalOneConnectedLineName() { return localOneConnectedLineName; } - public void setLocalOneConnectedLineName(String localOneConnectedLineName) - { + public void setLocalOneConnectedLineName(String localOneConnectedLineName) { this.localOneConnectedLineName = localOneConnectedLineName; } - public String getLocalOneAccountCode() - { + public String getLocalOneAccountCode() { return localOneAccountCode; } - public void setLocalOneAccountCode(String localOneAccountCode) - { + public void setLocalOneAccountCode(String localOneAccountCode) { this.localOneAccountCode = localOneAccountCode; } - public String getLocalOneContext() - { + public String getLocalOneContext() { return localOneContext; } - public void setLocalOneContext(String localOneContext) - { + public void setLocalOneContext(String localOneContext) { this.localOneContext = localOneContext; } - public String getLocalOneExten() - { + public String getLocalOneExten() { return localOneExten; } - public void setLocalOneExten(String localOneExten) - { + public void setLocalOneExten(String localOneExten) { this.localOneExten = localOneExten; } - public String getLocalOnePriority() - { + public String getLocalOnePriority() { return localOnePriority; } - public void setLocalOnePriority(String localOnePriority) - { + public void setLocalOnePriority(String localOnePriority) { this.localOnePriority = localOnePriority; } - public String getLocalOneUniqueid() - { + public String getLocalOneUniqueid() { return localOneUniqueid; } - public void setLocalOneUniqueid(String localOneUniqueid) - { + public void setLocalOneUniqueid(String localOneUniqueid) { this.localOneUniqueid = localOneUniqueid; } - public String getLocalTwoChannel() - { + public String getLocalTwoChannel() { return localTwoChannel; } - public void setLocalTwoChannel(String localTwoChannel) - { + public void setLocalTwoChannel(String localTwoChannel) { this.localTwoChannel = localTwoChannel; } - public String getLocalTwoChannelState() - { + public String getLocalTwoChannelState() { return localTwoChannelState; } - public void setLocalTwoChannelState(String localTwoChannelState) - { + public void setLocalTwoChannelState(String localTwoChannelState) { this.localTwoChannelState = localTwoChannelState; } - public String getLocalTwoChannelStateDesc() - { + public String getLocalTwoChannelStateDesc() { return localTwoChannelStateDesc; } - public void setLocalTwoChannelStateDesc(String localTwoChannelStateDesc) - { + public void setLocalTwoChannelStateDesc(String localTwoChannelStateDesc) { this.localTwoChannelStateDesc = localTwoChannelStateDesc; } - public String getLocalTwoCallerIDNum() - { + public String getLocalTwoCallerIDNum() { return localTwoCallerIDNum; } - public void setLocalTwoCallerIDNum(String localTwoCallerIDNum) - { + public void setLocalTwoCallerIDNum(String localTwoCallerIDNum) { this.localTwoCallerIDNum = localTwoCallerIDNum; } - public String getLocalTwoCallerIDName() - { + public String getLocalTwoCallerIDName() { return localTwoCallerIDName; } - public void setLocalTwoCallerIDName(String localTwoCallerIDName) - { + public void setLocalTwoCallerIDName(String localTwoCallerIDName) { this.localTwoCallerIDName = localTwoCallerIDName; } - public String getLocalTwoConnectedLineNum() - { + public String getLocalTwoConnectedLineNum() { return localTwoConnectedLineNum; } - public void setLocalTwoConnectedLineNum(String localTwoConnectedLineNum) - { + public void setLocalTwoConnectedLineNum(String localTwoConnectedLineNum) { this.localTwoConnectedLineNum = localTwoConnectedLineNum; } - public String getLocalTwoConnectedLineName() - { + public String getLocalTwoConnectedLineName() { return localTwoConnectedLineName; } - public void setLocalTwoConnectedLineName(String localTwoConnectedLineName) - { + public void setLocalTwoConnectedLineName(String localTwoConnectedLineName) { this.localTwoConnectedLineName = localTwoConnectedLineName; } - public String getLocalTwoAccountCode() - { + public String getLocalTwoAccountCode() { return localTwoAccountCode; } - public void setLocalTwoAccountCode(String localTwoAccountCode) - { + public void setLocalTwoAccountCode(String localTwoAccountCode) { this.localTwoAccountCode = localTwoAccountCode; } - public String getLocalTwoContext() - { + public String getLocalTwoContext() { return localTwoContext; } - public void setLocalTwoContext(String localTwoContext) - { + public void setLocalTwoContext(String localTwoContext) { this.localTwoContext = localTwoContext; } - public String getLocalTwoExten() - { + public String getLocalTwoExten() { return localTwoExten; } - public void setLocalTwoExten(String localTwoExten) - { + public void setLocalTwoExten(String localTwoExten) { this.localTwoExten = localTwoExten; } - public String getLocalTwoPriority() - { + public String getLocalTwoPriority() { return localTwoPriority; } - public void setLocalTwoPriority(String localTwoPriority) - { + public void setLocalTwoPriority(String localTwoPriority) { this.localTwoPriority = localTwoPriority; } - public String getLocalTwoUniqueid() - { + public String getLocalTwoUniqueid() { return localTwoUniqueid; } - public void setLocalTwoUniqueid(String localTwoUniqueid) - { + public void setLocalTwoUniqueid(String localTwoUniqueid) { this.localTwoUniqueid = localTwoUniqueid; } - public String getDestTransfererChannel() - { + public String getDestTransfererChannel() { return destTransfererChannel; } - public void setDestTransfererChannel(String destTransfererChannel) - { + public void setDestTransfererChannel(String destTransfererChannel) { this.destTransfererChannel = destTransfererChannel; } - public String getTransfereeChannel() - { + public String getTransfereeChannel() { return transfereeChannel; } - public void setTransfereeChannel(String transfereeChannel) - { + public void setTransfereeChannel(String transfereeChannel) { this.transfereeChannel = transfereeChannel; } - public String getTransfereeChannelState() - { + public String getTransfereeChannelState() { return transfereeChannelState; } - public void setTransfereeChannelState(String transfereeChannelState) - { + public void setTransfereeChannelState(String transfereeChannelState) { this.transfereeChannelState = transfereeChannelState; } - public String getTransfereeChannelStateDesc() - { + public String getTransfereeChannelStateDesc() { return transfereeChannelStateDesc; } - public void setTransfereeChannelStateDesc(String transfereeChannelStateDesc) - { + public void setTransfereeChannelStateDesc(String transfereeChannelStateDesc) { this.transfereeChannelStateDesc = transfereeChannelStateDesc; } - public String getTransfereeCallerIDNum() - { + public String getTransfereeCallerIDNum() { return transfereeCallerIDNum; } - public void setTransfereeCallerIDNum(String transfereeCallerIDNum) - { + public void setTransfereeCallerIDNum(String transfereeCallerIDNum) { this.transfereeCallerIDNum = transfereeCallerIDNum; } - public String getTransfereeCallerIDName() - { + public String getTransfereeCallerIDName() { return transfereeCallerIDName; } - public void setTransfereeCallerIDName(String transfereeCallerIDName) - { + public void setTransfereeCallerIDName(String transfereeCallerIDName) { this.transfereeCallerIDName = transfereeCallerIDName; } - public String getTransfereeConnectedLineNum() - { + public String getTransfereeConnectedLineNum() { return transfereeConnectedLineNum; } - public void setTransfereeConnectedLineNum(String transfereeConnectedLineNum) - { + public void setTransfereeConnectedLineNum(String transfereeConnectedLineNum) { this.transfereeConnectedLineNum = transfereeConnectedLineNum; } - public String getTransfereeConnectedLineName() - { + public String getTransfereeConnectedLineName() { return transfereeConnectedLineName; } - public void setTransfereeConnectedLineName(String transfereeConnectedLineName) - { + public void setTransfereeConnectedLineName(String transfereeConnectedLineName) { this.transfereeConnectedLineName = transfereeConnectedLineName; } - public String getTransfereeAccountCode() - { + public String getTransfereeAccountCode() { return transfereeAccountCode; } - public void setTransfereeAccountCode(String transfereeAccountCode) - { + public void setTransfereeAccountCode(String transfereeAccountCode) { this.transfereeAccountCode = transfereeAccountCode; } - public String getTransfereeContext() - { + public String getTransfereeContext() { return transfereeContext; } - public void setTransfereeContext(String transfereeContext) - { + public void setTransfereeContext(String transfereeContext) { this.transfereeContext = transfereeContext; } - public String getTransfereeExten() - { + public String getTransfereeExten() { return transfereeExten; } - public void setTransfereeExten(String transfereeExten) - { + public void setTransfereeExten(String transfereeExten) { this.transfereeExten = transfereeExten; } - public String getTransfereePriority() - { + public String getTransfereePriority() { return transfereePriority; } - public void setTransfereePriority(String transfereePriority) - { + public void setTransfereePriority(String transfereePriority) { this.transfereePriority = transfereePriority; } - public String getTransfereeUniqueid() - { + public String getTransfereeUniqueid() { return transfereeUniqueid; } - public void setTransfereeUniqueid(String transfereeUniqueid) - { + public void setTransfereeUniqueid(String transfereeUniqueid) { this.transfereeUniqueid = transfereeUniqueid; } - public String getTransfereeLinkedId() - { + public String getTransfereeLinkedId() { return transfereeLinkedId; } - public void setTransfereeLinkedId(String transfereeLinkedId) - { + public void setTransfereeLinkedId(String transfereeLinkedId) { this.transfereeLinkedId = transfereeLinkedId; } - public String getTransfereeLanguage() - { + public String getTransfereeLanguage() { return transfereeLanguage; } - public void setTransfereeLanguage(String transfereeLanguage) - { + public void setTransfereeLanguage(String transfereeLanguage) { this.transfereeLanguage = transfereeLanguage; } - public String getOrigTransfererLinkedId() - { + public String getOrigTransfererLinkedId() { return origTransfererLinkedId; } - public void setOrigTransfererLinkedId(String origTransfererLinkedId) - { + public void setOrigTransfererLinkedId(String origTransfererLinkedId) { this.origTransfererLinkedId = origTransfererLinkedId; } - public String getSecondTransfererLanguage() - { + public String getSecondTransfererLanguage() { return secondTransfererLanguage; } - public void setSecondTransfererLanguage(String secondTransfererLanguage) - { + public void setSecondTransfererLanguage(String secondTransfererLanguage) { this.secondTransfererLanguage = secondTransfererLanguage; } - public String getIsexternal() - { + public String getIsexternal() { return isexternal; } - public void setIsexternal(String isexternal) - { + public void setIsexternal(String isexternal) { this.isexternal = isexternal; } - public String getResult() - { + public String getResult() { return result; } - public void setResult(String result) - { + public void setResult(String result) { this.result = result; } - public String getSecondTransfererLinkedId() - { + public String getSecondTransfererLinkedId() { return secondTransfererLinkedId; } - public void setSecondTransfererLinkedId(String secondTransfererLinkedId) - { + public void setSecondTransfererLinkedId(String secondTransfererLinkedId) { this.secondTransfererLinkedId = secondTransfererLinkedId; } - public String getOrigTransfererLanguage() - { + public String getOrigTransfererLanguage() { return origTransfererLanguage; } - public void setOrigTransfererLanguage(String origTransfererLanguage) - { + public void setOrigTransfererLanguage(String origTransfererLanguage) { this.origTransfererLanguage = origTransfererLanguage; } - public String getTransferTargetUniqueID() - { + public String getTransferTargetUniqueID() { return transferTargetUniqueID; } - public void setTransferTargetUniqueID(String transferTargetUniqueID) - { + public void setTransferTargetUniqueID(String transferTargetUniqueID) { this.transferTargetUniqueID = transferTargetUniqueID; } - public String getTransferTargetCallerIDName() - { + public String getTransferTargetCallerIDName() { return transferTargetCallerIDName; } - public void setTransferTargetCallerIDName(String transferTargetCallerIDName) - { + public void setTransferTargetCallerIDName(String transferTargetCallerIDName) { this.transferTargetCallerIDName = transferTargetCallerIDName; } - public String getSecondBridgeVideoSourceMode() - { + public String getSecondBridgeVideoSourceMode() { return secondBridgeVideoSourceMode; } - public void setSecondBridgeVideoSourceMode(String secondBridgeVideoSourceMode) - { + public void setSecondBridgeVideoSourceMode(String secondBridgeVideoSourceMode) { this.secondBridgeVideoSourceMode = secondBridgeVideoSourceMode; } - public String getTransferTargetLinkedID() - { + public String getTransferTargetLinkedID() { return transferTargetLinkedID; } - public void setTransferTargetLinkedID(String transferTargetLinkedID) - { + public void setTransferTargetLinkedID(String transferTargetLinkedID) { this.transferTargetLinkedID = transferTargetLinkedID; } - public String getTransferTargetPriority() - { + public String getTransferTargetPriority() { return transferTargetPriority; } - public void setTransferTargetPriority(String transferTargetPriority) - { + public void setTransferTargetPriority(String transferTargetPriority) { this.transferTargetPriority = transferTargetPriority; } - public String getTransferTargetCallerIDNum() - { + public String getTransferTargetCallerIDNum() { return transferTargetCallerIDNum; } - public void setTransferTargetCallerIDNum(String transferTargetCallerIDNum) - { + public void setTransferTargetCallerIDNum(String transferTargetCallerIDNum) { this.transferTargetCallerIDNum = transferTargetCallerIDNum; } - public String getOrigBridgeVideoSourceMode() - { + public String getOrigBridgeVideoSourceMode() { return origBridgeVideoSourceMode; } - public void setOrigBridgeVideoSourceMode(String origBridgeVideoSourceMode) - { + public void setOrigBridgeVideoSourceMode(String origBridgeVideoSourceMode) { this.origBridgeVideoSourceMode = origBridgeVideoSourceMode; } - public String getTransferTargetConnectedLineNum() - { + public String getTransferTargetConnectedLineNum() { return transferTargetConnectedLineNum; } - public void setTransferTargetConnectedLineNum(String transferTargetConnectedLineNum) - { + public void setTransferTargetConnectedLineNum(String transferTargetConnectedLineNum) { this.transferTargetConnectedLineNum = transferTargetConnectedLineNum; } - public String getTransferTargetChannel() - { + public String getTransferTargetChannel() { return transferTargetChannel; } - public void setTransferTargetChannel(String transferTargetChannel) - { + public void setTransferTargetChannel(String transferTargetChannel) { this.transferTargetChannel = transferTargetChannel; } - public String getTransferTargetContext() - { + public String getTransferTargetContext() { return transferTargetContext; } - public void setTransferTargetContext(String transferTargetContext) - { + public void setTransferTargetContext(String transferTargetContext) { this.transferTargetContext = transferTargetContext; } - public String getTransferTargetConnectedLineName() - { + public String getTransferTargetConnectedLineName() { return transferTargetConnectedLineName; } - public void setTransferTargetConnectedLineName(String transferTargetConnectedLineName) - { + public void setTransferTargetConnectedLineName(String transferTargetConnectedLineName) { this.transferTargetConnectedLineName = transferTargetConnectedLineName; } - public String getTransferTargetExten() - { + public String getTransferTargetExten() { return transferTargetExten; } - public void setTransferTargetExten(String transferTargetExten) - { + public void setTransferTargetExten(String transferTargetExten) { this.transferTargetExten = transferTargetExten; } - public String getTransferTargetChannelState() - { + public String getTransferTargetChannelState() { return transferTargetChannelState; } - public void setTransferTargetChannelState(String transferTargetChannelState) - { + public void setTransferTargetChannelState(String transferTargetChannelState) { this.transferTargetChannelState = transferTargetChannelState; } - public String getTransferTargetLanguage() - { + public String getTransferTargetLanguage() { return transferTargetLanguage; } - public void setTransferTargetLanguage(String transferTargetLanguage) - { + public void setTransferTargetLanguage(String transferTargetLanguage) { this.transferTargetLanguage = transferTargetLanguage; } - public String getTransferTargetAccountCode() - { + public String getTransferTargetAccountCode() { return transferTargetAccountCode; } - public void setTransferTargetAccountCode(String transferTargetAccountCode) - { + public void setTransferTargetAccountCode(String transferTargetAccountCode) { this.transferTargetAccountCode = transferTargetAccountCode; } - public String getTransferTargetChannelStateDesc() - { + public String getTransferTargetChannelStateDesc() { return transferTargetChannelStateDesc; } - public void setTransferTargetChannelStateDesc(String 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 index c5da2e206..2375944ed 100644 --- a/src/main/java/org/asteriskjava/manager/event/BlindTransferEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/BlindTransferEvent.java @@ -3,10 +3,9 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public class BlindTransferEvent extends AbstractBridgeEvent -{ +public class BlindTransferEvent extends AbstractBridgeEvent { /** - * + * */ private static final long serialVersionUID = 1L; private String transfererUniqueId; @@ -44,318 +43,255 @@ public class BlindTransferEvent extends AbstractBridgeEvent private String transfereeLanguage; private String transfereeaccountcode; - public BlindTransferEvent(Object source) - { + public BlindTransferEvent(Object source) { super(source); } - public String getTransfererUniqueId() - { + public String getTransfererUniqueId() { return transfererUniqueId; } - public void setTransfererUniqueId(String transfererUniqueId) - { + public void setTransfererUniqueId(String transfererUniqueId) { this.transfererUniqueId = transfererUniqueId; } - public String getTransfererConnectedLineNum() - { + public String getTransfererConnectedLineNum() { return transfererConnectedLineNum; } - public void setTransfererConnectedLineNum(String transfererConnectedLineNum) - { + public void setTransfererConnectedLineNum(String transfererConnectedLineNum) { this.transfererConnectedLineNum = transfererConnectedLineNum; } - public String getTransfererConnectedLineName() - { + public String getTransfererConnectedLineName() { return transfererConnectedLineName; } - public void setTransfererConnectedLineName(String transfererConnectedLineName) - { + public void setTransfererConnectedLineName(String transfererConnectedLineName) { this.transfererConnectedLineName = transfererConnectedLineName; } - public String getTransfererCallerIdName() - { + public String getTransfererCallerIdName() { return transfererCallerIdName; } - public void setTransfererCallerIdName(String transfererCallerIdName) - { + public void setTransfererCallerIdName(String transfererCallerIdName) { this.transfererCallerIdName = transfererCallerIdName; } - public String getTransfererCallerIdNum() - { + public String getTransfererCallerIdNum() { return transfererCallerIdNum; } - public void setTransfererCallerIdNum(String transfererCallerIdNum) - { + public void setTransfererCallerIdNum(String transfererCallerIdNum) { this.transfererCallerIdNum = transfererCallerIdNum; } - public String getTransfererChannel() - { + public String getTransfererChannel() { return transfererChannel; } - public void setTransfererChannel(String transfererChannel) - { + public void setTransfererChannel(String transfererChannel) { this.transfererChannel = transfererChannel; } - public String getTransfererChannelState() - { + public String getTransfererChannelState() { return transfererChannelState; } - public void setTransfererChannelState(String transfererChannelState) - { + public void setTransfererChannelState(String transfererChannelState) { this.transfererChannelState = transfererChannelState; } - public String getTransfererChannelStateDesc() - { + public String getTransfererChannelStateDesc() { return transfererChannelStateDesc; } - public void setTransfererChannelStateDesc(String transfererChannelStateDesc) - { + public void setTransfererChannelStateDesc(String transfererChannelStateDesc) { this.transfererChannelStateDesc = transfererChannelStateDesc; } - public Integer getTransfererPriority() - { + public Integer getTransfererPriority() { return transfererPriority; } - public void setTransfererPriority(Integer transfererPriority) - { + public void setTransfererPriority(Integer transfererPriority) { this.transfererPriority = transfererPriority; } - public String getTransfererContext() - { + public String getTransfererContext() { return transfererContext; } - public void setTransfererContext(String transfererContext) - { + public void setTransfererContext(String transfererContext) { this.transfererContext = transfererContext; } - public String getTransfereeUniqueId() - { + public String getTransfereeUniqueId() { return transfereeUniqueId; } - public void setTransfereeUniqueId(String transfereeUniqueId) - { + public void setTransfereeUniqueId(String transfereeUniqueId) { this.transfereeUniqueId = transfereeUniqueId; } - public String getTransfereeConnectedLineNum() - { + public String getTransfereeConnectedLineNum() { return transfereeConnectedLineNum; } - public void setTransfereeConnectedLineNum(String transfereeConnectedLineNum) - { + public void setTransfereeConnectedLineNum(String transfereeConnectedLineNum) { this.transfereeConnectedLineNum = transfereeConnectedLineNum; } - public String getTransfereeConnectedLineName() - { + public String getTransfereeConnectedLineName() { return transfereeConnectedLineName; } - public void setTransfereeConnectedLineName(String transfereeConnectedLineName) - { + public void setTransfereeConnectedLineName(String transfereeConnectedLineName) { this.transfereeConnectedLineName = transfereeConnectedLineName; } - public String getTransfereeCallerIdName() - { + public String getTransfereeCallerIdName() { return transfereeCallerIdName; } - public void setTransfereeCallerIdName(String transfereeCallerIdName) - { + public void setTransfereeCallerIdName(String transfereeCallerIdName) { this.transfereeCallerIdName = transfereeCallerIdName; } - public String getTransfereeCallerIdNum() - { + public String getTransfereeCallerIdNum() { return transfereeCallerIdNum; } - public void setTransfereeCallerIdNum(String transfereeCallerIdNum) - { + public void setTransfereeCallerIdNum(String transfereeCallerIdNum) { this.transfereeCallerIdNum = transfereeCallerIdNum; } - public String getTransfereeChannel() - { + public String getTransfereeChannel() { return transfereeChannel; } - public void setTransfereeChannel(String transfereeChannel) - { + public void setTransfereeChannel(String transfereeChannel) { this.transfereeChannel = transfereeChannel; } - public String getTransfereeChannelState() - { + public String getTransfereeChannelState() { return transfereeChannelState; } - public void setTransfereeChannelState(String transfereeChannelState) - { + public void setTransfereeChannelState(String transfereeChannelState) { this.transfereeChannelState = transfereeChannelState; } - public String getTransfereeChannelStateDesc() - { + public String getTransfereeChannelStateDesc() { return transfereeChannelStateDesc; } - public void setTransfereeChannelStateDesc(String transfereeChannelStateDesc) - { + public void setTransfereeChannelStateDesc(String transfereeChannelStateDesc) { this.transfereeChannelStateDesc = transfereeChannelStateDesc; } - public Integer getTransfereePriority() - { + public Integer getTransfereePriority() { return transfereePriority; } - public void setTransfereePriority(Integer transfereePriority) - { + public void setTransfereePriority(Integer transfereePriority) { this.transfereePriority = transfereePriority; } - public String getTransfereeContext() - { + public String getTransfereeContext() { return transfereeContext; } - public void setTransfereeContext(String transfereeContext) - { + public void setTransfereeContext(String transfereeContext) { this.transfereeContext = transfereeContext; } - public String getExtension() - { + public String getExtension() { return extension; } - public void setExtension(String extension) - { + public void setExtension(String extension) { this.extension = extension; } - public String getIsexternal() - { + public String getIsexternal() { return isexternal; } - public void setIsexternal(String isexternal) - { + public void setIsexternal(String isexternal) { this.isexternal = isexternal; } - public String getResult() - { + public String getResult() { return result; } - public void setResult(String result) - { + public void setResult(String result) { this.result = result; } - public String getTransfereeExten() - { + public String getTransfereeExten() { return transfereeExten; } - public void setTransfereeExten(String transfereeExten) - { + public void setTransfereeExten(String transfereeExten) { this.transfereeExten = transfereeExten; } - public String getTransfereeLinkedId() - { + public String getTransfereeLinkedId() { return transfereeLinkedId; } - public void setTransfereeLinkedId(String transfereeLinkedId) - { + public void setTransfereeLinkedId(String transfereeLinkedId) { this.transfereeLinkedId = transfereeLinkedId; } - public String getTransfererAccountCode() - { + public String getTransfererAccountCode() { return transfererAccountCode; } - public void setTransfererAccountCode(String transfererAccountCode) - { + public void setTransfererAccountCode(String transfererAccountCode) { this.transfererAccountCode = transfererAccountCode; } - public String getTransfererExten() - { + public String getTransfererExten() { return transfererExten; } - public void setTransfererExten(String transfererExten) - { + public void setTransfererExten(String transfererExten) { this.transfererExten = transfererExten; } - public String getTransfererLanguage() - { + public String getTransfererLanguage() { return transfererLanguage; } - public void setTransfererLanguage(String transfererLanguage) - { + public void setTransfererLanguage(String transfererLanguage) { this.transfererLanguage = transfererLanguage; } - public String getTransfererLinkedId() - { + public String getTransfererLinkedId() { return transfererLinkedId; } - public void setTransfererLinkedId(String transfererLinkedId) - { + public void setTransfererLinkedId(String transfererLinkedId) { this.transfererLinkedId = transfererLinkedId; } - public String getTransfereeLanguage() - { + public String getTransfereeLanguage() { return transfereeLanguage; } - public void setTransfereeLanguage(String transfereeLanguage) - { + public void setTransfereeLanguage(String transfereeLanguage) { this.transfereeLanguage = transfereeLanguage; } - public void setTransfereeaccountcode(String transfereeaccountcode) - { + public void setTransfereeaccountcode(String transfereeaccountcode) { this.transfereeaccountcode = transfereeaccountcode; } - public String getTransfereeaccountcode() - { + 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 index 89ad67840..b6ada6b54 100644 --- a/src/main/java/org/asteriskjava/manager/event/BridgeCreateEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/BridgeCreateEvent.java @@ -3,30 +3,28 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public class BridgeCreateEvent extends AbstractBridgeEvent -{ - private String bridgevideosourcemode; +public class BridgeCreateEvent extends AbstractBridgeEvent { + private String bridgevideosourcemode; - /** - * @param bridgevideosourcemode the bridgevideosourcemode to set - */ - public void setBridgevideosourcemode(String bridgevideosourcemode) { - this.bridgevideosourcemode = bridgevideosourcemode; - } + /** + * @param bridgevideosourcemode the bridgevideosourcemode to set + */ + public void setBridgevideosourcemode(String bridgevideosourcemode) { + this.bridgevideosourcemode = bridgevideosourcemode; + } - /** - * @return the bridgevideosourcemode - */ - public String getBridgevideosourcemode() { - return bridgevideosourcemode; - } + /** + * @return the bridgevideosourcemode + */ + public String getBridgevideosourcemode() { + return bridgevideosourcemode; + } - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + public BridgeCreateEvent(Object source) { + super(source); + } - 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 index c7de172e2..06c2d0a9d 100644 --- a/src/main/java/org/asteriskjava/manager/event/BridgeDestroyEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/BridgeDestroyEvent.java @@ -3,15 +3,13 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public class BridgeDestroyEvent extends AbstractBridgeEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; +public class BridgeDestroyEvent extends AbstractBridgeEvent { + /** + * + */ + private static final long serialVersionUID = 1L; - public BridgeDestroyEvent(Object source) - { - super(source); - } + 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 index 6128aff73..6596eaae2 100644 --- a/src/main/java/org/asteriskjava/manager/event/BridgeEnterEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/BridgeEnterEvent.java @@ -3,10 +3,9 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public class BridgeEnterEvent extends AbstractBridgeEvent -{ +public class BridgeEnterEvent extends AbstractBridgeEvent { /** - * + * */ private static final long serialVersionUID = 2L; private String uniqueId; @@ -16,58 +15,47 @@ public class BridgeEnterEvent extends AbstractBridgeEvent private String swapuniqueid; - public BridgeEnterEvent(Object source) - { + public BridgeEnterEvent(Object source) { super(source); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getSwapuniqueid() - { + public String getSwapuniqueid() { return swapuniqueid; } - public void setSwapuniqueid(String 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 872e6b9d9..c9067c4d9 100644 --- a/src/main/java/org/asteriskjava/manager/event/BridgeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/BridgeEvent.java @@ -29,8 +29,7 @@ * @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,8 +236,7 @@ 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() - { + 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() - { + 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 index 293888c8e..62cccf771 100644 --- a/src/main/java/org/asteriskjava/manager/event/BridgeLeaveEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/BridgeLeaveEvent.java @@ -3,10 +3,9 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public class BridgeLeaveEvent extends AbstractBridgeEvent -{ +public class BridgeLeaveEvent extends AbstractBridgeEvent { /** - * + * */ private static final long serialVersionUID = 1L; private String uniqueId; @@ -14,49 +13,41 @@ public class BridgeLeaveEvent extends AbstractBridgeEvent private String language; private String linkedId; - public BridgeLeaveEvent(Object source) - { + public BridgeLeaveEvent(Object source) { super(source); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String 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 index 6be462537..54c45d967 100644 --- a/src/main/java/org/asteriskjava/manager/event/BridgeMergeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/BridgeMergeEvent.java @@ -1,124 +1,121 @@ package org.asteriskjava.manager.event; -public class BridgeMergeEvent extends ManagerEvent -{ +public class BridgeMergeEvent extends ManagerEvent { private static final long serialVersionUID = 1L; - public BridgeMergeEvent(Object source) - { + public BridgeMergeEvent(Object source) { super(source); } - - private Integer fromBridgeNumChannels; - private Integer toBridgeNumChannels; - private String fromBridgeName; + + 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 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() - { + public Integer getFromBridgeNumChannels() { return fromBridgeNumChannels; } - public void setFromBridgeNumChannels(Integer fromBridgeNumChannels) - { + + public void setFromBridgeNumChannels(Integer fromBridgeNumChannels) { this.fromBridgeNumChannels = fromBridgeNumChannels; } - public Integer getToBridgeNumChannels() - { + + public Integer getToBridgeNumChannels() { return toBridgeNumChannels; } - public void setToBridgeNumChannels(Integer toBridgeNumChannels) - { + + public void setToBridgeNumChannels(Integer toBridgeNumChannels) { this.toBridgeNumChannels = toBridgeNumChannels; } - public String getFromBridgeName() - { + + public String getFromBridgeName() { return fromBridgeName; } - public void setFromBridgeName(String fromBridgeName) - { + + public void setFromBridgeName(String fromBridgeName) { this.fromBridgeName = fromBridgeName; } - public String getFromBridgeUniqueId() - { + + public String getFromBridgeUniqueId() { return fromBridgeUniqueId; } - public void setFromBridgeUniqueId(String fromBridgeUniqueId) - { + + public void setFromBridgeUniqueId(String fromBridgeUniqueId) { this.fromBridgeUniqueId = fromBridgeUniqueId; } - public String getFromBridgeCreator() - { + + public String getFromBridgeCreator() { return fromBridgeCreator; } - public void setFromBridgeCreator(String fromBridgeCreator) - { + + public void setFromBridgeCreator(String fromBridgeCreator) { this.fromBridgeCreator = fromBridgeCreator; } - public String getToBridgeName() - { + + public String getToBridgeName() { return toBridgeName; } - public void setToBridgeName(String toBridgeName) - { + + public void setToBridgeName(String toBridgeName) { this.toBridgeName = toBridgeName; } - public String getFromBridgeTechnology() - { + + public String getFromBridgeTechnology() { return fromBridgeTechnology; } - public void setFromBridgeTechnology(String fromBridgeTechnology) - { + + public void setFromBridgeTechnology(String fromBridgeTechnology) { this.fromBridgeTechnology = fromBridgeTechnology; } - public String getToBridgeUniqueId() - { + + public String getToBridgeUniqueId() { return toBridgeUniqueId; } - public void setToBridgeUniqueId(String toBridgeUniqueId) - { + + public void setToBridgeUniqueId(String toBridgeUniqueId) { this.toBridgeUniqueId = toBridgeUniqueId; } - public String getToBridgeTechnology() - { + + public String getToBridgeTechnology() { return toBridgeTechnology; } - public void setToBridgeTechnology(String toBridgeTechnology) - { + + public void setToBridgeTechnology(String toBridgeTechnology) { this.toBridgeTechnology = toBridgeTechnology; } - public String getFromBridgeType() - { + + public String getFromBridgeType() { return fromBridgeType; } - public void setFromBridgeType(String fromBridgeType) - { + + public void setFromBridgeType(String fromBridgeType) { this.fromBridgeType = fromBridgeType; } - public String getToBridgeType() - { + + public String getToBridgeType() { return toBridgeType; } - public void setToBridgeType(String toBridgeType) - { + + public void setToBridgeType(String toBridgeType) { this.toBridgeType = toBridgeType; } - public String getToBridgeCreator() - { + + public String getToBridgeCreator() { return toBridgeCreator; } - public void setToBridgeCreator(String 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 index af872505c..6eded008b 100644 --- a/src/main/java/org/asteriskjava/manager/event/CelEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/CelEvent.java @@ -1,10 +1,11 @@ package org.asteriskjava.manager.event; + /** * Raised when a Channel Event Log is generated for a channel. - * https://wiki.asterisk.org/wiki/display/AST/Asterisk+13+ManagerEvent_CEL + *

    + * Asterisk AMI Events: CEL */ -public class CelEvent extends ManagerEvent -{ +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"; @@ -22,7 +23,11 @@ public class CelEvent extends ManagerEvent 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; @@ -41,168 +46,135 @@ public class CelEvent extends ManagerEvent private String extra; private String channel; - public CelEvent(Object source) - { + public CelEvent(Object source) { super(source); } - public String getEventName() - { + public String getEventName() { return eventName; } - public void setEventName(String eventName) - { + public void setEventName(String eventName) { this.eventName = eventName; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; - } + } - public String getCallerIDani() - { + public String getCallerIDani() { return callerIDani; } - public void setCallerIDani(String callerIDani) - { + public void setCallerIDani(String callerIDani) { this.callerIDani = callerIDani; } - public String getCallerIDrdnis() - { + public String getCallerIDrdnis() { return callerIDrdnis; } - public void setCallerIDrdnis(String callerIDrdnis) - { + public void setCallerIDrdnis(String callerIDrdnis) { this.callerIDrdnis = callerIDrdnis; } - public String getCallerIDdnid() - { + public String getCallerIDdnid() { return callerIDdnid; } - public void setCallerIDdnid(String callerIDdnid) - { + public void setCallerIDdnid(String callerIDdnid) { this.callerIDdnid = callerIDdnid; } - public String getApplication() - { + public String getApplication() { return application; } - public void setApplication(String application) - { + public void setApplication(String application) { this.application = application; } - public String getAppData() - { + public String getAppData() { return appData; } - public void setAppData(String appData) - { + public void setAppData(String appData) { this.appData = appData; } - public String getEventTime() - { + public String getEventTime() { return eventTime; } - public void setEventTime(String eventTime) - { + public void setEventTime(String eventTime) { this.eventTime = eventTime; } - public String getAmaFlags() - { + public String getAmaFlags() { return amaFlags; } - public void setAmaFlags(String amaFlags) - { + public void setAmaFlags(String amaFlags) { this.amaFlags = amaFlags; } - public String getUniqueID() - { + public String getUniqueID() { return uniqueID; } - public void setUniqueID(String uniqueID) - { + public void setUniqueID(String uniqueID) { this.uniqueID = uniqueID; } - public String getLinkedID() - { + public String getLinkedID() { return linkedID; } - public void setLinkedID(String linkedID) - { + public void setLinkedID(String linkedID) { this.linkedID = linkedID; } - public String getUserField() - { + public String getUserField() { return userField; } - public void setUserField(String userField) - { + public void setUserField(String userField) { this.userField = userField; } - public String getPeer() - { + public String getPeer() { return peer; } - public void setPeer(String peer) - { + public void setPeer(String peer) { this.peer = peer; } - public String getPeerAccount() - { + public String getPeerAccount() { return peerAccount; } - public void setPeerAccount(String peerAccount) - { + public void setPeerAccount(String peerAccount) { this.peerAccount = peerAccount; } - public String getExtra() - { + public String getExtra() { return extra; } - public void setExtra(String extra) - { + public void setExtra(String extra) { this.extra = extra; } - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String 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 index 96e13050a..877facde9 100644 --- a/src/main/java/org/asteriskjava/manager/event/ChallengeResponseFailedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ChallengeResponseFailedEvent.java @@ -5,85 +5,139 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; -public class ChallengeResponseFailedEvent extends ManagerEvent -{ + +public class ChallengeResponseFailedEvent extends ManagerEvent { /** * Serializable version identifier. */ - private static final long serialVersionUID = 1L; + 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 ChallengeResponseFailedEvent(Object source) { + super(source); + } - public String getSeverity() - { + public String getSeverity() { return severity; } - public void setSeverity(String severity) - { + + public void setSeverity(String severity) { this.severity = severity; } - public String getEventversion() - { + public String getEventversion() { return eventversion; } - public void setEventversion(String eventversion) - { + + public void setEventversion(String eventversion) { this.eventversion = eventversion; } - - - public String getService() - { + + + public String getService() { return service; } - public void setService(String service) - { + + public void setService(String service) { this.service = service; } - public String getRemoteAddress() - { + public String getRemoteAddress() { return remoteaddress; } - public void setRemoteAddress(String remoteaddress) - { + + public void setRemoteAddress(String remoteaddress) { this.remoteaddress = remoteaddress; } - public String getLocalAddress() - { + public String getLocalAddress() { return localaddress; } - public void setLocalAddress(String localaddress) - { + + public void setLocalAddress(String localaddress) { this.localaddress = localaddress; } - public void setEventtv(String eventv) - { + 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()); + 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 index 348e35923..a4e9256a8 100644 --- a/src/main/java/org/asteriskjava/manager/event/ChallengeSentEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ChallengeSentEvent.java @@ -3,114 +3,112 @@ /** * Created by plhk on 1/15/15. */ -public class ChallengeSentEvent extends ManagerEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; - 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; - - 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 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 index 63bbcfd5f..bfe0bc7e8 100644 --- a/src/main/java/org/asteriskjava/manager/event/ChanSpyStartEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ChanSpyStartEvent.java @@ -17,8 +17,7 @@ package org.asteriskjava.manager.event; -public class ChanSpyStartEvent extends ManagerEvent -{ +public class ChanSpyStartEvent extends ManagerEvent { /** * Serial version identifier */ @@ -26,7 +25,7 @@ public class ChanSpyStartEvent extends ManagerEvent private String spyeeChannel; private String spyerChannel; - + private Integer spyeeChannelState; private String spyeeLinkedId; private String spyeeUniqueId; @@ -41,423 +40,305 @@ public class ChanSpyStartEvent extends ManagerEvent 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 spyerContext; private String spyerLanguage; - private String spyerChannelStateDesc; + private String spyerChannelStateDesc; private String spyerExten; private String spyerCallerIdNum; private String spyerConnectedLineNum; - private String spyerConnectedLineName; + private String spyerConnectedLineName; private String spyerCallerIdName; - - - public ChanSpyStartEvent(Object source) - { + + public ChanSpyStartEvent(Object source) { super(source); } - - public String getSpyeeChannel() - { + public String getSpyeeChannel() { return spyeeChannel; } - - public void setSpyeeChannel(String spyeeChannel) - { + public void setSpyeeChannel(String spyeeChannel) { this.spyeeChannel = spyeeChannel; } - - public String getSpyerChannel() - { + public String getSpyerChannel() { return spyerChannel; } - - public void setSpyerChannel(String spyerChannel) - { + public void setSpyerChannel(String spyerChannel) { this.spyerChannel = spyerChannel; } - - public Integer getSpyeeChannelState() - { + public Integer getSpyeeChannelState() { return spyeeChannelState; } - - public void setSpyeeChannelState(Integer spyeeChannelState) - { + public void setSpyeeChannelState(Integer spyeeChannelState) { this.spyeeChannelState = spyeeChannelState; } - - public String getSpyeeLinkedId() - { + public String getSpyeeLinkedId() { return spyeeLinkedId; } - - public void setSpyeeLinkedId(String spyeeLinkedId) - { + public void setSpyeeLinkedId(String spyeeLinkedId) { this.spyeeLinkedId = spyeeLinkedId; } - - public String getSpyeeUniqueId() - { + public String getSpyeeUniqueId() { return spyeeUniqueId; } - - public void setSpyeeUniqueId(String spyeeUniqueId) - { + public void setSpyeeUniqueId(String spyeeUniqueId) { this.spyeeUniqueId = spyeeUniqueId; } - - public String getSpyeeCallerIdNum() - { + public String getSpyeeCallerIdNum() { return spyeeCallerIdNum; } - - public void setSpyeeCallerIdNum(String spyeeCallerIdNum) - { + public void setSpyeeCallerIdNum(String spyeeCallerIdNum) { this.spyeeCallerIdNum = spyeeCallerIdNum; } - - public String getSpyeeConnectedLineName() - { + public String getSpyeeConnectedLineName() { return spyeeConnectedLineName; } - - public void setSpyeeConnectedLineName(String spyeeConnectedLineName) - { + public void setSpyeeConnectedLineName(String spyeeConnectedLineName) { this.spyeeConnectedLineName = spyeeConnectedLineName; } - - public String getSpyeeLanguage() - { + public String getSpyeeLanguage() { return spyeeLanguage; } - - public void setSpyeeLanguage(String spyeeLanguage) - { + public void setSpyeeLanguage(String spyeeLanguage) { this.spyeeLanguage = spyeeLanguage; } - - public String getSpyeeContext() - { + public String getSpyeeContext() { return spyeeContext; } - - public void setSpyeeContext(String spyeeContext) - { + public void setSpyeeContext(String spyeeContext) { this.spyeeContext = spyeeContext; } - - public String getSpyeeConnectedLineNum() - { + public String getSpyeeConnectedLineNum() { return spyeeConnectedLineNum; } - - public void setSpyeeConnectedLineNum(String spyeeConnectedLineNum) - { + public void setSpyeeConnectedLineNum(String spyeeConnectedLineNum) { this.spyeeConnectedLineNum = spyeeConnectedLineNum; } - - public String getSpyeeChannelStateDesc() - { + public String getSpyeeChannelStateDesc() { return spyeeChannelStateDesc; } - - public void setSpyeeChannelStateDesc(String spyeeChannelStateDesc) - { + public void setSpyeeChannelStateDesc(String spyeeChannelStateDesc) { this.spyeeChannelStateDesc = spyeeChannelStateDesc; } - - public String getSpyeeExten() - { + public String getSpyeeExten() { return spyeeExten; } - - public void setSpyeeExten(String spyeeExten) - { + public void setSpyeeExten(String spyeeExten) { this.spyeeExten = spyeeExten; } - - public Integer getSpyeeChannelstate() - { + public Integer getSpyeeChannelstate() { return spyeeChannelstate; } - - public void setSpyeeChannelstate(Integer spyeeChannelstate) - { + public void setSpyeeChannelstate(Integer spyeeChannelstate) { this.spyeeChannelstate = spyeeChannelstate; } - - public String getSpyeeAccountCode() - { + public String getSpyeeAccountCode() { return spyeeAccountCode; } - - public void setSpyeeAccountCode(String spyeeAccountCode) - { + public void setSpyeeAccountCode(String spyeeAccountCode) { this.spyeeAccountCode = spyeeAccountCode; } - - public Integer getSpyeePriority() - { + public Integer getSpyeePriority() { return spyeePriority; } - - public void setSpyeePriority(Integer spyeePriority) - { + public void setSpyeePriority(Integer spyeePriority) { this.spyeePriority = spyeePriority; } - - public String getSpyeeCallerIdName() - { + public String getSpyeeCallerIdName() { return spyeeCallerIdName; } - - public void setSpyeeCallerIdName(String spyeeCallerIdName) - { + public void setSpyeeCallerIdName(String spyeeCallerIdName) { this.spyeeCallerIdName = spyeeCallerIdName; } - - public String getSpyerUniqueId() - { + public String getSpyerUniqueId() { return spyerUniqueId; } - - public void setSpyerUniqueId(String spyerUniqueId) - { + public void setSpyerUniqueId(String spyerUniqueId) { this.spyerUniqueId = spyerUniqueId; } - - public String getSpyerLinkedId() - { + public String getSpyerLinkedId() { return spyerLinkedId; } - - public void setSpyerLinkedId(String spyerLinkedId) - { + public void setSpyerLinkedId(String spyerLinkedId) { this.spyerLinkedId = spyerLinkedId; } - - public Integer getSpyerChannelState() - { + public Integer getSpyerChannelState() { return spyerChannelState; } - - public void setSpyerChannelState(Integer spyerChannelState) - { + public void setSpyerChannelState(Integer spyerChannelState) { this.spyerChannelState = spyerChannelState; } - - public Integer getSpyerPriority() - { + public Integer getSpyerPriority() { return spyerPriority; } - - public void setSpyerPriority(Integer spyerPriority) - { + public void setSpyerPriority(Integer spyerPriority) { this.spyerPriority = spyerPriority; } - - public String getSpyerContext() - { + public String getSpyerContext() { return spyerContext; } - - public void setSpyerContext(String spyerContext) - { + public void setSpyerContext(String spyerContext) { this.spyerContext = spyerContext; } - - public String getSpyerLanguage() - { + public String getSpyerLanguage() { return spyerLanguage; } - - public void setSpyerLanguage(String spyerLanguage) - { + public void setSpyerLanguage(String spyerLanguage) { this.spyerLanguage = spyerLanguage; } - - public String getSpyerChannelStateDesc() - { + public String getSpyerChannelStateDesc() { return spyerChannelStateDesc; } - - public void setSpyerChannelStateDesc(String spyerChannelStateDesc) - { + public void setSpyerChannelStateDesc(String spyerChannelStateDesc) { this.spyerChannelStateDesc = spyerChannelStateDesc; } - - public String getSpyerExten() - { + public String getSpyerExten() { return spyerExten; } - - public void setSpyerExten(String spyerExten) - { + public void setSpyerExten(String spyerExten) { this.spyerExten = spyerExten; } - - public String getSpyerCallerIdNum() - { + public String getSpyerCallerIdNum() { return spyerCallerIdNum; } - - public void setSpyerCallerIdNum(String spyerCallerIdNum) - { + public void setSpyerCallerIdNum(String spyerCallerIdNum) { this.spyerCallerIdNum = spyerCallerIdNum; } - - public String getSpyerConnectedLineNum() - { + public String getSpyerConnectedLineNum() { return spyerConnectedLineNum; } - - public void setSpyerConnectedLineNum(String spyerConnectedLineNum) - { + public void setSpyerConnectedLineNum(String spyerConnectedLineNum) { this.spyerConnectedLineNum = spyerConnectedLineNum; } - - public String getSpyerConnectedLineName() - { + public String getSpyerConnectedLineName() { return spyerConnectedLineName; } - - public void setSpyerConnectedLineName(String spyerConnectedLineName) - { + public void setSpyerConnectedLineName(String spyerConnectedLineName) { this.spyerConnectedLineName = spyerConnectedLineName; } - - public String getSpyerCallerIdName() - { + public String getSpyerCallerIdName() { return spyerCallerIdName; } - - public void setSpyerCallerIdName(String 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 index 7b9e9a19b..872cb74d6 100644 --- a/src/main/java/org/asteriskjava/manager/event/ChanSpyStopEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ChanSpyStopEvent.java @@ -1,233 +1,278 @@ /* - * 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.event; - -public class ChanSpyStopEvent extends ManagerEvent -{ - /** - * Serial version identifier - */ +public class ChanSpyStopEvent extends ManagerEvent { private static final long serialVersionUID = 3256725065466000696L; - /** - * The name of the channel. - */ - private String spyeechannel; - - private String spyerUniqueId; - private String spyerLinkedId; + private String spyerChannel; private Integer spyerChannelState; - private Integer spyerPriority; - private String spyerContext; - private String spyerLanguage; - private String spyerChannelStateDesc; - private String spyerExten; + private String spyerChannelStateDesc; private String spyerCallerIdNum; - private String spyerConnectedLineNum; - private String spyerConnectedLineName; private String spyerCallerIdName; - private String spyerChannel; - + 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; - public ChanSpyStopEvent(Object source) - { + 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 getSpyeeChannel() - { - return spyeechannel; + public String getSpyerChannel() { + return spyerChannel; } - public void setSpyeeChannel(String channel) - { - this.spyeechannel = channel; + public void setSpyerChannel(String spyerChannel) { + this.spyerChannel = spyerChannel; } - - public String getSpyeechannel() - { - return spyeechannel; + public Integer getSpyerChannelState() { + return spyerChannelState; } - - public void setSpyeechannel(String spyeechannel) - { - this.spyeechannel = spyeechannel; + public void setSpyerChannelState(Integer spyerChannelState) { + this.spyerChannelState = spyerChannelState; } - - public String getSpyerUniqueId() - { - return spyerUniqueId; + public String getSpyerChannelStateDesc() { + return spyerChannelStateDesc; } + public void setSpyerChannelStateDesc(String spyerChannelStateDesc) { + this.spyerChannelStateDesc = spyerChannelStateDesc; + } - public void setSpyerUniqueId(String spyerUniqueId) - { - this.spyerUniqueId = spyerUniqueId; + public String getSpyerCallerIdNum() { + return spyerCallerIdNum; } + public void setSpyerCallerIdNum(String spyerCallerIdNum) { + this.spyerCallerIdNum = spyerCallerIdNum; + } - public String getSpyerLinkedId() - { - return spyerLinkedId; + public String getSpyerCallerIdName() { + return spyerCallerIdName; } + public void setSpyerCallerIdName(String spyerCallerIdName) { + this.spyerCallerIdName = spyerCallerIdName; + } - public void setSpyerLinkedId(String spyerLinkedId) - { - this.spyerLinkedId = spyerLinkedId; + public String getSpyerConnectedLineNum() { + return spyerConnectedLineNum; } + public void setSpyerConnectedLineNum(String spyerConnectedLineNum) { + this.spyerConnectedLineNum = spyerConnectedLineNum; + } - public Integer getSpyerChannelState() - { - return spyerChannelState; + public String getSpyerConnectedLineName() { + return spyerConnectedLineName; } + public void setSpyerConnectedLineName(String spyerConnectedLineName) { + this.spyerConnectedLineName = spyerConnectedLineName; + } - public void setSpyerChannelState(Integer spyerChannelState) - { - this.spyerChannelState = spyerChannelState; + public String getSpyerLanguage() { + return spyerLanguage; } + public void setSpyerLanguage(String spyerLanguage) { + this.spyerLanguage = spyerLanguage; + } - public Integer getSpyerPriority() - { - return spyerPriority; + public String getSpyerAccountCode() { + return spyerAccountCode; } + public void setSpyerAccountCode(String spyerAccountCode) { + this.spyerAccountCode = spyerAccountCode; + } - public void setSpyerPriority(Integer spyerPriority) - { - this.spyerPriority = spyerPriority; + public String getSpyerContext() { + return spyerContext; } + public void setSpyerContext(String spyerContext) { + this.spyerContext = spyerContext; + } - public String getSpyerContext() - { - return spyerContext; + public String getSpyerExten() { + return spyerExten; } + public void setSpyerExten(String spyerExten) { + this.spyerExten = spyerExten; + } - public void setSpyerContext(String spyerContext) - { - this.spyerContext = spyerContext; + public Integer getSpyerPriority() { + return spyerPriority; } + public void setSpyerPriority(Integer spyerPriority) { + this.spyerPriority = spyerPriority; + } - public String getSpyerLanguage() - { - return spyerLanguage; + public String getSpyerUniqueId() { + return spyerUniqueId; } + public void setSpyerUniqueId(String spyerUniqueId) { + this.spyerUniqueId = spyerUniqueId; + } - public void setSpyerLanguage(String spyerLanguage) - { - this.spyerLanguage = spyerLanguage; + public String getSpyerLinkedId() { + return spyerLinkedId; } + public void setSpyerLinkedId(String spyerLinkedId) { + this.spyerLinkedId = spyerLinkedId; + } - public String getSpyerChannelStateDesc() - { - return spyerChannelStateDesc; + public String getSpyeeChannel() { + return spyeeChannel; } + public void setSpyeeChannel(String spyeeChannel) { + this.spyeeChannel = spyeeChannel; + } - public void setSpyerChannelStateDesc(String spyerChannelStateDesc) - { - this.spyerChannelStateDesc = spyerChannelStateDesc; + public Integer getSpyeeChannelState() { + return spyeeChannelState; } + public void setSpyeeChannelState(Integer spyeeChannelState) { + this.spyeeChannelState = spyeeChannelState; + } - public String getSpyerExten() - { - return spyerExten; + public String getSpyeeChannelStateDesc() { + return spyeeChannelStateDesc; } + public void setSpyeeChannelStateDesc(String spyeeChannelStateDesc) { + this.spyeeChannelStateDesc = spyeeChannelStateDesc; + } - public void setSpyerExten(String spyerExten) - { - this.spyerExten = spyerExten; + public String getSpyeeCallerIdNum() { + return spyeeCallerIdNum; } + public void setSpyeeCallerIdNum(String spyeeCallerIdNum) { + this.spyeeCallerIdNum = spyeeCallerIdNum; + } - public String getSpyerCallerIdNum() - { - return spyerCallerIdNum; + public String getSpyeeCallerIdName() { + return spyeeCallerIdName; } + public void setSpyeeCallerIdName(String spyeeCallerIdName) { + this.spyeeCallerIdName = spyeeCallerIdName; + } - public void setSpyerCallerIdNum(String spyerCallerIdNum) - { - this.spyerCallerIdNum = spyerCallerIdNum; + public String getSpyeeConnectedLineNum() { + return spyeeConnectedLineNum; } + public void setSpyeeConnectedLineNum(String spyeeConnectedLineNum) { + this.spyeeConnectedLineNum = spyeeConnectedLineNum; + } - public String getSpyerConnectedLineNum() - { - return spyerConnectedLineNum; + public String getSpyeeConnectedLineName() { + return spyeeConnectedLineName; } + public void setSpyeeConnectedLineName(String spyeeConnectedLineName) { + this.spyeeConnectedLineName = spyeeConnectedLineName; + } - public void setSpyerConnectedLineNum(String spyerConnectedLineNum) - { - this.spyerConnectedLineNum = spyerConnectedLineNum; + public String getSpyeeLanguage() { + return spyeeLanguage; } + public void setSpyeeLanguage(String spyeeLanguage) { + this.spyeeLanguage = spyeeLanguage; + } - public String getSpyerConnectedLineName() - { - return spyerConnectedLineName; + public String getSpyeeAccountCode() { + return spyeeAccountCode; } + public void setSpyeeAccountCode(String spyeeAccountCode) { + this.spyeeAccountCode = spyeeAccountCode; + } - public void setSpyerConnectedLineName(String spyerConnectedLineName) - { - this.spyerConnectedLineName = spyerConnectedLineName; + public String getSpyeeContext() { + return spyeeContext; } + public void setSpyeeContext(String spyeeContext) { + this.spyeeContext = spyeeContext; + } - public String getSpyerCallerIdName() - { - return spyerCallerIdName; + public String getSpyeeExten() { + return spyeeExten; } + public void setSpyeeExten(String spyeeExten) { + this.spyeeExten = spyeeExten; + } - public void setSpyerCallerIdName(String spyerCallerIdName) - { - this.spyerCallerIdName = spyerCallerIdName; + public Integer getSpyeePriority() { + return spyeePriority; } + public void setSpyeePriority(Integer spyeePriority) { + this.spyeePriority = spyeePriority; + } - public String getSpyerChannel() - { - return spyerChannel; + public String getSpyeeUniqueId() { + return spyeeUniqueId; } + public void setSpyeeUniqueId(String spyeeUniqueId) { + this.spyeeUniqueId = spyeeUniqueId; + } - public void setSpyerChannel(String spyerChannel) - { - this.spyerChannel = spyerChannel; + 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 fc5cab85d..d3a6b998e 100644 --- a/src/main/java/org/asteriskjava/manager/event/ChannelReloadEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ChannelReloadEvent.java @@ -34,8 +34,7 @@ * * @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,8 +166,7 @@ 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; } @@ -189,8 +180,7 @@ public void setRegistryCount(Integer registryCount) * @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 16b97b27d..e5d0edd6c 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeEndEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeEndEvent.java @@ -6,16 +6,14 @@ * * @since 1.0.0 */ -public class ConfbridgeEndEvent extends AbstractConfbridgeEvent -{ +public class ConfbridgeEndEvent extends AbstractConfbridgeEvent { /** * Serializable version identifier */ private static final long serialVersionUID = -8973512592594074108L; - public ConfbridgeEndEvent(Object source) - { + 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 f4111f1c7..228283784 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeJoinEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeJoinEvent.java @@ -6,8 +6,7 @@ * * @since 1.0.0 */ -public class ConfbridgeJoinEvent extends AbstractConfbridgeEvent -{ +public class ConfbridgeJoinEvent extends AbstractConfbridgeEvent { /** * Serializable version identifier */ @@ -15,18 +14,15 @@ public class ConfbridgeJoinEvent extends AbstractConfbridgeEvent String muted; - public ConfbridgeJoinEvent(Object source) - { + public ConfbridgeJoinEvent(Object source) { super(source); } - public String getMuted() - { + public String getMuted() { return muted; } - public void setMuted(String muted) - { + 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 2116a5a5f..7abbe5460 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeLeaveEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeLeaveEvent.java @@ -5,15 +5,13 @@ * * @since 1.0.0 */ -public class ConfbridgeLeaveEvent extends AbstractConfbridgeEvent -{ +public class ConfbridgeLeaveEvent extends AbstractConfbridgeEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 1L; - public ConfbridgeLeaveEvent(Object source) - { + public ConfbridgeLeaveEvent(Object source) { super(source); } 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 4046c17bd..dc76b41fe 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeListEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeListEvent.java @@ -6,8 +6,7 @@ * @see org.asteriskjava.manager.action.ConfbridgeListAction * @since 1.0.0 */ -public class ConfbridgeListEvent extends ResponseEvent -{ +public class ConfbridgeListEvent extends ResponseEvent { /** * Serializable version identifier */ @@ -17,9 +16,18 @@ public class ConfbridgeListEvent extends ResponseEvent 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); } @@ -28,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; } @@ -38,54 +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 role of the caller in the list admin = yes or no of the conference. + * 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. + * @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 bd001c754..1368f0915 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeStartEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeStartEvent.java @@ -6,8 +6,7 @@ * * @since 1.0.0 */ -public class ConfbridgeStartEvent extends AbstractConfbridgeEvent -{ +public class ConfbridgeStartEvent extends AbstractConfbridgeEvent { /** * Serializable version identifier */ @@ -16,8 +15,7 @@ public class ConfbridgeStartEvent extends AbstractConfbridgeEvent @SuppressWarnings("unused") private String conference; - public ConfbridgeStartEvent(Object source) - { + public ConfbridgeStartEvent(Object source) { super(source); } diff --git a/src/main/java/org/asteriskjava/manager/event/ConfbridgeTalkingEvent.java b/src/main/java/org/asteriskjava/manager/event/ConfbridgeTalkingEvent.java index 4ce4fba72..960ad1ed2 100644 --- a/src/main/java/org/asteriskjava/manager/event/ConfbridgeTalkingEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ConfbridgeTalkingEvent.java @@ -6,17 +6,15 @@ * * @since 1.0.0 */ -public class ConfbridgeTalkingEvent extends AbstractConfbridgeEvent -{ +public class ConfbridgeTalkingEvent extends AbstractConfbridgeEvent { /** * Serializable version identifier */ private static final long serialVersionUID = 1L; private Boolean talkingStatus; - - public ConfbridgeTalkingEvent(Object source) - { + + public ConfbridgeTalkingEvent(Object source) { super(source); } @@ -25,8 +23,7 @@ public ConfbridgeTalkingEvent(Object source) * * @param talkingStatus the talking status */ - public void setTalkingStatus(Boolean talkingStatus) - { + public void setTalkingStatus(Boolean talkingStatus) { this.talkingStatus = talkingStatus; } @@ -34,11 +31,10 @@ public void setTalkingStatus(Boolean talkingStatus) * Returns the talking status. * * @return true if the participant started talking, - * false if the participant stopped 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 index 752597af6..8d23aca21 100644 --- a/src/main/java/org/asteriskjava/manager/event/ContactList.java +++ b/src/main/java/org/asteriskjava/manager/event/ContactList.java @@ -21,13 +21,12 @@ * been reported in response to an PJSipShowContactsAction. *

    * Available since Asterisk 16? - * + * * @author srt * @version $Id$ * @since 3.0 */ -public class ContactList extends ResponseEvent -{ +public class ContactList extends ResponseEvent { /** * Serial version identifier. */ @@ -58,203 +57,164 @@ public class ContactList extends ResponseEvent /** * Creates a new instance. - * + * * @param source */ - public ContactList(Object source) - { + public ContactList(Object source) { super(source); } - public double getQualifyTimeout() - { + public double getQualifyTimeout() { return qualifyTimeout; } - public void setQualifyTimeout(double qualifyTimeout) - { + public void setQualifyTimeout(double qualifyTimeout) { this.qualifyTimeout = qualifyTimeout; } - public String getCallid() - { + public String getCallid() { return callid; } - public void setCallid(String callid) - { + public void setCallid(String callid) { this.callid = callid; } - public String getRegserver() - { + public String getRegserver() { return regserver; } - public void setRegserver(String regserver) - { + public void setRegserver(String regserver) { this.regserver = regserver; } - public String getRoundtripusec() - { + public String getRoundtripusec() { return roundtripusec; } - public void setRoundtripusec(String roundtripusec) - { + public void setRoundtripusec(String roundtripusec) { this.roundtripusec = roundtripusec; } - public long getExpirationtime() - { + public long getExpirationtime() { return expirationtime; } - public void setExpirationtime(long expirationtime) - { + public void setExpirationtime(long expirationtime) { this.expirationtime = expirationtime; } - public String getAuthenticatequalify() - { + public String getAuthenticatequalify() { return authenticatequalify; } - public void setAuthenticatequalify(String authenticatequalify) - { + public void setAuthenticatequalify(String authenticatequalify) { this.authenticatequalify = authenticatequalify; } - public String getObjectname() - { + public String getObjectname() { return objectname; } - public void setObjectname(String objectname) - { + public void setObjectname(String objectname) { this.objectname = objectname; } - public String getUseragent() - { + public String getUseragent() { return useragent; } - public void setUseragent(String useragent) - { + public void setUseragent(String useragent) { this.useragent = useragent; } - public String getUri() - { + public String getUri() { return uri; } - public void setUri(String uri) - { + public void setUri(String uri) { this.uri = uri; } - public String getViaaddr() - { + public String getViaaddr() { return viaaddr; } - public void setViaaddr(String viaaddr) - { + public void setViaaddr(String viaaddr) { this.viaaddr = viaaddr; } - public long getQualifyfrequency() - { + public long getQualifyfrequency() { return qualifyfrequency; } - public void setQualifyfrequency(Long qualifyfrequency) - { + public void setQualifyfrequency(Long qualifyfrequency) { this.qualifyfrequency = qualifyfrequency; } - public String getPath() - { + public String getPath() { return path; } - public void setPath(String path) - { + public void setPath(String path) { this.path = path; } - public String getEndpoint() - { + public String getEndpoint() { return endpoint; } - public void setEndpoint(String endpoint) - { + public void setEndpoint(String endpoint) { this.endpoint = endpoint; } - public String getViaport() - { + public String getViaport() { return viaport; } - public void setViaport(String viaport) - { + public void setViaport(String viaport) { this.viaport = viaport; } - public String getOutboundproxy() - { + public String getOutboundproxy() { return outboundproxy; } - public void setOutboundproxy(String outboundproxy) - { + public void setOutboundproxy(String outboundproxy) { this.outboundproxy = outboundproxy; } - public String getObjecttype() - { + public String getObjecttype() { return objecttype; } - public void setObjecttype(String objecttype) - { + public void setObjecttype(String objecttype) { this.objecttype = objecttype; } - public String getPruneonboot() - { + public String getPruneonboot() { return pruneonboot; } - public void setPruneonboot(String pruneonboot) - { + public void setPruneonboot(String pruneonboot) { this.pruneonboot = pruneonboot; } - public ContactStatusEnum getStatus() - { + public ContactStatusEnum getStatus() { return status; } - public void setStatus(String status) - { + public void setStatus(String status) { this.status = ContactStatusEnum.UNKNOWN; - if (status != null && status.length() > 0) - { + if (status != null && status.length() > 0) { this.status = ContactStatusEnum.valueOf(status.toUpperCase()); } } @Override - public String toString() - { + public String toString() { return "ContactList [qualifyTimeout=" + qualifyTimeout + ", callid=" + callid + ", regserver=" + regserver + ", roundtripusec=" + roundtripusec + ", expirationtime=" + expirationtime + ", authenticatequalify=" + authenticatequalify + ", objectname=" + objectname + ", useragent=" + useragent + ", uri=" + uri diff --git a/src/main/java/org/asteriskjava/manager/event/ContactListComplete.java b/src/main/java/org/asteriskjava/manager/event/ContactListComplete.java index 08cea4cdb..13fb427fd 100644 --- a/src/main/java/org/asteriskjava/manager/event/ContactListComplete.java +++ b/src/main/java/org/asteriskjava/manager/event/ContactListComplete.java @@ -21,16 +21,15 @@ * 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 ContactListComplete extends ResponseEvent -{ +public class ContactListComplete extends ResponseEvent { /** * Serial version identifier. */ @@ -40,31 +39,28 @@ public class ContactListComplete extends ResponseEvent /** * Creates a new instance. - * + * * @param source */ - public ContactListComplete(Object 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() - { + 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,16 +70,14 @@ public void setListItems(Integer listItems) * Available since Asterisk 1.6. * * @return always returns "Complete" confirming that all PeerEntry events - * have been sent. + * 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/ContactStatusDetail.java b/src/main/java/org/asteriskjava/manager/event/ContactStatusDetail.java new file mode 100644 index 000000000..efdb18a78 --- /dev/null +++ b/src/main/java/org/asteriskjava/manager/event/ContactStatusDetail.java @@ -0,0 +1,166 @@ +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; + + 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 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 index c7d421529..84443bceb 100644 --- a/src/main/java/org/asteriskjava/manager/event/ContactStatusEnum.java +++ b/src/main/java/org/asteriskjava/manager/event/ContactStatusEnum.java @@ -1,7 +1,6 @@ package org.asteriskjava.manager.event; -public enum ContactStatusEnum -{ +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 index a2ef9ca1a..eb0b9e463 100644 --- a/src/main/java/org/asteriskjava/manager/event/ContactStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ContactStatusEvent.java @@ -18,19 +18,18 @@ /** * Raised when the state of a contact changes. - * + *

    * Available since Asterisk 13 */ -public class ContactStatusEvent extends ManagerEvent -{ +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_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"; + public static final String STATUS_UPDATED = "Updated"; private String uri; private String contactStatus; @@ -42,98 +41,79 @@ public class ContactStatusEvent extends ManagerEvent private String viaAddress; private String callID; - public ContactStatusEvent(Object source) - { + public ContactStatusEvent(Object source) { super(source); } - public String getUri() - { + public String getUri() { return uri; } - public void setUri(String value) - { + public void setUri(String value) { this.uri = value; } - public String getContactStatus() - { + public String getContactStatus() { return contactStatus; } - public void setContactStatus(String value) - { + public void setContactStatus(String value) { this.contactStatus = value; } - public String getAor() - { + public String getAor() { return aor; } - public void setAor(String value) - { + public void setAor(String value) { this.aor = value; } - public String getEndpointName() - { + public String getEndpointName() { return endpointName; } - public void setEndpointName(String value) - { + public void setEndpointName(String value) { this.endpointName = value; } - public String getRoundtripUsec() - { + public String getRoundtripUsec() { return roundtripUsec; } - public void setRoundtripUsec(String value) - { + public void setRoundtripUsec(String value) { this.roundtripUsec = value; } - public String getUserAgent() - { + public String getUserAgent() { return userAgent; } - public void setUserAgent(String value) - { + public void setUserAgent(String value) { this.userAgent = value; } - public String getRegExpire() - { + public String getRegExpire() { return regExpire; } - public void setRegExpire(String value) - { + public void setRegExpire(String value) { this.regExpire = value; } - public String getViaAddress() - { + public String getViaAddress() { return viaAddress; } - public void setViaAddress(String value) - { + public void setViaAddress(String value) { this.viaAddress = value; } - public String getCallID() - { + public String getCallID() { return callID; } - public void setCallID(String 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 c401b272f..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. @@ -25,8 +25,7 @@ * @see org.asteriskjava.manager.action.CoreShowChannelsAction * @since 1.0.0 */ -public class CoreShowChannelEvent extends ResponseEvent -{ +public class CoreShowChannelEvent extends ResponseEvent { /** * Serializable version identifier. */ @@ -45,8 +44,7 @@ public class CoreShowChannelEvent extends ResponseEvent private String language; - public CoreShowChannelEvent(Object source) - { + public CoreShowChannelEvent(Object source) { super(source); } @@ -61,13 +59,11 @@ public CoreShowChannelEvent(Object source) * * @return accountcode */ - public String getAccountcode() - { + public String getAccountcode() { return accountcode; } - public void setAccountcode(String accountcode) - { + public void setAccountcode(String accountcode) { this.accountcode = accountcode; } @@ -76,13 +72,11 @@ 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; } @@ -92,13 +86,11 @@ public void setApplication(String 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; } @@ -107,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; } @@ -123,14 +113,12 @@ public void setBridgedChannel(String bridgedChannel) * @return uniqueid */ @Deprecated - public String getBridgeduniqueid() - { + public String getBridgeduniqueid() { return bridgeid; } @Deprecated - public void setBridgeduniqueid(String bridgeduniqueid) - { + public void setBridgeduniqueid(String bridgeduniqueid) { this.bridgeid = bridgeduniqueid; } @@ -139,13 +127,11 @@ public void setBridgeduniqueid(String bridgeduniqueid) * * @return uniqueid */ - public String getBridgeid() - { + public String getBridgeid() { return bridgeid; } - public void setBridgeid(String bridgeid) - { + public void setBridgeid(String bridgeid) { this.bridgeid = bridgeid; } @@ -154,13 +140,11 @@ public void setBridgeid(String bridgeid) * * @return Channel name */ - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -169,13 +153,11 @@ public void setChannel(String channel) * * @return duration */ - public String getDuration() - { + public String getDuration() { return duration; } - public void setDuration(String duration) - { + public void setDuration(String duration) { this.duration = duration; } @@ -184,13 +166,11 @@ 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; } @@ -199,13 +179,11 @@ public void setExtension(String extension) * * @return uniqueid */ - 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/CoreShowChannelsCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/CoreShowChannelsCompleteEvent.java index 8bab60ebe..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,8 +59,7 @@ public void setEventlist(String eventlist) * * @return the number of channels reported. */ - public Integer getListitems() - { + public Integer getListitems() { return listitems; } @@ -73,8 +68,7 @@ public Integer getListitems() * * @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 index 2c8a139f4..40ab63d22 100644 --- a/src/main/java/org/asteriskjava/manager/event/DAHDIChannelEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DAHDIChannelEvent.java @@ -1,63 +1,89 @@ - package org.asteriskjava.manager.event; /** * @author Sebastian */ -public class DAHDIChannelEvent extends ManagerEvent -{ +public class DAHDIChannelEvent extends ManagerEvent { /** - * + * */ - private static final long serialVersionUID = 1L; + 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 String getDahdichannel() - { + public Integer getDahdigroup() { + return this.dahdigroup; + } + + public void setDahdigroup(Integer dahdigroup) { + this.dahdigroup = dahdigroup; + } + + public String getDahdichannel() { return dahdichannel; } - public void setDahdichannel(String dahdichannel) - { + public void setDahdichannel(String dahdichannel) { this.dahdichannel = dahdichannel; } - public String getDahdispan() - { + public String getDahdispan() { return dahdispan; } - public void setDahdispan(String dahdispan) - { + public void setDahdispan(String dahdispan) { this.dahdispan = dahdispan; } - public String getUniqueid() - { + public String getUniqueid() { return uniqueid; } - public void setUniqueid(String uniqueid) - { + public void setUniqueid(String uniqueid) { this.uniqueid = uniqueid; } - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - public DAHDIChannelEvent(Object source) - { + 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 index 5945f2fed..8053e1e4e 100644 --- a/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsCompleteEvent.java @@ -19,15 +19,13 @@ /** * A DahdiShowChannelsCompleteEvent is triggered after the state of all Dahdi channels has been reported * in response to a DahdiShowChannelsAction. - * - * @see org.asteriskjava.manager.action.DahdiShowChannelsAction - * @see org.asteriskjava.manager.event.DahdiShowChannelsEvent - * + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.DahdiShowChannelsAction + * @see org.asteriskjava.manager.event.DahdiShowChannelsEvent */ -public class DahdiShowChannelsCompleteEvent extends ResponseEvent -{ +public class DahdiShowChannelsCompleteEvent extends ResponseEvent { /** * Serial version identifier */ @@ -44,28 +42,25 @@ public Integer getItems() { public void setItems(Integer items) { this.items = items; } - + /** * @param source */ - public DahdiShowChannelsCompleteEvent(Object 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() - { + public String getEventlist() { return eventlist; } - public void setEventlist(String eventlist) - { + public void setEventlist(String eventlist) { this.eventlist = eventlist; } @@ -74,8 +69,7 @@ public void setEventlist(String eventlist) * * @return the number of channels reported. */ - public Integer getListitems() - { + public Integer getListitems() { return listitems; } @@ -84,8 +78,7 @@ public Integer getListitems() * * @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/DahdiShowChannelsEvent.java b/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsEvent.java index e878df7b6..38035de39 100644 --- a/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DahdiShowChannelsEvent.java @@ -19,14 +19,12 @@ /** * A DahdiShowChannelsEvent is triggered in response to a DahdiShowChannelsAction and shows the state of * a Dahdi channel. - * - * @see org.asteriskjava.manager.action.DahdiShowChannelsAction - * + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.DahdiShowChannelsAction */ -public class DahdiShowChannelsEvent extends ResponseEvent -{ +public class DahdiShowChannelsEvent extends ResponseEvent { /** * Serial version identifier */ @@ -81,17 +79,14 @@ public void setUniqueid(String uniqueid) { } - - /** * @param source */ - public DahdiShowChannelsEvent(Object source) - { + public DahdiShowChannelsEvent(Object source) { super(source); } - + /** * Returns the signalling of this Dahdi channel.

    * Possible values are: @@ -121,39 +116,35 @@ public DahdiShowChannelsEvent(Object source) *

  • Pseudo Signalling
  • * */ - public String getSignalling() - { + public String getSignalling() { return signalling; } /** * Sets the signalling of this Dahdi channel. */ - public void setSignalling(String signalling) - { + 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. + * 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 Dahdi channel. - * + * * @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; } @@ -170,16 +161,14 @@ public void setDnd(Boolean dnd) *
  • No Alarm
  • * */ - public String getAlarm() - { + public String getAlarm() { return alarm; } /** * Sets the alarm state of this Dahdi channel. */ - public void setAlarm(String alarm) - { + 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 index b4d31d8f9..841a25be4 100644 --- a/src/main/java/org/asteriskjava/manager/event/DeviceStateChangeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DeviceStateChangeEvent.java @@ -1,36 +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 class DeviceStateChangeEvent extends ManagerEvent { + /** + * + */ + private static final long serialVersionUID = 1L; + private String state; + private String device; - public String getState() - { - return state; - } + public String getState() { + return state; + } - public void setState(String state) - { - this.state = state; - } + public void setState(String state) { + this.state = state; + } - public String getDevice() - { - return device; - } + public String getDevice() { + return device; + } - public void setDevice(String device) - { - this.device = device; - } + public void setDevice(String device) { + this.device = device; + } - public DeviceStateChangeEvent(Object source) - { - super(source); - } + 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 index f4f3601be..bba22d876 100644 --- a/src/main/java/org/asteriskjava/manager/event/DialBeginEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DialBeginEvent.java @@ -1,94 +1,74 @@ package org.asteriskjava.manager.event; -public class DialBeginEvent extends DialEvent -{ +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) - { + public DialBeginEvent(Object source) { super(source); setSubEvent(SUBEVENT_BEGIN); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getDestLanguage() - { + public String getDestLanguage() { return destlanguage; } - public void setDestLanguage(String destlanguage) - { + public void setDestLanguage(String destlanguage) { this.destlanguage = destlanguage; } - public String getDestAccountCode() - { + public String getDestAccountCode() { return destAccountCode; } - public void setDestAccountCode(String destAccountCode) - { + public void setDestAccountCode(String destAccountCode) { this.destAccountCode = destAccountCode; } - public String getDestlanguage() - { + public String getDestlanguage() { return destlanguage; } - public void setDestlanguage(String destlanguage) - { - this.destlanguage = destlanguage; - } - - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getDestLinkedId() - { + public String getDestLinkedId() { return destLinkedId; } - public void setDestLinkedId(String destLinkedId) - { + public void setDestLinkedId(String destLinkedId) { this.destLinkedId = destLinkedId; } - public String getAccountcode() - { - return accountcode; - } + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = 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 index 39b459ae9..dcb5be717 100644 --- a/src/main/java/org/asteriskjava/manager/event/DialEndEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DialEndEvent.java @@ -1,9 +1,8 @@ package org.asteriskjava.manager.event; -public class DialEndEvent extends DialEvent -{ +public class DialEndEvent extends DialEvent { /** - * + * */ private static final long serialVersionUID = 1L; private String language; @@ -14,79 +13,64 @@ public class DialEndEvent extends DialEvent private String linkedId; private String forward; - public DialEndEvent(Object source) - { + public DialEndEvent(Object source) { super(source); setSubEvent(SUBEVENT_END); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getDestLanguage() - { + public String getDestLanguage() { return destLanguage; } - public void setDestLanguage(String destLanguage) - { + public void setDestLanguage(String destLanguage) { this.destLanguage = destLanguage; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - public String getDestAccountCode() - { + public String getDestAccountCode() { return destAccountCode; } - public void setDestAccountCode(String destAccountCode) - { + public void setDestAccountCode(String destAccountCode) { this.destAccountCode = destAccountCode; } - public String getDestLinkedId() - { + public String getDestLinkedId() { return destLinkedId; } - public void setDestLinkedId(String destLinkedId) - { + public void setDestLinkedId(String destLinkedId) { this.destLinkedId = destLinkedId; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getForward() - { + public String getForward() { return forward; } - public void setForward(String 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 7c1c7f0b6..4af7c5e6f 100644 --- a/src/main/java/org/asteriskjava/manager/event/DialEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DialEvent.java @@ -27,8 +27,7 @@ * @version $Id$ * @since 0.2 */ -public class DialEvent extends ManagerEvent -{ +public class DialEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -90,8 +89,7 @@ public class DialEvent extends ManagerEvent private String dialString; private String dialStatus; - public DialEvent(Object source) - { + public DialEvent(Object source) { super(source); } @@ -99,8 +97,7 @@ public DialEvent(Object source) * Enro 2015-03 Workaround to build legacy DialEvent (unsupported in * Asterisk 13) from new DialBeginEvent Asterisk 13. */ - public DialEvent(DialBeginEvent dialBeginEvent) - { + public DialEvent(DialBeginEvent dialBeginEvent) { this(dialBeginEvent.getSource()); setDateReceived(dialBeginEvent.getDateReceived()); setTimestamp(dialBeginEvent.getTimestamp()); @@ -125,16 +122,14 @@ public DialEvent(DialBeginEvent dialBeginEvent) * available except for the dial status. * * @return "Begin" or "End" for Asterisk since 1.6, "Begin" for Asterisk - * prior to 1.6. + * 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; } @@ -144,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; } @@ -155,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; } @@ -167,8 +160,7 @@ public void setChannel(String channel) * @deprecated as of 1.0.0, use {@link #getChannel()} instead. */ @Deprecated - public String getSrc() - { + public String getSrc() { return channel; } @@ -180,8 +172,7 @@ public String getSrc() * * @param src the name of the source channel. */ - public void setSrc(String src) - { + public void setSrc(String src) { this.channel = src; } @@ -190,13 +181,11 @@ public void setSrc(String src) * * @return the name of the destination channel. */ - public String getDestination() - { + public String getDestination() { return destination; } - public String getDestChannel() - { + public String getDestChannel() { return getDestination(); } @@ -205,13 +194,11 @@ public String getDestChannel() * * @param destination the name of the destination channel. */ - public void setDestination(String destination) - { + public void setDestination(String destination) { this.destination = destination; } - public void setDestChannel(String destination) - { + public void setDestChannel(String destination) { setDestination(destination); } @@ -222,8 +209,7 @@ public void setDestChannel(String destination) * @deprecated as of 1.0.0, use {@link #getCallerIdNum()} instead. */ @Deprecated - public String getCallerId() - { + public String getCallerId() { return getCallerIdNum(); } @@ -234,8 +220,7 @@ public String getCallerId() * @deprecated as of 1.0.0, use {@link #setCallerIdNum()} instead. */ @Deprecated - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { setCallerIdNum(callerId); } @@ -245,8 +230,7 @@ public void setCallerId(String callerId) * @return the unique ID of the source channel. * @since 1.0.0 */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -256,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; } @@ -268,8 +251,7 @@ public void setUniqueId(String srcUniqueId) * @deprecated as of 1.0.0, use {@link #getUniqueId()} instead. */ @Deprecated - public String getSrcUniqueId() - { + public String getSrcUniqueId() { return uniqueId; } @@ -281,8 +263,7 @@ public String getSrcUniqueId() * * @param srcUniqueId the unique ID of the source channel. */ - public void setSrcUniqueId(String srcUniqueId) - { + public void setSrcUniqueId(String srcUniqueId) { this.uniqueId = srcUniqueId; } @@ -291,8 +272,7 @@ public void setSrcUniqueId(String srcUniqueId) * * @return the unique ID of the destination channel. */ - public String getDestUniqueId() - { + public String getDestUniqueId() { return destUniqueId; } @@ -301,8 +281,7 @@ 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; } @@ -314,8 +293,7 @@ public void setDestUniqueId(String destUniqueId) * @return the dial string passed to the Dial application. * @since 1.0.0 */ - public String getDialString() - { + public String getDialString() { return dialString; } @@ -325,8 +303,7 @@ 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; } @@ -352,19 +329,16 @@ public void setDialString(String dialString) * @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() - { + public String toString() { StringBuilder builder = new StringBuilder(); builder.append("DialEvent [subEvent="); builder.append(subEvent); @@ -392,93 +366,75 @@ public String toString() return builder.toString(); } - public Integer getDestChannelState() - { + public Integer getDestChannelState() { return destChannelState; } - public void setDestChannelState(Integer destChannelState) - { + public void setDestChannelState(Integer destChannelState) { this.destChannelState = destChannelState; } - public String getDestContext() - { + public String getDestContext() { return destContext; } - public void setDestContext(String destContext) - { + public void setDestContext(String destContext) { this.destContext = destContext; } - public Integer getDestPriority() - { + public Integer getDestPriority() { return destPriority; } - public void setDestPriority(Integer destPriority) - { + public void setDestPriority(Integer destPriority) { this.destPriority = destPriority; } - public String getDestChannelStateDesc() - { + public String getDestChannelStateDesc() { return destChannelStateDesc; } - public void setDestChannelStateDesc(String destChannelStateDesc) - { + public void setDestChannelStateDesc(String destChannelStateDesc) { this.destChannelStateDesc = destChannelStateDesc; } - public String getDestExten() - { + public String getDestExten() { return destExten; } - public void setDestExten(String destExten) - { + public void setDestExten(String destExten) { this.destExten = destExten; } - public String getDestConnectedLineName() - { + public String getDestConnectedLineName() { return destConnectedLineName; } - public void setDestConnectedLineName(String destConnectedLineName) - { + public void setDestConnectedLineName(String destConnectedLineName) { this.destConnectedLineName = destConnectedLineName; } - public String getDestConnectedLineNum() - { + public String getDestConnectedLineNum() { return destConnectedLineNum; } - public void setDestConnectedLineNum(String destConnectedLineNum) - { + public void setDestConnectedLineNum(String destConnectedLineNum) { this.destConnectedLineNum = destConnectedLineNum; } - public String getDestCallerIdName() - { + public String getDestCallerIdName() { return destCallerIdName; } - public void setDestCallerIdName(String destCallerIdName) - { + public void setDestCallerIdName(String destCallerIdName) { this.destCallerIdName = destCallerIdName; } - public String getDestCallerIdNum() - { + public String getDestCallerIdNum() { return destCallerIdNum; } - public void setDestCallerIdNum(String 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 index ed22a173e..7e6ce09c6 100644 --- a/src/main/java/org/asteriskjava/manager/event/DialStateEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DialStateEvent.java @@ -16,8 +16,7 @@ */ package org.asteriskjava.manager.event; -public class DialStateEvent extends ManagerEvent -{ +public class DialStateEvent extends ManagerEvent { private static final long serialVersionUID = 1L; String destAccountCode; @@ -42,218 +41,175 @@ public class DialStateEvent extends ManagerEvent String language; String channel; - public DialStateEvent(Object source) - { + public DialStateEvent(Object source) { super(source); } - public String getDestAccountCode() - { + public String getDestAccountCode() { return destAccountCode; } - public void setDestAccountCode(String destAccountCode) - { + public void setDestAccountCode(String destAccountCode) { this.destAccountCode = destAccountCode; } - public String getDestCallerIdName() - { + public String getDestCallerIdName() { return destCallerIdName; } - public void setDestCallerIdName(String destCallerIdName) - { + public void setDestCallerIdName(String destCallerIdName) { this.destCallerIdName = destCallerIdName; } - public String getDestCallerIdNum() - { + public String getDestCallerIdNum() { return destCallerIdNum; } - public void setDestCallerIdNum(String destCallerIdNum) - { + public void setDestCallerIdNum(String destCallerIdNum) { this.destCallerIdNum = destCallerIdNum; } - public String getDestChannel() - { + public String getDestChannel() { return destChannel; } - public void setDestChannel(String destChannel) - { + public void setDestChannel(String destChannel) { this.destChannel = destChannel; } - public String getDestChannelState() - { + public String getDestChannelState() { return destChannelState; } - public void setDestChannelState(String destChannelState) - { + public void setDestChannelState(String destChannelState) { this.destChannelState = destChannelState; } - public String getDestChannelStateDesc() - { + public String getDestChannelStateDesc() { return destChannelStateDesc; } - public void setDestChannelStateDesc(String destChannelStateDesc) - { + public void setDestChannelStateDesc(String destChannelStateDesc) { this.destChannelStateDesc = destChannelStateDesc; } - public String getDestConnectedLineName() - { + public String getDestConnectedLineName() { return destConnectedLineName; } - public void setDestConnectedLineName(String destConnectedLineName) - { + public void setDestConnectedLineName(String destConnectedLineName) { this.destConnectedLineName = destConnectedLineName; } - public String getDestConnectedLineNum() - { + public String getDestConnectedLineNum() { return destConnectedLineNum; } - public void setDestConnectedLineNum(String destConnectedLineNum) - { + public void setDestConnectedLineNum(String destConnectedLineNum) { this.destConnectedLineNum = destConnectedLineNum; } - public String getDestContext() - { + public String getDestContext() { return destContext; } - public void setDestContext(String destContext) - { + public void setDestContext(String destContext) { this.destContext = destContext; } - public String getDestExten() - { + public String getDestExten() { return destExten; } - public void setDestExten(String destExten) - { + public void setDestExten(String destExten) { this.destExten = destExten; } - public String getDestLanguage() - { + public String getDestLanguage() { return destLanguage; } - public void setDestLanguage(String destLanguage) - { + public void setDestLanguage(String destLanguage) { this.destLanguage = destLanguage; } - public String getDestLinkedId() - { + public String getDestLinkedId() { return destLinkedId; } - public void setDestLinkedId(String destLinkedId) - { + public void setDestLinkedId(String destLinkedId) { this.destLinkedId = destLinkedId; } - public String getDestPriority() - { + public String getDestPriority() { return destPriority; } - public void setDestPriority(String destPriority) - { + public void setDestPriority(String destPriority) { this.destPriority = destPriority; } - public String getDestUniqueId() - { + public String getDestUniqueId() { return destUniqueId; } - public void setDestUniqueId(String destUniqueId) - { + public void setDestUniqueId(String destUniqueId) { this.destUniqueId = destUniqueId; } - public String getDialStatus() - { + public String getDialStatus() { return dialStatus; } - public void setDialStatus(String dialStatus) - { + public void setDialStatus(String dialStatus) { this.dialStatus = dialStatus; } - public String getPrivilege() - { + public String getPrivilege() { return privilege; } - public void setPrivilege(String privilege) - { + public void setPrivilege(String privilege) { this.privilege = privilege; } - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String 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 index 6d8382908..4911a06f1 100644 --- a/src/main/java/org/asteriskjava/manager/event/DongleCENDEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DongleCENDEvent.java @@ -1,28 +1,25 @@ 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 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; @@ -56,8 +53,5 @@ public void setEndstatus(String endstatus) { this.endstatus = endstatus; } - - - -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleCallStateChangeEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleCallStateChangeEvent.java index 59e16e263..1c32b334d 100644 --- a/src/main/java/org/asteriskjava/manager/event/DongleCallStateChangeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DongleCallStateChangeEvent.java @@ -1,24 +1,22 @@ 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 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; @@ -36,6 +34,5 @@ public void setNewstate(String newstate) { this.newstate = newstate; } - -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleDeviceEntryEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleDeviceEntryEvent.java index 1ef740d86..08020c101 100644 --- a/src/main/java/org/asteriskjava/manager/event/DongleDeviceEntryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DongleDeviceEntryEvent.java @@ -1,10 +1,9 @@ package org.asteriskjava.manager.event; -public class DongleDeviceEntryEvent extends ResponseEvent -{ +public class DongleDeviceEntryEvent extends ResponseEvent { /** - * + * */ private static final long serialVersionUID = 1L; private String Device; @@ -65,568 +64,455 @@ public class DongleDeviceEntryEvent extends ResponseEvent private String Releasing; private String Initializing; - public DongleDeviceEntryEvent(Object source) - { + public DongleDeviceEntryEvent(Object source) { super(source); } - public String getDevice() - { + public String getDevice() { return Device; } - public void setDevice(String Device) - { + public void setDevice(String Device) { this.Device = Device; } - public String getAudioSetting() - { + public String getAudioSetting() { return AudioSetting; } - public void setAudioSetting(String AudioSetting) - { + public void setAudioSetting(String AudioSetting) { this.AudioSetting = AudioSetting; } - public String getDataSetting() - { + public String getDataSetting() { return DataSetting; } - public void setDataSetting(String DataSetting) - { + public void setDataSetting(String DataSetting) { this.DataSetting = DataSetting; } - public String getIMEISetting() - { + public String getIMEISetting() { return IMEISetting; } - public void setIMEISetting(String IMEISetting) - { + public void setIMEISetting(String IMEISetting) { this.IMEISetting = IMEISetting; } - public String getIMSISetting() - { + public String getIMSISetting() { return IMSISetting; } - public void setIMSISetting(String IMSISetting) - { + public void setIMSISetting(String IMSISetting) { this.IMSISetting = IMSISetting; } - public String getChannelLanguage() - { + public String getChannelLanguage() { return ChannelLanguage; } - public void setChannelLanguage(String ChannelLanguage) - { + public void setChannelLanguage(String ChannelLanguage) { this.ChannelLanguage = ChannelLanguage; } - public String getGroup() - { + public String getGroup() { return Group; } - public void setGroup(String Group) - { + public void setGroup(String Group) { this.Group = Group; } - public String getRXGain() - { + public String getRXGain() { return RXGain; } - public void setRXGain(String RXGain) - { + public void setRXGain(String RXGain) { this.RXGain = RXGain; } - public String getTXGain() - { + public String getTXGain() { return TXGain; } - public void setTXGain(String TXGain) - { + public void setTXGain(String TXGain) { this.TXGain = TXGain; } - public String getU2DIAG() - { + public String getU2DIAG() { return U2DIAG; } - public void setU2DIAG(String U2DIAG) - { + public void setU2DIAG(String U2DIAG) { this.U2DIAG = U2DIAG; } - public String getUseCallingPres() - { + public String getUseCallingPres() { return UseCallingPres; } - public void setUseCallingPres(String UseCallingPres) - { + public void setUseCallingPres(String UseCallingPres) { this.UseCallingPres = UseCallingPres; } - public String getDefaultCallingPres() - { + public String getDefaultCallingPres() { return DefaultCallingPres; } - public void setDefaultCallingPres(String DefaultCallingPres) - { + public void setDefaultCallingPres(String DefaultCallingPres) { this.DefaultCallingPres = DefaultCallingPres; } - public String getAutoDeleteSMS() - { + public String getAutoDeleteSMS() { return AutoDeleteSMS; } - public void setAutoDeleteSMS(String AutoDeleteSMS) - { + public void setAutoDeleteSMS(String AutoDeleteSMS) { this.AutoDeleteSMS = AutoDeleteSMS; } - public String getDisableSMS() - { + public String getDisableSMS() { return DisableSMS; } - public void setDisableSMS(String DisableSMS) - { + public void setDisableSMS(String DisableSMS) { this.DisableSMS = DisableSMS; } - public String getResetDongle() - { + public String getResetDongle() { return ResetDongle; } - public void setResetDongle(String ResetDongle) - { + public void setResetDongle(String ResetDongle) { this.ResetDongle = ResetDongle; } - public String getSMSPDU() - { + public String getSMSPDU() { return SMSPDU; } - public void setSMSPDU(String SMSPDU) - { + public void setSMSPDU(String SMSPDU) { this.SMSPDU = SMSPDU; } - public String getCallWaitingSetting() - { + public String getCallWaitingSetting() { return CallWaitingSetting; } - public void setCallWaitingSetting(String CallWaitingSetting) - { + public void setCallWaitingSetting(String CallWaitingSetting) { this.CallWaitingSetting = CallWaitingSetting; } - public String getDTMF() - { + public String getDTMF() { return DTMF; } - public void setDTMF(String DTMF) - { + public void setDTMF(String DTMF) { this.DTMF = DTMF; } - public String getMinimalDTMFGap() - { + public String getMinimalDTMFGap() { return MinimalDTMFGap; } - public void setMinimalDTMFGap(String MinimalDTMFGap) - { + public void setMinimalDTMFGap(String MinimalDTMFGap) { this.MinimalDTMFGap = MinimalDTMFGap; } - public String getMinimalDTMFDuration() - { + public String getMinimalDTMFDuration() { return MinimalDTMFDuration; } - public void setMinimalDTMFDuration(String MinimalDTMFDuration) - { + public void setMinimalDTMFDuration(String MinimalDTMFDuration) { this.MinimalDTMFDuration = MinimalDTMFDuration; } - public String getMinimalDTMFInterval() - { + public String getMinimalDTMFInterval() { return MinimalDTMFInterval; } - public void setMinimalDTMFInterval(String MinimalDTMFInterval) - { + public void setMinimalDTMFInterval(String MinimalDTMFInterval) { this.MinimalDTMFInterval = MinimalDTMFInterval; } - public String getState() - { + public String getState() { return State; } - public void setState(String State) - { + public void setState(String State) { this.State = State; } - public String getAudioState() - { + public String getAudioState() { return AudioState; } - public void setAudioState(String AudioState) - { + public void setAudioState(String AudioState) { this.AudioState = AudioState; } - public String getDataState() - { + public String getDataState() { return DataState; } - public void setDataState(String DataState) - { + public void setDataState(String DataState) { this.DataState = DataState; } - public String getVoice() - { + public String getVoice() { return Voice; } - public void setVoice(String Voice) - { + public void setVoice(String Voice) { this.Voice = Voice; } - public String getSMS() - { + public String getSMS() { return SMS; } - public void setSMS(String SMS) - { + public void setSMS(String SMS) { this.SMS = SMS; } - public String getManufacturer() - { + public String getManufacturer() { return Manufacturer; } - public void setManufacturer(String Manufacturer) - { + public void setManufacturer(String Manufacturer) { this.Manufacturer = Manufacturer; } - public String getModel() - { + public String getModel() { return Model; } - public void setModel(String Model) - { + public void setModel(String Model) { this.Model = Model; } - public String getFirmware() - { + public String getFirmware() { return Firmware; } - public void setFirmware(String Firmware) - { + public void setFirmware(String Firmware) { this.Firmware = Firmware; } - public String getIMEIState() - { + public String getIMEIState() { return IMEIState; } - public void setIMEIState(String IMEIState) - { + public void setIMEIState(String IMEIState) { this.IMEIState = IMEIState; } - public String getGSMRegistrationStatus() - { + public String getGSMRegistrationStatus() { return GSMRegistrationStatus; } - public void setGSMRegistrationStatus(String GSMRegistrationStatus) - { + public void setGSMRegistrationStatus(String GSMRegistrationStatus) { this.GSMRegistrationStatus = GSMRegistrationStatus; } - public String getRSSI() - { + public String getRSSI() { return RSSI; } - public void setRSSI(String RSSI) - { + public void setRSSI(String RSSI) { this.RSSI = RSSI; } - public String getMode() - { + public String getMode() { return Mode; } - public void setMode(String Mode) - { + public void setMode(String Mode) { this.Mode = Mode; } - public String getSubmode() - { + public String getSubmode() { return Submode; } - public void setSubmode(String Submode) - { + public void setSubmode(String Submode) { this.Submode = Submode; } - public String getProviderName() - { + public String getProviderName() { return ProviderName; } - public void setProviderName(String ProviderName) - { + public void setProviderName(String ProviderName) { this.ProviderName = ProviderName; } - public String getLocationAreaCode() - { + public String getLocationAreaCode() { return LocationAreaCode; } - public void setLocationAreaCode(String LocationAreaCode) - { + public void setLocationAreaCode(String LocationAreaCode) { this.LocationAreaCode = LocationAreaCode; } - public String getCellID() - { + public String getCellID() { return CellID; } - public void setCellID(String CellID) - { + public void setCellID(String CellID) { this.CellID = CellID; } - public String getSubscriberNumber() - { + public String getSubscriberNumber() { return SubscriberNumber; } - public void setSubscriberNumber(String SubscriberNumber) - { + public void setSubscriberNumber(String SubscriberNumber) { this.SubscriberNumber = SubscriberNumber; } - public String getSMSServiceCenter() - { + public String getSMSServiceCenter() { return SMSServiceCenter; } - public void setSMSServiceCenter(String SMSServiceCenter) - { + public void setSMSServiceCenter(String SMSServiceCenter) { this.SMSServiceCenter = SMSServiceCenter; } - public String getUseUCS2Encoding() - { + public String getUseUCS2Encoding() { return UseUCS2Encoding; } - public void setUseUCS2Encoding(String UseUCS2Encoding) - { + public void setUseUCS2Encoding(String UseUCS2Encoding) { this.UseUCS2Encoding = UseUCS2Encoding; } - public String getUSSDUse7BitEncoding() - { + public String getUSSDUse7BitEncoding() { return USSDUse7BitEncoding; } - public void setUSSDUse7BitEncoding(String USSDUse7BitEncoding) - { + public void setUSSDUse7BitEncoding(String USSDUse7BitEncoding) { this.USSDUse7BitEncoding = USSDUse7BitEncoding; } - public String getUSSDUseUCS2Decoding() - { + public String getUSSDUseUCS2Decoding() { return USSDUseUCS2Decoding; } - public void setUSSDUseUCS2Decoding(String USSDUseUCS2Decoding) - { + public void setUSSDUseUCS2Decoding(String USSDUseUCS2Decoding) { this.USSDUseUCS2Decoding = USSDUseUCS2Decoding; } - public String getTasksInQueue() - { + public String getTasksInQueue() { return TasksInQueue; } - public void setTasksInQueue(String TasksInQueue) - { + public void setTasksInQueue(String TasksInQueue) { this.TasksInQueue = TasksInQueue; } - public String getCommandsInQueue() - { + public String getCommandsInQueue() { return CommandsInQueue; } - public void setCommandsInQueue(String CommandsInQueue) - { + public void setCommandsInQueue(String CommandsInQueue) { this.CommandsInQueue = CommandsInQueue; } - public String getCallWaitingState() - { + public String getCallWaitingState() { return CallWaitingState; } - public void setCallWaitingState(String CallWaitingState) - { + public void setCallWaitingState(String CallWaitingState) { this.CallWaitingState = CallWaitingState; } - public String getCurrentDeviceState() - { + public String getCurrentDeviceState() { return CurrentDeviceState; } - public void setCurrentDeviceState(String CurrentDeviceState) - { + public void setCurrentDeviceState(String CurrentDeviceState) { this.CurrentDeviceState = CurrentDeviceState; } - public String getDesiredDeviceState() - { + public String getDesiredDeviceState() { return DesiredDeviceState; } - public void setDesiredDeviceState(String DesiredDeviceState) - { + public void setDesiredDeviceState(String DesiredDeviceState) { this.DesiredDeviceState = DesiredDeviceState; } - public String getCallsChannels() - { + public String getCallsChannels() { return CallsChannels; } - public void setCallsChannels(String CallsChannels) - { + public void setCallsChannels(String CallsChannels) { this.CallsChannels = CallsChannels; } - public String getActive() - { + public String getActive() { return Active; } - public void setActive(String Active) - { + public void setActive(String Active) { this.Active = Active; } - public String getHeld() - { + public String getHeld() { return Held; } - public void setHeld(String Held) - { + public void setHeld(String Held) { this.Held = Held; } - public String getDialing() - { + public String getDialing() { return Dialing; } - public void setDialing(String Dialing) - { + public void setDialing(String Dialing) { this.Dialing = Dialing; } - public String getAlerting() - { + public String getAlerting() { return Alerting; } - public void setAlerting(String Alerting) - { + public void setAlerting(String Alerting) { this.Alerting = Alerting; } - public String getIncoming() - { + public String getIncoming() { return Incoming; } - public void setIncoming(String Incoming) - { + public void setIncoming(String Incoming) { this.Incoming = Incoming; } - public String getWaiting() - { + public String getWaiting() { return Waiting; } - public void setWaiting(String Waiting) - { + public void setWaiting(String Waiting) { this.Waiting = Waiting; } - public String getReleasing() - { + public String getReleasing() { return Releasing; } - public void setReleasing(String Releasing) - { + public void setReleasing(String Releasing) { this.Releasing = Releasing; } - public String getInitializing() - { + public String getInitializing() { return Initializing; } - public void setInitializing(String 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 index 6f58b2d70..cbc3d457a 100644 --- a/src/main/java/org/asteriskjava/manager/event/DongleNewCMGREvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DongleNewCMGREvent.java @@ -1,22 +1,18 @@ package org.asteriskjava.manager.event; -public class DongleNewCMGREvent extends ManagerEvent -{ +public class DongleNewCMGREvent extends ManagerEvent { private static final long serialVersionUID = 3257845467831284784L; private String device; - public DongleNewCMGREvent(Object source) - { + public DongleNewCMGREvent(Object source) { super(source); } - public String getDevice() - { + public String getDevice() { return this.device; } - public void setDevice(String 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 index 9f1535cdb..ba794e9e3 100644 --- a/src/main/java/org/asteriskjava/manager/event/DongleNewSMSBase64Event.java +++ b/src/main/java/org/asteriskjava/manager/event/DongleNewSMSBase64Event.java @@ -1,38 +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; - } -} \ No newline at end of file +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 index 81fce3390..b6d07b1f0 100644 --- a/src/main/java/org/asteriskjava/manager/event/DongleNewSMSEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DongleNewSMSEvent.java @@ -1,34 +1,32 @@ 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 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; @@ -47,4 +45,4 @@ public void setMessageline0(String messageline0) { } -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/DongleShowDevicesCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleShowDevicesCompleteEvent.java index 45b3f0de1..c61e690ea 100644 --- a/src/main/java/org/asteriskjava/manager/event/DongleShowDevicesCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DongleShowDevicesCompleteEvent.java @@ -19,15 +19,13 @@ /** * A DahdiShowChannelsCompleteEvent is triggered after the state of all Dahdi channels has been reported * in response to a DahdiShowChannelsAction. - * - * @see org.asteriskjava.manager.action.DahdiShowChannelsAction - * @see org.asteriskjava.manager.event.DahdiShowChannelsEvent - * + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.DahdiShowChannelsAction + * @see org.asteriskjava.manager.event.DahdiShowChannelsEvent */ -public class DongleShowDevicesCompleteEvent extends ResponseEvent -{ +public class DongleShowDevicesCompleteEvent extends ResponseEvent { /** * Serial version identifier */ @@ -44,28 +42,25 @@ public Integer getItems() { public void setItems(Integer items) { this.items = items; } - + /** * @param source */ - public DongleShowDevicesCompleteEvent(Object 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() - { + public String getEventlist() { return eventlist; } - public void setEventlist(String eventlist) - { + public void setEventlist(String eventlist) { this.eventlist = eventlist; } @@ -74,8 +69,7 @@ public void setEventlist(String eventlist) * * @return the number of channels reported. */ - public Integer getListitems() - { + public Integer getListitems() { return listitems; } @@ -84,8 +78,7 @@ public Integer getListitems() * * @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/DongleStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/DongleStatusEvent.java index 622087aea..6ea1c24d6 100644 --- a/src/main/java/org/asteriskjava/manager/event/DongleStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DongleStatusEvent.java @@ -1,23 +1,21 @@ package org.asteriskjava.manager.event; -public class DongleStatusEvent extends ManagerEvent -{ - private static final long serialVersionUID = 3257845467831284784L; - private String device; - private String status; +public class DongleStatusEvent extends ManagerEvent { + private static final long serialVersionUID = 3257845467831284784L; + private String device; + private String status; - public DongleStatusEvent(Object source) - { - super(source); - } + public DongleStatusEvent(Object source) { + super(source); + } - public String getDevice() { - return this.device; - } + public String getDevice() { + return this.device; + } - public void setDevice(String device) { - this.device = device; - } + public void setDevice(String device) { + this.device = device; + } public String getStatus() { return status; @@ -27,6 +25,5 @@ public void setStatus(String status) { this.status = status; } - -} \ No newline at end of file +} diff --git a/src/main/java/org/asteriskjava/manager/event/DtmfBeginEvent.java b/src/main/java/org/asteriskjava/manager/event/DtmfBeginEvent.java index 31808823b..eee04cc48 100644 --- a/src/main/java/org/asteriskjava/manager/event/DtmfBeginEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DtmfBeginEvent.java @@ -3,17 +3,15 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public class DtmfBeginEvent extends DtmfEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; +public class DtmfBeginEvent extends DtmfEvent { + /** + * + */ + private static final long serialVersionUID = 1L; - public DtmfBeginEvent(Object source) - { - super(source); - setBegin(true); - setEnd(false); - } + 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 index a92633dfc..245847d22 100644 --- a/src/main/java/org/asteriskjava/manager/event/DtmfEndEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DtmfEndEvent.java @@ -3,28 +3,24 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public class DtmfEndEvent extends DtmfEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; - private Integer durationMs; +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 DtmfEndEvent(Object source) { + super(source); + setBegin(false); + setEnd(true); + } - public Integer getDurationMs() - { - return durationMs; - } + public Integer getDurationMs() { + return durationMs; + } - public void setDurationMs(Integer durationMs) - { - this.durationMs = 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 329328b43..14b107a8c 100644 --- a/src/main/java/org/asteriskjava/manager/event/DtmfEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/DtmfEvent.java @@ -39,8 +39,7 @@ * @version $Id$ * @since 1.0.0 */ -public class DtmfEvent extends ManagerEvent -{ +public class DtmfEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -55,7 +54,7 @@ public class DtmfEvent extends ManagerEvent private String direction; private Boolean begin; private Boolean end; - + private String language; private String linkedId; private String accountCode; @@ -65,8 +64,7 @@ public class DtmfEvent extends ManagerEvent * * @param source */ - public DtmfEvent(Object source) - { + public DtmfEvent(Object source) { super(source); } @@ -76,8 +74,7 @@ public DtmfEvent(Object source) * * @return the channel name. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -86,8 +83,7 @@ public String getChannel() * * @param channel the channel name. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -96,8 +92,7 @@ public void setChannel(String channel) * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -106,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; } @@ -116,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; } @@ -126,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; } @@ -140,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; } @@ -154,8 +145,7 @@ public String getDirection() * * @param direction "Received" or "Sent". */ - public void setDirection(String direction) - { + public void setDirection(String direction) { this.direction = direction; } @@ -168,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; } @@ -181,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; } @@ -192,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; } @@ -205,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; } @@ -214,11 +200,10 @@ 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() - { + public boolean isReceived() { return DIRECTION_RECEIVED.equalsIgnoreCase(direction); } @@ -226,43 +211,36 @@ public boolean isReceived() * 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() - { + public boolean isSent() { return DIRECTION_SENT.equalsIgnoreCase(direction); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - - -} \ No newline at end of file + + +} 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 index 723027f02..3781a4cf1 100644 --- a/src/main/java/org/asteriskjava/manager/event/EndpointList.java +++ b/src/main/java/org/asteriskjava/manager/event/EndpointList.java @@ -21,16 +21,15 @@ * 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 EndpointList extends ResponseEvent -{ +public class EndpointList extends ResponseEvent { /** * Serial version identifier. */ @@ -51,31 +50,28 @@ public class EndpointList extends ResponseEvent /** * Creates a new instance. - * + * * @param source */ - public EndpointList(Object 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() - { + 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; } @@ -85,116 +81,94 @@ public void setListItems(Integer listItems) * Available since Asterisk 1.6. * * @return always returns "Complete" confirming that all PeerEntry events have - * been sent. + * 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; } - public String getAor() - { + public String getAor() { return aor; } - public void setAor(String aor) - { + public void setAor(String aor) { this.aor = aor; } - public String getAuths() - { + public String getAuths() { return auths; } - public void setAuths(String auths) - { + public void setAuths(String auths) { this.auths = auths; } - public String getObjectName() - { + public String getObjectName() { return objectName; } - public void setObjectName(String objectName) - { + public void setObjectName(String objectName) { this.objectName = objectName; } - public String getTransport() - { + public String getTransport() { return transport; } - public void setTransport(String transport) - { + public void setTransport(String transport) { this.transport = transport; } - public String getOutboundAuths() - { + public String getOutboundAuths() { return outboundAuths; } - public void setOutboundAuths(String outboundAuths) - { + public void setOutboundAuths(String outboundAuths) { this.outboundAuths = outboundAuths; } - public String getDevicestate() - { + public String getDevicestate() { return devicestate; } - public void setDevicestate(String devicestate) - { + public void setDevicestate(String devicestate) { this.devicestate = devicestate; } - public String getEvent() - { + public String getEvent() { return event; } - public void setEvent(String event) - { + public void setEvent(String event) { this.event = event; } - public String getObjectType() - { + public String getObjectType() { return objectType; } - public void setObjectType(String objectType) - { + public void setObjectType(String objectType) { this.objectType = objectType; } - public String getContacts() - { + public String getContacts() { return contacts; } - public void setContacts(String contacts) - { + public void setContacts(String contacts) { this.contacts = contacts; } - public String getActiveChannels() - { + public String getActiveChannels() { return activeChannels; } - public void setActiveChannels(String 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 index e1a1a5dd1..432a2de94 100644 --- a/src/main/java/org/asteriskjava/manager/event/EndpointListComplete.java +++ b/src/main/java/org/asteriskjava/manager/event/EndpointListComplete.java @@ -17,20 +17,17 @@ 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. + * An EndpointListComplete event is triggered after the details of all end points have been + * reported in response to a PJSIPShowEndpoints event. *

    - * Available since Asterisk 1.2 - * - * @see org.asteriskjava.manager.event.PeerEntryEvent - * @see org.asteriskjava.manager.action.SipPeersAction - * @see org.asteriskjava.manager.action.SipShowPeerAction + * Available since Asterisk 12 + * * @author srt * @version $Id$ - * @since 0.2 + * @see org.asteriskjava.manager.event.PJSipShowEndpoints + * @since 12 */ -public class EndpointListComplete extends ResponseEvent -{ +public class EndpointListComplete extends ResponseEvent { /** * Serial version identifier. */ @@ -40,31 +37,28 @@ public class EndpointListComplete extends ResponseEvent /** * Creates a new instance. - * + * * @param source */ - public EndpointListComplete(Object source) - { + public EndpointListComplete(Object source) { super(source); } /** - * Returns the number of PeerEvents that have been reported. - * - * @return the number of PeerEvents that have been reported. + * Returns the number of Endpoints that have been reported. + * + * @return the number of Endpoints that have been reported. */ - public Integer getListItems() - { + public Integer getListItems() { return listItems; } /** - * Sets the number of PeerEvents that have been reported. - * + * Sets the number of Endpoints 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,16 +68,14 @@ public void setListItems(Integer listItems) * Available since Asterisk 1.6. * * @return always returns "Complete" confirming that all PeerEntry events have - * been sent. + * 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/ExtensionStatusEvent.java b/src/main/java/org/asteriskjava/manager/event/ExtensionStatusEvent.java index 185760c2a..037d273a1 100644 --- a/src/main/java/org/asteriskjava/manager/event/ExtensionStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ExtensionStatusEvent.java @@ -33,8 +33,7 @@ * @author srt * @version $Id$ */ -public class ExtensionStatusEvent extends ManagerEvent -{ +public class ExtensionStatusEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -70,9 +69,8 @@ public class ExtensionStatusEvent extends ManagerEvent private String callerId; private String statustext; - - public ExtensionStatusEvent(Object source) - { + + public ExtensionStatusEvent(Object source) { super(source); } @@ -84,13 +82,11 @@ public ExtensionStatusEvent(Object source) * @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; } @@ -106,16 +102,14 @@ public void setHint(String hint) *

  • 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; } @@ -127,8 +121,7 @@ public void setStatus(Integer status) * @return the Caller*ID. * @since 0.3 */ - public String getCallerId() - { + public String getCallerId() { return callerId; } @@ -138,19 +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; - } + + 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 4d3ae442e..3becf967b 100644 --- a/src/main/java/org/asteriskjava/manager/event/FaxReceivedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/FaxReceivedEvent.java @@ -24,13 +24,12 @@ * 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. */ @@ -44,150 +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 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 d80a6f2ab..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. */ @@ -57,8 +56,12 @@ public class FaxStatusEvent extends AbstractFaxEvent 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); } @@ -66,497 +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() - { + public String getLocalStationId() { return localStationId; } /** * @param localStationId the localStationId to set */ - public void setLocalStationId(String localStationId) - { + public void setLocalStationId(String localStationId) { this.localStationId = localStationId; } /** * @return the callerId */ - public String getCallerId() - { + public String getCallerId() { return callerId; } /** * @param callerId the callerId to set */ - public void setCallerId(String callerid) - { + public void setCallerId(String callerid) { this.callerId = callerid; } /** * @return the status */ - public String getStatus() - { + public String getStatus() { return status; } /** * @param status the status to set */ - public void setStatus(String status) - { + public void setStatus(String status) { this.status = status; } /** * @return the operation */ - public String getOperation() - { + public String getOperation() { return operation; } /** * @param context the context to set */ - public void setOperation(String operation) - { + 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 84e220f45..3577e22b7 100644 --- a/src/main/java/org/asteriskjava/manager/event/FullyBootedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/FullyBootedEvent.java @@ -14,15 +14,13 @@ * 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); } @@ -31,8 +29,7 @@ public FullyBootedEvent(Object source) * * @return the status. */ - public String getStatus() - { + public String getStatus() { return status; } @@ -41,24 +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 String getLastreload() { + return lastreload; + } - public void setLastreload(String lastreload) { - this.lastreload = lastreload; - } + public void setLastreload(String lastreload) { + this.lastreload = lastreload; + } - public Integer getUptime() { - return uptime; - } + public Integer getUptime() { + return uptime; + } - public void setUptime(Integer uptime) { - this.uptime = 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 cccacb909..214dae62b 100644 --- a/src/main/java/org/asteriskjava/manager/event/HangupEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/HangupEvent.java @@ -24,8 +24,7 @@ * @author srt * @version $Id$ */ -public class HangupEvent extends AbstractChannelStateEvent -{ +public class HangupEvent extends AbstractChannelStateEvent { /** * Serializable version identifier. */ @@ -36,18 +35,15 @@ public class HangupEvent extends AbstractChannelStateEvent private String language; private String linkedId; - public HangupEvent(Object source) - { + public HangupEvent(Object source) { super(source); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } @@ -57,8 +53,7 @@ public void setLanguage(String language) * @return the hangup cause. * @see org.asteriskjava.live.HangupCause */ - public Integer getCause() - { + public Integer getCause() { return cause; } @@ -67,8 +62,7 @@ public Integer getCause() * * @param cause the hangup cause. */ - public void setCause(Integer cause) - { + public void setCause(Integer cause) { this.cause = cause; } @@ -78,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; } @@ -89,24 +82,20 @@ 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() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } @Override - public String toString() - { + public String toString() { StringBuilder builder = new StringBuilder(); builder.append("HangupEvent [cause="); builder.append(cause); 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 index 3852045be..6ebf0a036 100644 --- a/src/main/java/org/asteriskjava/manager/event/HangupRequestEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/HangupRequestEvent.java @@ -21,8 +21,7 @@ *

    * It is implemented in channel.c */ -public class HangupRequestEvent extends AbstractChannelEvent -{ +public class HangupRequestEvent extends AbstractChannelEvent { /** * Serializable version identifier. */ @@ -32,18 +31,15 @@ public class HangupRequestEvent extends AbstractChannelEvent private String language; private String linkedId; - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public HangupRequestEvent(Object source) - { + public HangupRequestEvent(Object source) { super(source); } @@ -53,8 +49,7 @@ public HangupRequestEvent(Object source) * @return the hangup cause. * @see org.asteriskjava.live.HangupCause */ - public Integer getCause() - { + public Integer getCause() { return cause; } @@ -63,18 +58,15 @@ public Integer getCause() * * @param cause the hangup cause. */ - public void setCause(Integer cause) - { + public void setCause(Integer cause) { this.cause = cause; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String 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 6c2b40435..ad3d21065 100644 --- a/src/main/java/org/asteriskjava/manager/event/HoldEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/HoldEvent.java @@ -32,22 +32,20 @@ * @version $Id$ * @since 0.2 */ -public class HoldEvent extends AbstractHoldEvent -{ +public class HoldEvent extends AbstractHoldEvent { /** * Serializable version identifier. */ private static final long serialVersionUID = 0L; private String musicClass; - + /** * Creates a new HoldEvent. * * @param source */ - public HoldEvent(Object source) - { + public HoldEvent(Object source) { super(source); /* * Asterisk prior to 1.6 and after 11 uses Hold and Unhold events @@ -58,14 +56,12 @@ public HoldEvent(Object source) setStatus(true); } - public String getMusicClass() - { + public String getMusicClass() { return musicClass; } - public void setMusicClass(String musicClass) - { + public void setMusicClass(String musicClass) { this.musicClass = musicClass; } - + } 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 index e478e3544..866dc725e 100644 --- a/src/main/java/org/asteriskjava/manager/event/InvalidPasswordEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/InvalidPasswordEvent.java @@ -3,136 +3,148 @@ /** * Created by Alexander Polakov on 1/23/15. */ -public class InvalidPasswordEvent extends ManagerEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; - 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; - - 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 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 b626dcbaa..22c355ef2 100644 --- a/src/main/java/org/asteriskjava/manager/event/JoinEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/JoinEvent.java @@ -23,8 +23,7 @@ * * @author srt */ -public class JoinEvent extends QueueEvent -{ +public class JoinEvent extends QueueEvent { /** * Serializable version identifier. */ @@ -33,8 +32,7 @@ public class JoinEvent extends QueueEvent protected String callerIdName; protected Integer position; - public JoinEvent(Object source) - { + public JoinEvent(Object source) { super(source); } @@ -46,8 +44,7 @@ public JoinEvent(Object source) * @deprecated since 1.0.0, use {@link #getCallerIdNum()} instead. */ @Deprecated - public String getCallerId() - { + public String getCallerId() { return callerIdNum; } @@ -55,26 +52,23 @@ public String getCallerId() * 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. + * queue. */ - public void setCallerId(String callerId) - { + public void setCallerId(String callerId) { this.callerIdNum = callerId; } /** * 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 ac069e286..c6eada661 100644 --- a/src/main/java/org/asteriskjava/manager/event/LeaveEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/LeaveEvent.java @@ -19,11 +19,10 @@ /** * A LeaveEvent is triggered when a channel leaves a queue.

    * It is implemented in apps/app_queue.c - * + * * @author srt */ -public class LeaveEvent extends QueueEvent -{ +public class LeaveEvent extends QueueEvent { /** * Serializable version identifier */ @@ -34,21 +33,18 @@ public class LeaveEvent extends QueueEvent /** * @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() - { + public Integer getPosition() { return position; } - public void setPosition(Integer 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 1f8ceea49..7e9740bed 100644 --- a/src/main/java/org/asteriskjava/manager/event/ListDialplanEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ListDialplanEvent.java @@ -12,8 +12,7 @@ * @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"; @@ -24,9 +23,11 @@ public class ListDialplanEvent extends ResponseEvent 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); } @@ -35,54 +36,46 @@ public ListDialplanEvent(Object source) * * @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; } /** * 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); } } @@ -92,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; } @@ -106,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 index 51e0cc9d3..45dd94ba5 100644 --- a/src/main/java/org/asteriskjava/manager/event/LocalBridgeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/LocalBridgeEvent.java @@ -19,14 +19,13 @@ /** * 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 -{ +public class LocalBridgeEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -63,14 +62,13 @@ public class LocalBridgeEvent extends ManagerEvent 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) - { + public LocalBridgeEvent(Object source) { super(source); } @@ -134,9 +132,9 @@ public void setCallerId2(String callerId2) { /** * Local optimization values - * - * Yes - * No + *

    + * Yes + * No * * @return Local optimization */ @@ -149,283 +147,227 @@ public void setLocalOptimization(String localOptimization) { this.localOptimization = localOptimization; } - public String getLocalOneCalleridName() - { + public String getLocalOneCalleridName() { return localOneCalleridName; } - public void setLocalOneCalleridName(String localOneCalleridName) - { + public void setLocalOneCalleridName(String localOneCalleridName) { this.localOneCalleridName = localOneCalleridName; } - public String getLocalTwoChannel() - { + public String getLocalTwoChannel() { return localTwoChannel; } - public void setLocalTwoChannel(String localTwoChannel) - { + public void setLocalTwoChannel(String localTwoChannel) { this.localTwoChannel = localTwoChannel; } - public String getLocalTwoLanguage() - { + public String getLocalTwoLanguage() { return localTwoLanguage; } - public void setLocalTwoLanguage(String localTwoLanguage) - { + public void setLocalTwoLanguage(String localTwoLanguage) { this.localTwoLanguage = localTwoLanguage; } - public String getLocalTwoExten() - { + public String getLocalTwoExten() { return localTwoExten; } - public void setLocalTwoExten(String localTwoExten) - { + public void setLocalTwoExten(String localTwoExten) { this.localTwoExten = localTwoExten; } - public String getLocalOneChannel() - { + public String getLocalOneChannel() { return localOneChannel; } - public void setLocalOneChannel(String localOneChannel) - { + public void setLocalOneChannel(String localOneChannel) { this.localOneChannel = localOneChannel; } - public String getLocalOneContext() - { + public String getLocalOneContext() { return localOneContext; } - public void setLocalOneContext(String localOneContext) - { + public void setLocalOneContext(String localOneContext) { this.localOneContext = localOneContext; } - public String getLocalOneConnectedLineNum() - { + public String getLocalOneConnectedLineNum() { return localOneConnectedLineNum; } - public void setLocalOneConnectedLineNum(String localOneConnectedLineNum) - { + public void setLocalOneConnectedLineNum(String localOneConnectedLineNum) { this.localOneConnectedLineNum = localOneConnectedLineNum; } - public String getLocalOneConnectedLineName() - { + public String getLocalOneConnectedLineName() { return localOneConnectedLineName; } - public void setLocalOneConnectedLineName(String localOneConnectedLineName) - { + public void setLocalOneConnectedLineName(String localOneConnectedLineName) { this.localOneConnectedLineName = localOneConnectedLineName; } - public String getLocalOneChannelStateDesc() - { + public String getLocalOneChannelStateDesc() { return localOneChannelStateDesc; } - public void setLocalOneChannelStateDesc(String localOneChannelStateDesc) - { + public void setLocalOneChannelStateDesc(String localOneChannelStateDesc) { this.localOneChannelStateDesc = localOneChannelStateDesc; } - public String getLocalOneChannelState() - { + public String getLocalOneChannelState() { return localOneChannelState; } - public void setLocalOneChannelState(String localOneChannelState) - { + public void setLocalOneChannelState(String localOneChannelState) { this.localOneChannelState = localOneChannelState; } - public String getLocalOneExten() - { + public String getLocalOneExten() { return localOneExten; } - public void setLocalOneExten(String localOneExten) - { + public void setLocalOneExten(String localOneExten) { this.localOneExten = localOneExten; } - public String getLocalOneLanguage() - { + public String getLocalOneLanguage() { return localOneLanguage; } - public void setLocalOneLanguage(String localOneLanguage) - { + public void setLocalOneLanguage(String localOneLanguage) { this.localOneLanguage = localOneLanguage; } - public String getLocalOnePriority() - { + public String getLocalOnePriority() { return localOnePriority; } - public void setLocalOnePriority(String localOnePriority) - { + public void setLocalOnePriority(String localOnePriority) { this.localOnePriority = localOnePriority; } - public String getLocalOneUniqueId() - { + public String getLocalOneUniqueId() { return localOneUniqueId; } - public void setLocalOneUniqueId(String localOneUniqueId) - { + public void setLocalOneUniqueId(String localOneUniqueId) { this.localOneUniqueId = localOneUniqueId; } - public String getLocalTwochannelState() - { + public String getLocalTwochannelState() { return localTwochannelState; } - public void setLocalTwochannelState(String localTwochannelState) - { + public void setLocalTwochannelState(String localTwochannelState) { this.localTwochannelState = localTwochannelState; } - public String getLocalTwoChannelStateDesc() - { + public String getLocalTwoChannelStateDesc() { return localTwoChannelStateDesc; } - public void setLocalTwoChannelStateDesc(String localTwoChannelStateDesc) - { + public void setLocalTwoChannelStateDesc(String localTwoChannelStateDesc) { this.localTwoChannelStateDesc = localTwoChannelStateDesc; } - public String getLocalTwoPriority() - { + public String getLocalTwoPriority() { return localTwoPriority; } - public void setLocalTwoPriority(String localTwoPriority) - { + public void setLocalTwoPriority(String localTwoPriority) { this.localTwoPriority = localTwoPriority; } - public String getLocalTwoContext() - { + public String getLocalTwoContext() { return localTwoContext; } - public void setLocalTwoContext(String localTwoContext) - { + public void setLocalTwoContext(String localTwoContext) { this.localTwoContext = localTwoContext; } - public String getLocalTwoCalleridNum() - { + public String getLocalTwoCalleridNum() { return localTwoCalleridNum; } - public void setLocalTwoCalleridNum(String localTwoCalleridNum) - { + public void setLocalTwoCalleridNum(String localTwoCalleridNum) { this.localTwoCalleridNum = localTwoCalleridNum; } - public String getLocalTwoCalleridName() - { + public String getLocalTwoCalleridName() { return localTwoCalleridName; } - public void setLocalTwoCalleridName(String localTwoCalleridName) - { + public void setLocalTwoCalleridName(String localTwoCalleridName) { this.localTwoCalleridName = localTwoCalleridName; } - public String getLocalTwoUniqueid() - { + public String getLocalTwoUniqueid() { return localTwoUniqueid; } - public void setLocalTwoUniqueid(String localTwoUniqueid) - { + public void setLocalTwoUniqueid(String localTwoUniqueid) { this.localTwoUniqueid = localTwoUniqueid; } - public String getLocalOneCalleridNum() - { + public String getLocalOneCalleridNum() { return localOneCalleridNum; } - public void setLocalOneCalleridNum(String localOneCalleridNum) - { + public void setLocalOneCalleridNum(String localOneCalleridNum) { this.localOneCalleridNum = localOneCalleridNum; } - public String getLocalTwoConnectedLineName() - { + public String getLocalTwoConnectedLineName() { return localTwoConnectedLineName; } - public void setLocalTwoConnectedLineName(String localTwoConnectedLineName) - { + public void setLocalTwoConnectedLineName(String localTwoConnectedLineName) { this.localTwoConnectedLineName = localTwoConnectedLineName; } - public String getLocalTwoConnectedLineNum() - { + public String getLocalTwoConnectedLineNum() { return localTwoConnectedLineNum; } - public void setLocalTwoConnectedLineNum(String localTwoConnectedLineNum) - { + public void setLocalTwoConnectedLineNum(String localTwoConnectedLineNum) { this.localTwoConnectedLineNum = localTwoConnectedLineNum; } - public String getLocalTwoLinkedid() - { + public String getLocalTwoLinkedid() { return localTwoLinkedid; } - public void setLocalTwoLinkedid(String localTwoLinkedid) - { + public void setLocalTwoLinkedid(String localTwoLinkedid) { this.localTwoLinkedid = localTwoLinkedid; } - public String getLocalOneLinkedid() - { + public String getLocalOneLinkedid() { return localOneLinkedid; } - public void setLocalOneLinkedid(String localOneLinkedid) - { + public void setLocalOneLinkedid(String localOneLinkedid) { this.localOneLinkedid = localOneLinkedid; } - public String getLocalOneAccountCode() - { + public String getLocalOneAccountCode() { return localOneAccountCode; } - public void setLocalOneAccountCode(String localOneAccountCode) - { + public void setLocalOneAccountCode(String localOneAccountCode) { this.localOneAccountCode = localOneAccountCode; } - public String getLocalTwoAccountCode() - { + public String getLocalTwoAccountCode() { return localTwoAccountCode; } - public void setLocalTwoAccountCode(String 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 index a05baf9ae..aa815f099 100644 --- a/src/main/java/org/asteriskjava/manager/event/LocalOptimizationBeginEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/LocalOptimizationBeginEvent.java @@ -20,8 +20,7 @@ * 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 -{ +public class LocalOptimizationBeginEvent extends ManagerEvent { private static final long serialVersionUID = 0L; private Integer id; @@ -73,448 +72,359 @@ public class LocalOptimizationBeginEvent extends ManagerEvent private String localOneLanguage; private String sourceLanguage; - public LocalOptimizationBeginEvent(Object source) - { + public LocalOptimizationBeginEvent(Object source) { super(source); } - public Integer getId() - { + public Integer getId() { return this.id; } - public void setId(Integer value) - { + public void setId(Integer value) { this.id = value; } - public String getDestUniqueId() - { + public String getDestUniqueId() { return this.destUniqueId; } - public void setDestUniqueId(String value) - { + public void setDestUniqueId(String value) { this.destUniqueId = value; } - public String getLocalOneChannel() - { + public String getLocalOneChannel() { return this.localOneChannel; } - public void setLocalOneChannel(String value) - { + public void setLocalOneChannel(String value) { this.localOneChannel = value; } - public String getLocalOneChannelState() - { + public String getLocalOneChannelState() { return this.localOneChannelState; } - public void setLocalOneChannelState(String value) - { + public void setLocalOneChannelState(String value) { this.localOneChannelState = value; } - public String getLocalOneChannelStateDesc() - { + public String getLocalOneChannelStateDesc() { return this.localOneChannelStateDesc; } - public void setLocalOneChannelStateDesc(String value) - { + public void setLocalOneChannelStateDesc(String value) { this.localOneChannelStateDesc = value; } - public String getLocalOneCallerIDNum() - { + public String getLocalOneCallerIDNum() { return this.localOneCallerIDNum; } - public void setLocalOneCallerIDNum(String value) - { + public void setLocalOneCallerIDNum(String value) { this.localOneCallerIDNum = value; } - public String getLocalOneCallerIDName() - { + public String getLocalOneCallerIDName() { return this.localOneCallerIDName; } - public void setLocalOneCallerIDName(String value) - { + public void setLocalOneCallerIDName(String value) { this.localOneCallerIDName = value; } - public String getLocalOneConnectedLineNum() - { + public String getLocalOneConnectedLineNum() { return this.localOneConnectedLineNum; } - public void setLocalOneConnectedLineNum(String value) - { + public void setLocalOneConnectedLineNum(String value) { this.localOneConnectedLineNum = value; } - public String getLocalOneConnectedLineName() - { + public String getLocalOneConnectedLineName() { return this.localOneConnectedLineName; } - public void setLocalOneConnectedLineName(String value) - { + public void setLocalOneConnectedLineName(String value) { this.localOneConnectedLineName = value; } - public String getLocalOneAccountCode() - { + public String getLocalOneAccountCode() { return this.localOneAccountCode; } - public void setLocalOneAccountCode(String value) - { + public void setLocalOneAccountCode(String value) { this.localOneAccountCode = value; } - public String getLocalOneContext() - { + public String getLocalOneContext() { return this.localOneContext; } - public void setLocalOneContext(String value) - { + public void setLocalOneContext(String value) { this.localOneContext = value; } - public String getLocalOneExten() - { + public String getLocalOneExten() { return this.localOneExten; } - public void setLocalOneExten(String value) - { + public void setLocalOneExten(String value) { this.localOneExten = value; } - public Integer getLocalOnePriority() - { + public Integer getLocalOnePriority() { return this.localOnePriority; } - public void setLocalOnePriority(Integer value) - { + public void setLocalOnePriority(Integer value) { this.localOnePriority = value; } - public String getLocalOneUniqueid() - { + public String getLocalOneUniqueid() { return this.localOneUniqueid; } - public void setLocalOneUniqueid(String value) - { + public void setLocalOneUniqueid(String value) { this.localOneUniqueid = value; } - public String getLocalOneLinkedid() - { + public String getLocalOneLinkedid() { return this.localOneLinkedid; } - public void setLocalOneLinkedid(String value) - { + public void setLocalOneLinkedid(String value) { this.localOneLinkedid = value; } - public String getLocalTwoChannel() - { + public String getLocalTwoChannel() { return this.localTwoChannel; } - public void setLocalTwoChannel(String value) - { + public void setLocalTwoChannel(String value) { this.localTwoChannel = value; } - public String getLocalTwoChannelState() - { + public String getLocalTwoChannelState() { return this.localTwoChannelState; } - public void setLocalTwoChannelState(String value) - { + public void setLocalTwoChannelState(String value) { this.localTwoChannelState = value; } - public String getLocalTwoChannelStateDesc() - { + public String getLocalTwoChannelStateDesc() { return this.localTwoChannelStateDesc; } - public void setLocalTwoChannelStateDesc(String value) - { + public void setLocalTwoChannelStateDesc(String value) { this.localTwoChannelStateDesc = value; } - public String getLocalTwoCallerIDNum() - { + public String getLocalTwoCallerIDNum() { return this.localTwoCallerIDNum; } - public void setLocalTwoCallerIDNum(String value) - { + public void setLocalTwoCallerIDNum(String value) { this.localTwoCallerIDNum = value; } - public String getLocalTwoCallerIDName() - { + public String getLocalTwoCallerIDName() { return this.localTwoCallerIDName; } - public void setLocalTwoCallerIDName(String value) - { + public void setLocalTwoCallerIDName(String value) { this.localTwoCallerIDName = value; } - public String getLocalTwoConnectedLineNum() - { + public String getLocalTwoConnectedLineNum() { return this.localTwoConnectedLineNum; } - public void setLocalTwoConnectedLineNum(String value) - { + public void setLocalTwoConnectedLineNum(String value) { this.localTwoConnectedLineNum = value; } - public String getLocalTwoConnectedLineName() - { + public String getLocalTwoConnectedLineName() { return this.localTwoConnectedLineName; } - public void setLocalTwoConnectedLineName(String value) - { + public void setLocalTwoConnectedLineName(String value) { this.localTwoConnectedLineName = value; } - public String getLocalTwoAccountCode() - { + public String getLocalTwoAccountCode() { return this.localTwoAccountCode; } - public void setLocalTwoAccountCode(String value) - { + public void setLocalTwoAccountCode(String value) { this.localTwoAccountCode = value; } - public String getLocalTwoContext() - { + public String getLocalTwoContext() { return this.localTwoContext; } - public void setLocalTwoContext(String value) - { + public void setLocalTwoContext(String value) { this.localTwoContext = value; } - public String getLocalTwoExten() - { + public String getLocalTwoExten() { return this.localTwoExten; } - public void setLocalTwoExten(String value) - { + public void setLocalTwoExten(String value) { this.localTwoExten = value; } - public Integer getLocalTwoPriority() - { + public Integer getLocalTwoPriority() { return this.localTwoPriority; } - public void setLocalTwoPriority(Integer value) - { + public void setLocalTwoPriority(Integer value) { this.localTwoPriority = value; } - public String getLocalTwoUniqueid() - { + public String getLocalTwoUniqueid() { return this.localTwoUniqueid; } - public void setLocalTwoUniqueid(String value) - { + public void setLocalTwoUniqueid(String value) { this.localTwoUniqueid = value; } - public String getLocalTwoLinkedid() - { + public String getLocalTwoLinkedid() { return this.localTwoLinkedid; } - public void setLocalTwoLinkedid(String value) - { + public void setLocalTwoLinkedid(String value) { this.localTwoLinkedid = value; } - public String getSourceChannel() - { + public String getSourceChannel() { return this.sourceChannel; } - public void setSourceChannel(String value) - { + public void setSourceChannel(String value) { this.sourceChannel = value; } - public String getSourceChannelState() - { + public String getSourceChannelState() { return this.sourceChannelState; } - public void setSourceChannelState(String value) - { + public void setSourceChannelState(String value) { this.sourceChannelState = value; } - public String getSourceChannelStateDesc() - { + public String getSourceChannelStateDesc() { return this.sourceChannelStateDesc; } - public void setSourceChannelStateDesc(String value) - { + public void setSourceChannelStateDesc(String value) { this.sourceChannelStateDesc = value; } - public String getSourceCallerIDNum() - { + public String getSourceCallerIDNum() { return this.sourceCallerIDNum; } - public void setSourceCallerIDNum(String value) - { + public void setSourceCallerIDNum(String value) { this.sourceCallerIDNum = value; } - public String getSourceCallerIDName() - { + public String getSourceCallerIDName() { return this.sourceCallerIDName; } - public void setSourceCallerIDName(String value) - { + public void setSourceCallerIDName(String value) { this.sourceCallerIDName = value; } - public String getSourceConnectedLineNum() - { + public String getSourceConnectedLineNum() { return this.sourceConnectedLineNum; } - public void setSourceConnectedLineNum(String value) - { + public void setSourceConnectedLineNum(String value) { this.sourceConnectedLineNum = value; } - public String getSourceConnectedLineName() - { + public String getSourceConnectedLineName() { return this.sourceConnectedLineName; } - public void setSourceConnectedLineName(String value) - { + public void setSourceConnectedLineName(String value) { this.sourceConnectedLineName = value; } - public String getSourceAccountCode() - { + public String getSourceAccountCode() { return this.sourceAccountCode; } - public void setSourceAccountCode(String value) - { + public void setSourceAccountCode(String value) { this.sourceAccountCode = value; } - public String getSourceContext() - { + public String getSourceContext() { return this.sourceContext; } - public void setSourceContext(String value) - { + public void setSourceContext(String value) { this.sourceContext = value; } - public String getSourceExten() - { + public String getSourceExten() { return this.sourceExten; } - public void setSourceExten(String value) - { + public void setSourceExten(String value) { this.sourceExten = value; } - public Integer getSourcePriority() - { + public Integer getSourcePriority() { return this.sourcePriority; } - public void setSourcePriority(Integer value) - { + public void setSourcePriority(Integer value) { this.sourcePriority = value; } - public String getSourceUniqueid() - { + public String getSourceUniqueid() { return this.sourceUniqueid; } - public void setSourceUniqueid(String value) - { + public void setSourceUniqueid(String value) { this.sourceUniqueid = value; } - public String getSourceLinkedid() - { + public String getSourceLinkedid() { return this.sourceLinkedid; } - public void setSourceLinkedid(String value) - { + public void setSourceLinkedid(String value) { this.sourceLinkedid = value; } - public String getLocalTwoLanguage() - { + public String getLocalTwoLanguage() { return localTwoLanguage; } - public void setLocalTwoLanguage(String localTwoLanguage) - { + public void setLocalTwoLanguage(String localTwoLanguage) { this.localTwoLanguage = localTwoLanguage; } - public String getLocalOneLanguage() - { + public String getLocalOneLanguage() { return localOneLanguage; } - public void setLocalOneLanguage(String localOneLanguage) - { + public void setLocalOneLanguage(String localOneLanguage) { this.localOneLanguage = localOneLanguage; } - public String getSourceLanguage() - { + public String getSourceLanguage() { return sourceLanguage; } - public void setSourceLanguage(String 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 index 1407bec13..4d4f20d88 100644 --- a/src/main/java/org/asteriskjava/manager/event/LocalOptimizationEndEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/LocalOptimizationEndEvent.java @@ -20,8 +20,7 @@ * 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 -{ +public class LocalOptimizationEndEvent extends ManagerEvent { private static final long serialVersionUID = 0L; private Integer id; @@ -58,308 +57,247 @@ public class LocalOptimizationEndEvent extends ManagerEvent private String localTwoLanguage; private String localOneLanguage; - public LocalOptimizationEndEvent(Object source) - { + public LocalOptimizationEndEvent(Object source) { super(source); } - public Integer getId() - { + public Integer getId() { return this.id; } - public void setId(Integer value) - { + public void setId(Integer value) { this.id = value; } - public Boolean getSuccess() - { + public Boolean getSuccess() { return this.success; } - public void setSuccess(Boolean success) - { + public void setSuccess(Boolean success) { this.success = success; } - public String getLocalOneChannel() - { + public String getLocalOneChannel() { return this.localOneChannel; } - public void setLocalOneChannel(String value) - { + public void setLocalOneChannel(String value) { this.localOneChannel = value; } - public String getLocalOneChannelState() - { + public String getLocalOneChannelState() { return this.localOneChannelState; } - public void setLocalOneChannelState(String value) - { + public void setLocalOneChannelState(String value) { this.localOneChannelState = value; } - public String getLocalOneChannelStateDesc() - { + public String getLocalOneChannelStateDesc() { return this.localOneChannelStateDesc; } - public void setLocalOneChannelStateDesc(String value) - { + public void setLocalOneChannelStateDesc(String value) { this.localOneChannelStateDesc = value; } - public String getLocalOneCallerIDNum() - { + public String getLocalOneCallerIDNum() { return this.localOneCallerIDNum; } - public void setLocalOneCallerIDNum(String value) - { + public void setLocalOneCallerIDNum(String value) { this.localOneCallerIDNum = value; } - public String getLocalOneCallerIDName() - { + public String getLocalOneCallerIDName() { return this.localOneCallerIDName; } - public void setLocalOneCallerIDName(String value) - { + public void setLocalOneCallerIDName(String value) { this.localOneCallerIDName = value; } - public String getLocalOneConnectedLineNum() - { + public String getLocalOneConnectedLineNum() { return this.localOneConnectedLineNum; } - public void setLocalOneConnectedLineNum(String value) - { + public void setLocalOneConnectedLineNum(String value) { this.localOneConnectedLineNum = value; } - public String getLocalOneConnectedLineName() - { + public String getLocalOneConnectedLineName() { return this.localOneConnectedLineName; } - public void setLocalOneConnectedLineName(String value) - { + public void setLocalOneConnectedLineName(String value) { this.localOneConnectedLineName = value; } - public String getLocalOneAccountCode() - { + public String getLocalOneAccountCode() { return this.localOneAccountCode; } - public void setLocalOneAccountCode(String value) - { + public void setLocalOneAccountCode(String value) { this.localOneAccountCode = value; } - public String getLocalOneContext() - { + public String getLocalOneContext() { return this.localOneContext; } - public void setLocalOneContext(String value) - { + public void setLocalOneContext(String value) { this.localOneContext = value; } - public String getLocalOneExten() - { + public String getLocalOneExten() { return this.localOneExten; } - public void setLocalOneExten(String value) - { + public void setLocalOneExten(String value) { this.localOneExten = value; } - public Integer getLocalOnePriority() - { + public Integer getLocalOnePriority() { return this.localOnePriority; } - public void setLocalOnePriority(Integer value) - { + public void setLocalOnePriority(Integer value) { this.localOnePriority = value; } - public String getLocalOneUniqueid() - { + public String getLocalOneUniqueid() { return this.localOneUniqueid; } - public void setLocalOneUniqueid(String value) - { + public void setLocalOneUniqueid(String value) { this.localOneUniqueid = value; } - public String getLocalOneLinkedid() - { + public String getLocalOneLinkedid() { return this.localOneLinkedid; } - public void setLocalOneLinkedid(String value) - { + public void setLocalOneLinkedid(String value) { this.localOneLinkedid = value; } - public String getLocalTwoChannel() - { + public String getLocalTwoChannel() { return this.localTwoChannel; } - public void setLocalTwoChannel(String value) - { + public void setLocalTwoChannel(String value) { this.localTwoChannel = value; } - public String getLocalTwoChannelState() - { + public String getLocalTwoChannelState() { return this.localTwoChannelState; } - public void setLocalTwoChannelState(String value) - { + public void setLocalTwoChannelState(String value) { this.localTwoChannelState = value; } - public String getLocalTwoChannelStateDesc() - { + public String getLocalTwoChannelStateDesc() { return this.localTwoChannelStateDesc; } - public void setLocalTwoChannelStateDesc(String value) - { + public void setLocalTwoChannelStateDesc(String value) { this.localTwoChannelStateDesc = value; } - public String getLocalTwoCallerIDNum() - { + public String getLocalTwoCallerIDNum() { return this.localTwoCallerIDNum; } - public void setLocalTwoCallerIDNum(String value) - { + public void setLocalTwoCallerIDNum(String value) { this.localTwoCallerIDNum = value; } - public String getLocalTwoCallerIDName() - { + public String getLocalTwoCallerIDName() { return this.localTwoCallerIDName; } - public void setLocalTwoCallerIDName(String value) - { + public void setLocalTwoCallerIDName(String value) { this.localTwoCallerIDName = value; } - public String getLocalTwoConnectedLineNum() - { + public String getLocalTwoConnectedLineNum() { return this.localTwoConnectedLineNum; } - public void setLocalTwoConnectedLineNum(String value) - { + public void setLocalTwoConnectedLineNum(String value) { this.localTwoConnectedLineNum = value; } - public String getLocalTwoConnectedLineName() - { + public String getLocalTwoConnectedLineName() { return this.localTwoConnectedLineName; } - public void setLocalTwoConnectedLineName(String value) - { + public void setLocalTwoConnectedLineName(String value) { this.localTwoConnectedLineName = value; } - public String getLocalTwoAccountCode() - { + public String getLocalTwoAccountCode() { return this.localTwoAccountCode; } - public void setLocalTwoAccountCode(String value) - { + public void setLocalTwoAccountCode(String value) { this.localTwoAccountCode = value; } - public String getLocalTwoContext() - { + public String getLocalTwoContext() { return this.localTwoContext; } - public void setLocalTwoContext(String value) - { + public void setLocalTwoContext(String value) { this.localTwoContext = value; } - public String getLocalTwoExten() - { + public String getLocalTwoExten() { return this.localTwoExten; } - public void setLocalTwoExten(String value) - { + public void setLocalTwoExten(String value) { this.localTwoExten = value; } - public Integer getLocalTwoPriority() - { + public Integer getLocalTwoPriority() { return this.localTwoPriority; } - public void setLocalTwoPriority(Integer value) - { + public void setLocalTwoPriority(Integer value) { this.localTwoPriority = value; } - public String getLocalTwoUniqueid() - { + public String getLocalTwoUniqueid() { return this.localTwoUniqueid; } - public void setLocalTwoUniqueid(String value) - { + public void setLocalTwoUniqueid(String value) { this.localTwoUniqueid = value; } - public String getLocalTwoLinkedid() - { + public String getLocalTwoLinkedid() { return this.localTwoLinkedid; } - public void setLocalTwoLinkedid(String value) - { + public void setLocalTwoLinkedid(String value) { this.localTwoLinkedid = value; } - public String getLocalTwoLanguage() - { + public String getLocalTwoLanguage() { return localTwoLanguage; } - public void setLocalTwoLanguage(String localTwoLanguage) - { + public void setLocalTwoLanguage(String localTwoLanguage) { this.localTwoLanguage = localTwoLanguage; } - public String getLocalOneLanguage() - { + public String getLocalOneLanguage() { return localOneLanguage; } - public void setLocalOneLanguage(String 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 58e7f654b..1aaa100a1 100644 --- a/src/main/java/org/asteriskjava/manager/event/ManagerEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ManagerEvent.java @@ -16,16 +16,12 @@ */ package org.asteriskjava.manager.event; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Date; -import java.util.EventObject; -import java.util.List; -import java.util.Map; - import org.asteriskjava.util.AstState; import org.asteriskjava.util.ReflectionUtil; +import java.lang.reflect.Method; +import java.util.*; + /** * Abstract base class for all Events that can be received from the Asterisk * server.
    @@ -37,12 +33,11 @@ * @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; @@ -51,105 +46,107 @@ public abstract class ManagerEvent extends EventObject 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. + * has been set. * @since 0.2 */ - public String getCallerIdName() - { + public String getCallerIdName() { return callerIdName; } - public void setCallerIdName(String callerIdName) - { + public void setCallerIdName(String callerIdName) { this.callerIdName = callerIdName; } - public String getConnectedLineNum() - { + public String getConnectedLineNum() { return connectedLineNum; } - public void setConnectedLineNum(String connectedLineNum) - { + public void setConnectedLineNum(String connectedLineNum) { this.connectedLineNum = connectedLineNum; } - public String getConnectedLineName() - { + public String getConnectedLineName() { return connectedLineName; } - public void setConnectedLineName(String connectedLineName) - { + public void setConnectedLineName(String connectedLineName) { this.connectedLineName = connectedLineName; } - public Integer getPriority() - { + public Integer getPriority() { return priority; } - public void setPriority(Integer priority) - { + public void setPriority(Integer priority) { this.priority = priority; } - public Integer getChannelState() - { + public Integer getChannelState() { return channelState == null ? AstState.str2state(channelStateDesc) : channelState; } - public void setChannelState(Integer channelState) - { + public void setChannelState(Integer channelState) { this.channelState = channelState; } - public String getChannelStateDesc() - { + public String getChannelStateDesc() { return channelStateDesc; } - public void setChannelStateDesc(String channelStateDesc) - { + public void setChannelStateDesc(String channelStateDesc) { this.channelStateDesc = channelStateDesc; } - public String getExten() - { + public String getExten() { return exten; } - public void setExten(String exten) - { + public void setExten(String exten) { this.exten = exten; } - public String getCallerIdNum() - { + public String getCallerIdNum() { return callerIdNum; } - public void setCallerIdNum(String callerIdNum) - { + public void setCallerIdNum(String callerIdNum) { this.callerIdNum = callerIdNum; } - public String getContext() - { + public String getContext() { return context; } - public void setContext(String 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; /** @@ -178,8 +175,7 @@ public void setContext(String context) private String func; private Integer sequenceNumber; - public ManagerEvent(Object source) - { + public ManagerEvent(Object source) { super(source); } @@ -191,16 +187,14 @@ public ManagerEvent(Object source) * (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; } @@ -212,8 +206,7 @@ public void setDateReceived(Date dateReceived) * * @since 0.2 */ - public String getPrivilege() - { + public String getPrivilege() { return privilege; } @@ -222,8 +215,7 @@ public String getPrivilege() * * @since 0.2 */ - public void setPrivilege(String privilege) - { + public void setPrivilege(String privilege) { this.privilege = privilege; } @@ -239,8 +231,7 @@ public void setPrivilege(String privilege) * @return the timestamp for this event. * @since 0.3 */ - public final Double getTimestamp() - { + public final Double getTimestamp() { return timestamp; } @@ -250,8 +241,7 @@ 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; } @@ -261,12 +251,11 @@ public final void setTimestamp(Double timestamp) * 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. + * 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; } @@ -275,21 +264,18 @@ public final String getServer() * received. * * @param server the name of the Asterisk server from which this event has - * been received. + * been received. * @since 1.0.0 */ - public final void setServer(String server) - { + public final void setServer(String server) { this.server = server; } - public String getSystemName() - { + public String getSystemName() { return systemName; } - public void setSystemName(String systemName) - { + public void setSystemName(String systemName) { this.systemName = systemName; } @@ -304,18 +290,16 @@ public void setSystemName(String systemName) * 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. + * 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; } @@ -330,18 +314,16 @@ public void setFile(String file) * 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. + * 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; } @@ -356,18 +338,16 @@ public void setLine(Integer line) * 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. + * 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; } @@ -382,24 +362,21 @@ public void setFunc(String func) * This feature is availble in Asterisk since 1.6.0. * * @return the sequence number of this event or null if - * debgging is turned off. + * 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() - { + public String toString() { final List ignoredProperties = Arrays.asList("file", "func", "line", "sequenceNumber", "datereceived", "privilege", "source", "class"); final StringBuilder sb = new StringBuilder(getClass().getName() + "["); @@ -411,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 } @@ -435,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 5b7f16815..23cd9d626 100644 --- a/src/main/java/org/asteriskjava/manager/event/MeetMeJoinEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MeetMeJoinEvent.java @@ -27,18 +27,31 @@ * @author srt * @version $Id$ */ -public class MeetMeJoinEvent extends AbstractMeetMeEvent -{ +public class MeetMeJoinEvent extends AbstractMeetMeEvent { /** * Serializable version identifier. */ private static final long serialVersionUID = 0L; + private Integer duration; + /** * @param source */ - public MeetMeJoinEvent(Object source) - { + public MeetMeJoinEvent(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; + } } diff --git a/src/main/java/org/asteriskjava/manager/event/MeetMeLeaveEvent.java b/src/main/java/org/asteriskjava/manager/event/MeetMeLeaveEvent.java index 517a21cb1..aa6aa748d 100644 --- a/src/main/java/org/asteriskjava/manager/event/MeetMeLeaveEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MeetMeLeaveEvent.java @@ -23,12 +23,11 @@ * 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. */ @@ -39,8 +38,7 @@ public class MeetMeLeaveEvent extends AbstractMeetMeEvent /** * @param source */ - public MeetMeLeaveEvent(Object source) - { + public MeetMeLeaveEvent(Object source) { super(source); } @@ -48,21 +46,19 @@ public MeetMeLeaveEvent(Object source) * 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 a4ac71629..ffeb20d57 100644 --- a/src/main/java/org/asteriskjava/manager/event/MusicOnHoldEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MusicOnHoldEvent.java @@ -27,8 +27,7 @@ * @author srt * @since 1.0.0 */ -public class MusicOnHoldEvent extends ManagerEvent -{ +public class MusicOnHoldEvent extends ManagerEvent { private static final long serialVersionUID = 1L; public static final String STATE_START = "Start"; @@ -42,8 +41,7 @@ public class MusicOnHoldEvent extends ManagerEvent private String linkedId; private String language; - public MusicOnHoldEvent(Object source) - { + public MusicOnHoldEvent(Object source) { super(source); } @@ -52,8 +50,7 @@ public MusicOnHoldEvent(Object source) * * @return channel the name of the channel. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -62,18 +59,15 @@ 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() - { + public String getClassName() { return this.className; } - public void setClazz(String className) - { + public void setClazz(String className) { this.className = className; } @@ -82,8 +76,7 @@ public void setClazz(String className) * * @return the unique id of the channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -92,8 +85,7 @@ public String getUniqueId() * * @param uniqueId the unique id of the channel. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -102,19 +94,17 @@ public void setUniqueId(String uniqueId) * 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. + * 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; } @@ -122,10 +112,9 @@ public void setState(String state) * Returns whether this is a start event. * * @return true if this a start event, false - * otherwise. + * otherwise. */ - public boolean isStart() - { + public boolean isStart() { return STATE_START.equals(state); } @@ -133,41 +122,34 @@ public boolean isStart() * Returns whether this is a stop event. * * @return true if this an stop event, false - * otherwise. + * otherwise. */ - public boolean isStop() - { + public boolean isStop() { return STATE_STOP.equals(state); } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - - public String getLinkedId() - { + + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String 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 index 68e0e002a..82d88f2b2 100644 --- a/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStartEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStartEvent.java @@ -3,16 +3,14 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public class MusicOnHoldStartEvent extends MusicOnHoldEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; +public class MusicOnHoldStartEvent extends MusicOnHoldEvent { + /** + * + */ + private static final long serialVersionUID = 1L; - public MusicOnHoldStartEvent(Object source) - { - super(source); - setState(STATE_START); - } + 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 index f25f9d4a5..fd49673ba 100644 --- a/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStopEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/MusicOnHoldStopEvent.java @@ -3,16 +3,14 @@ /** * Created by Alexander Polakov on 1/26/15. */ -public class MusicOnHoldStopEvent extends MusicOnHoldEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; +public class MusicOnHoldStopEvent extends MusicOnHoldEvent { + /** + * + */ + private static final long serialVersionUID = 1L; - public MusicOnHoldStopEvent(Object source) - { - super(source); - setState(STATE_STOP); - } + 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 cb6e80aee..58d6fb41f 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewAccountCodeEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewAccountCodeEvent.java @@ -26,8 +26,7 @@ * @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; @@ -39,8 +38,7 @@ public class NewAccountCodeEvent extends ManagerEvent /** * @param source */ - public NewAccountCodeEvent(Object source) - { + public NewAccountCodeEvent(Object source) { super(source); } @@ -49,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; } @@ -64,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; } @@ -79,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; } @@ -94,35 +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; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - - -} \ No newline at end of file + + +} diff --git a/src/main/java/org/asteriskjava/manager/event/NewCallerIdEvent.java b/src/main/java/org/asteriskjava/manager/event/NewCallerIdEvent.java index a840dce92..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. */ @@ -39,86 +38,72 @@ public class NewCallerIdEvent extends AbstractChannelEvent private String language; private String linkedId; - public NewCallerIdEvent(Object source) - { + public NewCallerIdEvent(Object source) { super(source); } - public String getLanguage() - { - return language; + public String getLanguage() { + return language; } - - public void setLanguage(String language) - { - this.language = 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() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String 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 e731dbdaf..b57e74e17 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewChannelEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewChannelEvent.java @@ -24,8 +24,7 @@ * @author srt * @version $Id$ */ -public class NewChannelEvent extends AbstractChannelStateEvent -{ +public class NewChannelEvent extends AbstractChannelStateEvent { /** * Serializable version identifier. */ @@ -33,30 +32,25 @@ public class NewChannelEvent extends AbstractChannelStateEvent private String language; private String linkedid; - public NewChannelEvent(Object source) - { + public NewChannelEvent(Object source) { super(source); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getLinkedid() - { + public String getLinkedid() { return linkedid; } - public void setLinkedid(String linkedid) - { + public void setLinkedid(String linkedid) { this.linkedid = linkedid; } - - + + } diff --git a/src/main/java/org/asteriskjava/manager/event/NewConnectedLineEvent.java b/src/main/java/org/asteriskjava/manager/event/NewConnectedLineEvent.java index 4274e2d33..c145f5c76 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewConnectedLineEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewConnectedLineEvent.java @@ -3,10 +3,9 @@ /** * Created by plhk on 1/15/15. */ -public class NewConnectedLineEvent extends ManagerEvent -{ +public class NewConnectedLineEvent extends ManagerEvent { /** - * + * */ private static final long serialVersionUID = 1L; private String channel; @@ -15,60 +14,49 @@ public class NewConnectedLineEvent extends ManagerEvent private String accountCode; private String linkedId; - public NewConnectedLineEvent(Object source) - { + public NewConnectedLineEvent(Object source) { super(source); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String 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 9997b9152..ddf71a982 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewExtenEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewExtenEvent.java @@ -20,12 +20,11 @@ * 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 */ @@ -43,50 +42,43 @@ public class NewExtenEvent extends ManagerEvent /** * @param source */ - public NewExtenEvent(Object source) - { + public NewExtenEvent(Object source) { super(source); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String 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; } @@ -94,69 +86,59 @@ public void setApplication(String application) * 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 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; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String 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 275146b31..b6f71f738 100644 --- a/src/main/java/org/asteriskjava/manager/event/NewStateEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/NewStateEvent.java @@ -19,12 +19,11 @@ /** * 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. */ @@ -32,28 +31,23 @@ public class NewStateEvent extends AbstractChannelStateEvent private String language; private String linkedId; - public NewStateEvent(Object source) - { + public NewStateEvent(Object source) { super(source); } - - public String getLanguage() - { - return language; + + public String getLanguage() { + return language; } - - public void setLanguage(String language) - { - this.language = language; + + public void setLanguage(String language) { + this.language = language; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String 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 33ce8cb00..93bf466ee 100644 --- a/src/main/java/org/asteriskjava/manager/event/OriginateResponseEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/OriginateResponseEvent.java @@ -18,13 +18,12 @@ /** * 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. */ @@ -39,104 +38,88 @@ public class OriginateResponseEvent extends ResponseEvent /** * @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; } - 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; } // for backward compatibility only - public void setCallerId(String callerId) - { - if (getCallerIdNum() == null) - { + public void setCallerId(String callerId) { + if (getCallerIdNum() == null) { setCallerIdNum(callerId); } } - public String getData() - { + public String getData() { return data; } - public void setData(String data) - { + public void setData(String data) { this.data = data; } - public String getApplication() - { + public String getApplication() { return application; } - public void setApplication(String application) - { + 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 b8c681d08..aef32c1d1 100644 --- a/src/main/java/org/asteriskjava/manager/event/ParkedCallEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ParkedCallEvent.java @@ -21,13 +21,12 @@ * 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 */ @@ -39,8 +38,7 @@ public class ParkedCallEvent extends AbstractParkedCallEvent /** * @param source */ - public ParkedCallEvent(Object source) - { + public ParkedCallEvent(Object source) { super(source); } @@ -50,16 +48,14 @@ public ParkedCallEvent(Object source) * This corresponds to the parkingtime option in * features.conf. */ - public Integer getTimeout() - { + public Integer getTimeout() { return timeout; } /** * Sets the number of seconds this call will be parked. */ - public void setTimeout(Integer timeout) - { + public void setTimeout(Integer timeout) { this.timeout = timeout; } @@ -67,24 +63,21 @@ public void setTimeout(Integer timeout) * Sets the unique id of the parked channel as a workaround for a typo in * asterisk manager event. */ - public void setUnqiueId(String unqiueId) - { + public void setUnqiueId(String unqiueId) { setUniqueId(unqiueId); } /** * @param parkeelinkedid the parkeelinkedid to set */ - public void setParkeelinkedid(String parkeelinkedid) - { + public void setParkeelinkedid(String parkeelinkedid) { this.parkeelinkedid = parkeelinkedid; } /** * @return the parkeelinkedid */ - public String getParkeelinkedid() - { + 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 1c4a456e5..1d0e998ef 100644 --- a/src/main/java/org/asteriskjava/manager/event/ParkedCallGiveUpEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ParkedCallGiveUpEvent.java @@ -23,13 +23,12 @@ * It is implemented in res/res_features.c *

    * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class ParkedCallGiveUpEvent extends AbstractUnParkedEvent -{ +public class ParkedCallGiveUpEvent extends AbstractUnParkedEvent { /** * Serializable version identifier */ @@ -38,8 +37,7 @@ public class ParkedCallGiveUpEvent extends AbstractUnParkedEvent /** * @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 c258ba4af..644b6dd0f 100644 --- a/src/main/java/org/asteriskjava/manager/event/ParkedCallTimeOutEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ParkedCallTimeOutEvent.java @@ -23,13 +23,12 @@ * It is implemented in res/res_features.c *

    * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class ParkedCallTimeOutEvent extends AbstractUnParkedEvent -{ +public class ParkedCallTimeOutEvent extends AbstractUnParkedEvent { /** * Serializable version identifier */ @@ -38,8 +37,7 @@ public class ParkedCallTimeOutEvent extends AbstractUnParkedEvent /** * @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 263df0c59..a00d9e10f 100644 --- a/src/main/java/org/asteriskjava/manager/event/ParkedCallsCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ParkedCallsCompleteEvent.java @@ -19,14 +19,13 @@ /** * 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 + * * @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 */ @@ -35,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 index efa0dbe83..b073f8a03 100644 --- a/src/main/java/org/asteriskjava/manager/event/PausedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/PausedEvent.java @@ -2,34 +2,34 @@ 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; - } - - + 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 0e8b9b64e..45244f669 100644 --- a/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/PeerEntryEvent.java @@ -30,8 +30,7 @@ * @version $Id$ * @since 0.2 */ -public class PeerEntryEvent extends ResponseEvent -{ +public class PeerEntryEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -67,8 +66,7 @@ public class PeerEntryEvent extends ResponseEvent * * @param source */ - public PeerEntryEvent(Object source) - { + public PeerEntryEvent(Object source) { super(source); } @@ -79,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; } @@ -103,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; } @@ -118,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; } @@ -133,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; } @@ -143,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; } @@ -155,13 +143,11 @@ public void setIpAddress(String ipAddress) * @deprecated since 1.0.0, use {@link #getPort()} instead. */ @Deprecated - public Integer getIpPort() - { + public Integer getIpPort() { return port; } - public void setIpPort(Integer ipPort) - { + public void setIpPort(Integer ipPort) { this.port = ipPort; } @@ -171,33 +157,27 @@ 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; } @@ -206,16 +186,14 @@ public void setNatSupport(Boolean natSupport) * 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. + * force_rport, false otherwise or + * null if not supported by Asterisk. */ - public Boolean getForceRport() - { + public Boolean getForceRport() { return forceRport; } - public void setForceRport(Boolean forceRport) - { + public void setForceRport(Boolean forceRport) { this.forceRport = forceRport; } @@ -224,8 +202,7 @@ public void setForceRport(Boolean forceRport) * * @since 0.3 */ - public Boolean getVideoSupport() - { + public Boolean getVideoSupport() { return videoSupport; } @@ -234,8 +211,7 @@ public Boolean getVideoSupport() * * @since 0.3 */ - public void setVideoSupport(Boolean videoSupport) - { + public void setVideoSupport(Boolean videoSupport) { this.videoSupport = videoSupport; } @@ -245,27 +221,23 @@ public void setVideoSupport(Boolean videoSupport) * 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). + * 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; } @@ -288,8 +260,7 @@ public void setAcl(Boolean acl) * * @return the status of this peer. */ - public String getStatus() - { + public String getStatus() { return status; } @@ -298,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; } @@ -308,8 +278,7 @@ public void setStatus(String status) * * @since 0.3 */ - public String getRealtimeDevice() - { + public String getRealtimeDevice() { return realtimeDevice; } @@ -318,8 +287,7 @@ public String getRealtimeDevice() * * @since 0.3 */ - public void setRealtimeDevice(String realtimeDevice) - { + public void setRealtimeDevice(String realtimeDevice) { this.realtimeDevice = realtimeDevice; } @@ -329,106 +297,92 @@ public void setRealtimeDevice(String realtimeDevice) * Available since Asterisk 1.6. * * @return true if trunking is used, false if not - * or null if not set. + * 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() - { + public String getAutoComedia() { return autoComedia; } /** * @param autoComedia the autoComedia to set */ - public void setAutoComedia(String autoComedia) - { + public void setAutoComedia(String autoComedia) { this.autoComedia = autoComedia; } /** * @return the autoForcerport */ - public String getAutoForcerport() - { + public String getAutoForcerport() { return autoForcerport; } /** * @param autoForcerport the autoForcerport to set */ - public void setAutoForcerport(String autoForcerport) - { + public void setAutoForcerport(String autoForcerport) { this.autoForcerport = autoForcerport; } /** * @return the comedia */ - public String getComedia() - { + public String getComedia() { return comedia; } /** * @param comedia the comedia to set */ - public void setComedia(String comedia) - { + public void setComedia(String comedia) { this.comedia = comedia; } /** * @return the description */ - public String getDescription() - { + public String getDescription() { return description; } /** * @param the description to set */ - public void setDescription(String description) - { + public void setDescription(String description) { this.description = description; } /** * @return the accountcode */ - public String getAccountcode() - { + public String getAccountcode() { return accountcode; } /** * @param the accountcode to set */ - public void setAccountcode(String accountcode) - { + 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 200de7a54..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; } @@ -88,16 +84,14 @@ public void setChannelType(String channelType) * * @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 index 2e1692d9c..5a4ed9f11 100644 --- a/src/main/java/org/asteriskjava/manager/event/PeersEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/PeersEvent.java @@ -28,8 +28,7 @@ * @version $Id$ * @since 0.2 */ -public class PeersEvent extends ResponseEvent -{ +public class PeersEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -45,18 +44,15 @@ public class PeersEvent extends ResponseEvent * * @param source */ - public PeersEvent( Object source ) - { + public PeersEvent(Object source) { super(source); } - public List getChildEvents() - { + public List getChildEvents() { return childEvents; } - public void setChildEvents( List 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 index b7c829cda..13e47466e 100644 --- a/src/main/java/org/asteriskjava/manager/event/PickupEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/PickupEvent.java @@ -1,38 +1,184 @@ package org.asteriskjava.manager.event; -public class PickupEvent extends ManagerEvent -{ +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; - - public PickupEvent(Object source) - { - super(source); - } - - /** - * - */ - private static final long serialVersionUID = 1L; - - public String getChannel() - { - return channel; - } - - public void setChannel(String channel) - { - this.channel = channel; - } - - public String getTargetchannel() - { - return targetchannel; - } - - public void setTargetchannel(String targetchannel) - { - this.targetchannel = 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 58d189a73..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 */ @@ -38,93 +37,80 @@ public class QueueCallerAbandonEvent extends QueueEvent 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() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getAccountcode() - { - return accountcode; - } + public String getAccountcode() { + return accountcode; + } - public void setAccountcode(String accountcode) - { - this.accountcode = 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 index 204390119..121df3ff5 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueCallerJoinEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueCallerJoinEvent.java @@ -26,8 +26,7 @@ * * @author Leonardo de Souza */ -public class QueueCallerJoinEvent extends QueueEvent -{ +public class QueueCallerJoinEvent extends QueueEvent { /** * Serializable version identifier @@ -42,57 +41,48 @@ public class QueueCallerJoinEvent extends QueueEvent /** * @param source */ - public QueueCallerJoinEvent(Object source) - { + public QueueCallerJoinEvent(Object source) { super(source); } /** * @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() - { + + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getAccountcode() - { - return accountcode; - } + public String getAccountcode() { + return accountcode; + } + + public void setAccountcode(String accountcode) { + this.accountcode = 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 index 77538b0d5..56e8862cf 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueCallerLeaveEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueCallerLeaveEvent.java @@ -26,8 +26,7 @@ * * @author Leonardo de Souza */ -public class QueueCallerLeaveEvent extends QueueEvent -{ +public class QueueCallerLeaveEvent extends QueueEvent { /** * Serializable version identifier @@ -37,61 +36,52 @@ public class QueueCallerLeaveEvent extends QueueEvent private Integer position; private String language; private String linkedId; - + private String accountcode; /** * @param source */ - public QueueCallerLeaveEvent(Object source) - { + public QueueCallerLeaveEvent(Object source) { super(source); } /** * @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() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getAccountcode() - { - return accountcode; - } + public String getAccountcode() { + return accountcode; + } - public void setAccountcode(String accountcode) - { - this.accountcode = 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 840e105ed..b48c923e4 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueEntryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueEntryEvent.java @@ -26,8 +26,7 @@ * @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 */ @@ -42,48 +41,42 @@ public class QueueEntryEvent extends ResponseEvent /** * @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; } @@ -95,13 +88,11 @@ public String getChannel() * @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,8 +101,7 @@ 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; } @@ -120,8 +110,7 @@ public void setChannel(String channel) * * @return the the Caller*ID number of this entry. */ - public String getCallerId() - { + public String getCallerId() { return callerId; } @@ -130,24 +119,21 @@ public String getCallerId() * * @param callerId the the Caller*ID number of this entry. */ - public void setCallerId(String callerId) - { + 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 090f6a5c4..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. */ @@ -38,99 +37,93 @@ public class QueueMemberAddedEvent extends AbstractQueueMemberEvent private Long lastCall; private Integer status; private Boolean paused; - + private String stateinterface; private Boolean ringinuse; + private Integer logintime; + private Integer wrapuptime; + private Integer lastpause; - public QueueMemberAddedEvent(Object source) - { + 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; } @@ -151,63 +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 String getStateinterface() { + return stateinterface; + } - public void setStateinterface(String stateinterface) - { - this.stateinterface = stateinterface; + public void setStateinterface(String stateinterface) { + this.stateinterface = stateinterface; } - public Boolean getRinginuse() - { - return ringinuse; - } + public Boolean getRinginuse() { + return ringinuse; + } - public void setRinginuse(Boolean ringinuse) - { - this.ringinuse = 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 236abab97..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; /** @@ -63,33 +62,32 @@ public class QueueMemberEvent extends ResponseEvent 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; } @@ -100,18 +98,16 @@ public void setQueue(String queue) * * @return the name of the member's interface. */ - final public String getInterface() - { + 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) - { + final public void setInterface(String _interface) { this._interface = _interface; } @@ -120,26 +116,23 @@ final public void setInterface(String _interface) *

    * E.g. the channel name or agent group. * - * @deprecated since Asterisk 12 * @return the name of the member's interface. + * @deprecated since Asterisk 12 */ @Deprecated - final public String getLocation() - { + final public String getLocation() { return _interface; } /** * Sets the name of the member's interface. * - * @deprecated since Asterisk 12 * @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 + final public void setLocation(String _interface) { + if ((_interface != null) && (!"null".equals(_interface))) { // Location is not in use since asterisk 12 this._interface = _interface; } } @@ -148,133 +141,122 @@ final public void setLocation(String _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() - { + 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) - { + public void setLastPause(Long lastPause) { this.lastPause = lastPause; } @@ -304,24 +286,22 @@ public void setLastPause(Long lastPause) *

    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; } @@ -329,24 +309,22 @@ 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; } @@ -354,16 +332,14 @@ public void setPaused(Boolean paused) * Returns the name of the member. * * @return the name of the member supplied for logging when the member is - * added + * 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; } @@ -371,55 +347,62 @@ public void setName(String name) * Returns the name of the member. * * @return the name of the member supplied for logging when the member is - * added + * added * @deprecated since 1.0.0. Use {@link #getName()} instead. */ @Deprecated - public String getMemberName() - { + 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() - { + public String getStateinterface() { return stateinterface; } - public void setStateinterface(String stateinterface) - { + public void setStateinterface(String stateinterface) { this.stateinterface = stateinterface; } /** * @return 1 if is incall 0 if not */ - public Integer getIncall() - { + public Integer getIncall() { return incall; } - public void setIncall(Integer incall) - { + public void setIncall(Integer incall) { this.incall = incall; } - public String getPausedreason() - { + public String getPausedreason() { return pausedreason; } - public void setPausedreason(String 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 index 8070d8286..80eb1be30 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueMemberPauseEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberPauseEvent.java @@ -1,12 +1,20 @@ package org.asteriskjava.manager.event; -public class QueueMemberPauseEvent extends QueueMemberPausedEvent -{ - private static final long serialVersionUID = 58564514209197321L; +/** + * 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; @@ -14,9 +22,10 @@ public class QueueMemberPauseEvent extends QueueMemberPausedEvent String stateInterface; Integer incall; String pausedreason; + Integer logintime; + Integer wrapuptime; - public QueueMemberPauseEvent(Object source) - { + public QueueMemberPauseEvent(Object source) { super(source); // TODO Auto-generated constructor stub } @@ -24,96 +33,98 @@ public QueueMemberPauseEvent(Object source) /** * @return the membership */ - public String getMembership() - { + public String getMembership() { return membership; } /** * @param membership the membership to set */ - public void setMembership(String membership) - { + public void setMembership(String membership) { this.membership = membership; } /** * @return the lastcall */ - public Long getLastcall() - { + public Long getLastcall() { return lastcall; } /** * @param lastcall the lastcall to set */ - public void setLastcall(Long lastcall) - { + 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() - { + public Integer getCallsTaken() { return callsTaken; } /** * @param callsTaken the callsTaken to set */ - public void setCallsTaken(Integer callsTaken) - { + public void setCallsTaken(Integer callsTaken) { this.callsTaken = callsTaken; } /** * @return the penalty */ - public Integer getPenalty() - { + public Integer getPenalty() { return penalty; } /** * @param penalty the penalty to set */ - public void setPenalty(Integer penalty) - { + public void setPenalty(Integer penalty) { this.penalty = penalty; } /** * @return the status */ - public Integer getStatus() - { + public Integer getStatus() { return status; } /** * @param status the status to set */ - public void setStatus(Integer status) - { + public void setStatus(Integer status) { this.status = status; } /** * @return the ringinuse */ - public Boolean getRinginuse() - { + public Boolean getRinginuse() { return ringinuse; } /** * @param ringinuse the ringinuse to set */ - public void setRinginuse(Boolean ringinuse) - { + public void setRinginuse(Boolean ringinuse) { this.ringinuse = ringinuse; } @@ -121,44 +132,72 @@ public void setRinginuse(Boolean ringinuse) /** * @return the stateInterface */ - public String getStateInterface() - { + public String getStateInterface() { return stateInterface; } /** * @param stateInterface the stateInterface to set */ - public void setStateInterface(String stateInterface) - { + public void setStateInterface(String stateInterface) { this.stateInterface = stateInterface; } /** * @return get Incall */ - public Integer getIncall() - { + public Integer getIncall() { return incall; } /** * @param setIncall the incall to set */ - public void setIncall(Integer incall) - { + public void setIncall(Integer incall) { this.incall = incall; } - public String getPausedreason() - { + public String getPausedreason() { return pausedreason; } - public void setPausedreason(String 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 3b61e9907..9d9da69ba 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueMemberRemovedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberRemovedEvent.java @@ -21,18 +21,17 @@ * 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; - + Boolean paused; Integer penalty; String stateinterface; @@ -41,105 +40,115 @@ public class QueueMemberRemovedEvent extends AbstractQueueMemberEvent Boolean ringinuse; Long lastcall; Integer status; - + Integer logintime; + Integer wrapuptime; + Integer lastpause; - public QueueMemberRemovedEvent(Object source) - { + + public QueueMemberRemovedEvent(Object source) { super(source); } - public Boolean getPaused() - { - return paused; - } + public Boolean getPaused() { + return paused; + } + + public void setPaused(Boolean paused) { + this.paused = paused; + } - public void setPaused(Boolean paused) - { - this.paused = paused; - } + public Integer getPenalty() { + return penalty; + } - public Integer getPenalty() - { - return penalty; - } + public void setPenalty(Integer penalty) { + this.penalty = 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 String getStateinterface() - { - return stateinterface; - } + public void setMembership(String membership) { + this.membership = membership; + } - public void setStateinterface(String stateinterface) - { - this.stateinterface = stateinterface; - } + public Long getCallstaken() { + return callstaken; + } - public String getMembership() - { - return membership; - } + public void setCallstaken(Long callstaken) { + this.callstaken = callstaken; + } - public void setMembership(String membership) - { - this.membership = membership; + public Boolean getRinginuse() { + return ringinuse; } - public Long getCallstaken() - { - return callstaken; - } + public void setRinginuse(Boolean ringinuse) { + this.ringinuse = ringinuse; + } - public void setCallstaken(Long callstaken) - { - this.callstaken = callstaken; - } + public Long getLastcall() { + return lastcall; + } - public Boolean getRinginuse() - { - return ringinuse; - } + public void setLastcall(Long lastcall) { + this.lastcall = lastcall; + } - public void setRinginuse(Boolean ringinuse) - { - this.ringinuse = ringinuse; - } + public Integer getStatus() { + return status; + } - public Long getLastcall() - { - return lastcall; - } + public void setStatus(Integer status) { + this.status = status; + } - public void setLastcall(Long lastcall) - { - this.lastcall = lastcall; - } + public Integer getLoginTime() { + return logintime; + } + public void setLoginTime(Integer logintime) { + this.logintime = logintime; + } - public Integer getStatus() - { - return status; - } + public Integer getWrapupTime() { + return wrapuptime; + } + public void setWrapupTime(Integer wrapuptime) { + this.wrapuptime = wrapuptime; + } - public void setStatus(Integer status) - { - this.status = status; - } + 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 f70dd6b67..1529654c1 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueMemberStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueMemberStatusEvent.java @@ -18,12 +18,11 @@ /** * A QueueMemberStatusEvent shows the status of a QueueMemberEvent - * + * * @author Asteria Solutions Group, Inc. http://www.asteriasgi.com/ * @version $Id$ */ -public class QueueMemberStatusEvent extends QueueMemberEvent -{ +public class QueueMemberStatusEvent extends QueueMemberEvent { /** * Serializable version identifier */ @@ -35,34 +34,29 @@ public class QueueMemberStatusEvent extends QueueMemberEvent /** * @param source */ - public QueueMemberStatusEvent(Object source) - { + public QueueMemberStatusEvent(Object source) { super(source); } /** * @return the ringinuse */ - public String getRinginuse() - { + public String getRinginuse() { return ringinuse; } /** * @param ringinuse the ringinuse to set */ - public void setRinginuse(String ringinuse) - { + public void setRinginuse(String ringinuse) { this.ringinuse = ringinuse; } - public Integer getWrapuptime() - { + public Integer getWrapuptime() { return wrapuptime; } - public void setWrapuptime(Integer 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 504dc3e83..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. */ @@ -44,8 +43,7 @@ public class QueueParamsEvent extends ResponseEvent private Double serviceLevelPerf2; private Integer weight; - public QueueParamsEvent(Object source) - { + public QueueParamsEvent(Object source) { super(source); } @@ -55,8 +53,7 @@ public QueueParamsEvent(Object source) * * @return the name of the queue. */ - public String getQueue() - { + public String getQueue() { return queue; } @@ -65,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; } @@ -76,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; } @@ -86,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; } @@ -107,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; } @@ -118,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; } @@ -128,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; } @@ -138,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; } @@ -148,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; } @@ -158,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; } @@ -169,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; } @@ -180,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; } @@ -190,8 +176,7 @@ public void setTalkTime(Integer talkTime) * * @return the number of completed calls. */ - public Integer getCompleted() - { + public Integer getCompleted() { return completed; } @@ -200,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; } @@ -210,8 +194,7 @@ public void setCompleted(Integer complete) * * @return the number of abandoned calls. */ - public Integer getAbandoned() - { + public Integer getAbandoned() { return abandoned; } @@ -220,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; } @@ -231,8 +213,7 @@ public void setAbandoned(Integer abandoned) * * @return the service level (in seconds). */ - public Integer getServiceLevel() - { + public Integer getServiceLevel() { return serviceLevel; } @@ -241,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; } @@ -251,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; } @@ -265,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; } @@ -279,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; } @@ -293,8 +270,7 @@ 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; } @@ -307,5 +283,4 @@ public void setServiceLevelPerf2(Double serviceLevelPerf2) { } - } diff --git a/src/main/java/org/asteriskjava/manager/event/QueueStatusCompleteEvent.java b/src/main/java/org/asteriskjava/manager/event/QueueStatusCompleteEvent.java index 5783bc7a1..44ab073e8 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueStatusCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueStatusCompleteEvent.java @@ -20,49 +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 = -1177773673509373297L; - + private Integer listItems; private String eventList; /** * @param source */ - public QueueStatusCompleteEvent(Object source) - { + public QueueStatusCompleteEvent(Object source) { super(source); } - public Integer getListItems() - { + public Integer getListItems() { return listItems; } - public void setListItems(Integer listItems) - { + public void setListItems(Integer listItems) { this.listItems = listItems; } - 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/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 dad4cab15..723c51aab 100644 --- a/src/main/java/org/asteriskjava/manager/event/QueueSummaryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/QueueSummaryEvent.java @@ -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,8 +65,7 @@ public Integer getLoggedIn() * * @param loggedIn the number of members logged in. */ - public void setLoggedIn(Integer loggedIn) - { + public void setLoggedIn(Integer loggedIn) { this.loggedIn = loggedIn; } @@ -82,8 +76,7 @@ public void setLoggedIn(Integer loggedIn) * * @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 5dfb41444..a38c571e8 100644 --- a/src/main/java/org/asteriskjava/manager/event/ReceiveFaxEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ReceiveFaxEvent.java @@ -3,8 +3,7 @@ /** * 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 callerId; @@ -15,88 +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 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 83a931c3b..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,12 +106,11 @@ 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() - { + 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() - { + 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 9ea5c8cec..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 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 13184eaa7..cd7f1312a 100644 --- a/src/main/java/org/asteriskjava/manager/event/ResponseEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ResponseEvent.java @@ -26,14 +26,12 @@ * @version $Id$ * @see org.asteriskjava.manager.action.ManagerAction */ -public abstract class ResponseEvent extends ManagerEvent -{ +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); } @@ -43,11 +41,10 @@ public ResponseEvent(Object source) * 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; } @@ -55,10 +52,9 @@ public final String getActionId() * Sets the action id of the ManagerAction that caused this event. * * @param actionId the action id of the ManagerAction that caused this - * event. + * event. */ - public final void setActionId(String actionId) - { + public final void setActionId(String actionId) { this.actionId = actionId; } @@ -70,11 +66,10 @@ public final void setActionId(String actionId) * 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; } @@ -82,11 +77,10 @@ public final String getInternalActionId() * Sets the internal action id of the ManagerAction that caused this event. * * @param internalActionId the internal action id of the ManagerAction that - * caused this event. + * 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 c5d9682c0..11681ebae 100644 --- a/src/main/java/org/asteriskjava/manager/event/RtcpReceivedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RtcpReceivedEvent.java @@ -27,8 +27,7 @@ * @version $Id$ * @since 1.0.0 */ -public class RtcpReceivedEvent extends AbstractRtcpEvent -{ +public class RtcpReceivedEvent extends AbstractRtcpEvent { private static final long serialVersionUID = 2L; /** @@ -52,9 +51,9 @@ public class RtcpReceivedEvent extends AbstractRtcpEvent private Long sequenceNumberCycles; private Double lastSr; private Double rtt; - + private String channel; - private String language; + private String language; private String report0SequenceNumberCycles; private String ssrc; private String linkedId; @@ -74,10 +73,10 @@ public class RtcpReceivedEvent extends AbstractRtcpEvent private Long sentPackets; private Long sentrtp; private String accountCode; - + private Double mes; + - public RtcpReceivedEvent(Object source) - { + public RtcpReceivedEvent(Object source) { super(source); } @@ -86,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; } @@ -96,13 +94,11 @@ 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); @@ -113,18 +109,16 @@ public void setFrom(String from) * * @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); } - + /** * Indicates the format of the payload, typical values are 200 for sender reports and * 201 for receiver reports. @@ -133,44 +127,34 @@ public void setTo(String to) * @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; } - try - { - if (ptString.indexOf('(') > 0) - { + try { + if (ptString.indexOf('(') > 0) { this.pt = Long.parseLong(ptString.substring(0, ptString.indexOf('('))); - } - else - { + } else { this.pt = Long.parseLong(ptString); } - } catch (NumberFormatException e) - { + } 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; } @@ -179,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; } @@ -194,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; } @@ -239,216 +213,179 @@ public void setLastSr(Double lastSr) * * @return the round trip time in seconds, may be null. */ - public Double getRtt() - { + public Double getRtt() { return rtt; } - public void setRtt(String rttString) - { + public void setRtt(String rttString) { this.rtt = secStringToDouble(rttString); } - - public Long getRttAsMillseconds() - { - return (long) (rtt * 1000); + + public Long getRttAsMillseconds() { + return (long) (rtt * 1000); } - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getReport0SequenceNumberCycles() - { + public String getReport0SequenceNumberCycles() { return report0SequenceNumberCycles; } - public void setReport0SequenceNumberCycles(String report0SequenceNumberCycles) - { + public void setReport0SequenceNumberCycles(String report0SequenceNumberCycles) { this.report0SequenceNumberCycles = report0SequenceNumberCycles; } - public String getSsrc() - { + public String getSsrc() { return ssrc; } - public void setSsrc(String ssrc) - { + public void setSsrc(String ssrc) { this.ssrc = ssrc; } - public String getReport0lsr() - { + public String getReport0lsr() { return report0lsr; } - public void setReport0lsr(String report0lsr) - { + public void setReport0lsr(String report0lsr) { this.report0lsr = report0lsr; } - public Long getSentOctets() - { + public Long getSentOctets() { return sentOctets; } - public void setSentOctets(Long sentOctets) - { + public void setSentOctets(Long sentOctets) { this.sentOctets = sentOctets; } - public String getReport0Sourcessrc() - { + public String getReport0Sourcessrc() { return report0Sourcessrc; } - public void setReport0Sourcessrc(String report0Sourcessrc) - { + public void setReport0Sourcessrc(String report0Sourcessrc) { this.report0Sourcessrc = report0Sourcessrc; } - public Double getReport0dlsr() - { + public Double getReport0dlsr() { return report0dlsr; } - public void setReport0dlsr(Double report0dlsr) - { + public void setReport0dlsr(Double report0dlsr) { this.report0dlsr = report0dlsr; } - public String getUniqueid() - { + public String getUniqueid() { return uniqueid; } - public void setUniqueid(String uniqueid) - { + public void setUniqueid(String uniqueid) { this.uniqueid = uniqueid; } - public Integer getReport0CumulativeLost() - { + public Integer getReport0CumulativeLost() { return report0CumulativeLost; } - public void setReport0CumulativeLost(Integer report0CumulativeLost) - { + public void setReport0CumulativeLost(Integer report0CumulativeLost) { this.report0CumulativeLost = report0CumulativeLost; } - public Integer getReport0FractionLost() - { + public Integer getReport0FractionLost() { return report0FractionLost; } - public void setReport0FractionLost(Integer report0FractionLost) - { + public void setReport0FractionLost(Integer report0FractionLost) { this.report0FractionLost = report0FractionLost; } - public Long getReport0iaJitter() - { + public Long getReport0iaJitter() { return report0iaJitter; } - public void setReport0iaJitter(Long report0iaJitter) - { + public void setReport0iaJitter(Long report0iaJitter) { this.report0iaJitter = report0iaJitter; } - public InetAddress getToAddress() - { + public InetAddress getToAddress() { return toAddress; } - public String getSentntp() - { + public String getSentntp() { return sentntp; } - public void setSentntp(String sentntp) - { + public void setSentntp(String 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; } - public Integer getReportCount() - { + public Integer getReportCount() { return reportCount; } - public void setReportCount(Integer reportCount) - { + public void setReportCount(Integer reportCount) { this.reportCount = reportCount; } - public Integer getReport0HighestSequence() - { + public Integer getReport0HighestSequence() { return report0HighestSequence; } - public void setReport0HighestSequence(Integer report0HighestSequence) - { + public void setReport0HighestSequence(Integer report0HighestSequence) { this.report0HighestSequence = report0HighestSequence; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public Long getSentPackets() - { + public Long getSentPackets() { return sentPackets; } - public void setSentPackets(Long sentPackets) - { + public void setSentPackets(Long sentPackets) { this.sentPackets = sentPackets; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String 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 e556ce733..188a7bf00 100644 --- a/src/main/java/org/asteriskjava/manager/event/RtcpSentEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RtcpSentEvent.java @@ -27,8 +27,7 @@ * @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; @@ -59,9 +58,9 @@ public class RtcpSentEvent extends AbstractRtcpEvent private Integer report0iaJitter; private Integer report0HighestSequence; private String accountCode; - - public RtcpSentEvent(Object source) - { + private Double mes; + + public RtcpSentEvent(Object source) { super(source); } @@ -70,8 +69,7 @@ public RtcpSentEvent(Object source) * * @return the IP address the RTCP message has been received from. */ - public InetAddress getFromAddress() - { + public InetAddress getFromAddress() { return fromAddress; } @@ -80,13 +78,11 @@ 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); @@ -100,38 +96,31 @@ public void setFrom(String from) * @see #RtcpReceivedEvent.PT_SENDER_REPORT * @see #RtcpReceivedEvent.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) - { + if (ptString.indexOf('(') > 0) { this.pt = Long.parseLong(ptString.substring(0, ptString.indexOf('('))); - } - else - { + } 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; } @@ -140,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); @@ -154,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; } @@ -191,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; } @@ -206,183 +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; } - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public String getReport0SequenceNumberCycles() - { + public String getReport0SequenceNumberCycles() { return report0SequenceNumberCycles; } - public void setReport0SequenceNumberCycles(String report0SequenceNumberCycles) - { + public void setReport0SequenceNumberCycles(String report0SequenceNumberCycles) { this.report0SequenceNumberCycles = report0SequenceNumberCycles; } - public String getSsrc() - { + public String getSsrc() { return ssrc; } - public void setSsrc(String ssrc) - { + public void setSsrc(String ssrc) { this.ssrc = ssrc; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getReport0lsr() - { + public String getReport0lsr() { return report0lsr; } - public void setReport0lsr(String report0lsr) - { + public void setReport0lsr(String report0lsr) { this.report0lsr = report0lsr; } - public String getReport0Sourcessrc() - { + public String getReport0Sourcessrc() { return report0Sourcessrc; } - public void setReport0Sourcessrc(String report0Sourcessrc) - { + public void setReport0Sourcessrc(String report0Sourcessrc) { this.report0Sourcessrc = report0Sourcessrc; } - public Double getReport0dlsr() - { + public Double getReport0dlsr() { return report0dlsr; } - public void setReport0dlsr(Double report0dlsr) - { + public void setReport0dlsr(Double report0dlsr) { this.report0dlsr = report0dlsr; } - public String getUniqueid() - { + public String getUniqueid() { return uniqueid; } - public void setUniqueid(String uniqueid) - { + public void setUniqueid(String uniqueid) { this.uniqueid = uniqueid; } - public Integer getReportCount() - { + public Integer getReportCount() { return reportCount; } - public void setReportCount(Integer reportCount) - { + public void setReportCount(Integer reportCount) { this.reportCount = reportCount; } - public Integer getReport0CumulativeLost() - { + public Integer getReport0CumulativeLost() { return report0CumulativeLost; } - public void setReport0CumulativeLost(Integer report0CumulativeLost) - { + public void setReport0CumulativeLost(Integer report0CumulativeLost) { this.report0CumulativeLost = report0CumulativeLost; } - public Integer getReport0FractionLost() - { + public Integer getReport0FractionLost() { return report0FractionLost; } - public void setReport0FractionLost(Integer report0FractionLost) - { + public void setReport0FractionLost(Integer report0FractionLost) { this.report0FractionLost = report0FractionLost; } - public Integer getReport0iaJitter() - { + public Integer getReport0iaJitter() { return report0iaJitter; } - public void setReport0iaJitter(Integer report0iaJitter) - { + public void setReport0iaJitter(Integer report0iaJitter) { this.report0iaJitter = report0iaJitter; } - public Integer getReport0HighestSequence() - { + public Integer getReport0HighestSequence() { return report0HighestSequence; } - public void setReport0HighestSequence(Integer report0HighestSequence) - { + public void setReport0HighestSequence(Integer report0HighestSequence) { this.report0HighestSequence = report0HighestSequence; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } -} \ No newline at end of file + + 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 49416cc88..e31aeab88 100644 --- a/src/main/java/org/asteriskjava/manager/event/RtpReceiverStatEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/RtpReceiverStatEvent.java @@ -26,8 +26,7 @@ * @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; @@ -35,8 +34,7 @@ public class RtpReceiverStatEvent extends AbstractRtpStatEvent private Long rrCount; private String accountCode; - public RtpReceiverStatEvent(Object source) - { + public RtpReceiverStatEvent(Object source) { super(source); } @@ -45,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; } @@ -70,25 +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; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String accountCode) - { + public void setAccountCode(String accountCode) { this.accountCode = accountCode; } - - -} \ No newline at end of file + + +} 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 1f6ae5ae0..7209364cc 100644 --- a/src/main/java/org/asteriskjava/manager/event/SendFaxEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SendFaxEvent.java @@ -19,12 +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 channel; private String callerId; private String localStationId; private String remoteStationId; @@ -33,18 +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); } + @Override + public String getChannel() { + return channel; + } + + @Override + public void setChannel(String channel) { + this.channel = channel; + } /** * @return the callerId */ - public String getCallerId() - { + public String getCallerId() { return callerId; } @@ -52,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; } @@ -61,8 +71,7 @@ public void setCallerId(String callerId) /** * @return the localStationId */ - public String getLocalStationId() - { + public String getLocalStationId() { return localStationId; } @@ -70,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; } @@ -79,8 +87,7 @@ public void setLocalStationId(String localStationId) /** * @return the remoteStationId */ - public String getRemoteStationId() - { + public String getRemoteStationId() { return remoteStationId; } @@ -88,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; } @@ -97,8 +103,7 @@ public void setRemoteStationId(String remoteStationId) /** * @return the pagesTransferred */ - public String getPagesTransferred() - { + public String getPagesTransferred() { return pagesTransferred; } @@ -106,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; } @@ -115,8 +119,7 @@ public void setPagesTransferred(String pagesTransferred) /** * @return the resolution */ - public String getResolution() - { + public String getResolution() { return resolution; } @@ -124,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; } @@ -133,8 +135,7 @@ public void setResolution(String resolution) /** * @return the transferRate */ - public String getTransferRate() - { + public String getTransferRate() { return transferRate; } @@ -142,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; } @@ -151,8 +151,7 @@ public void setTransferRate(String transferRate) /** * @return the fileName */ - public String getFileName() - { + public String getFileName() { return fileName; } @@ -160,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 f09be6e8b..6a84f1c7b 100644 --- a/src/main/java/org/asteriskjava/manager/event/SendFaxStatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SendFaxStatusEvent.java @@ -19,8 +19,7 @@ /** * 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. */ @@ -31,8 +30,7 @@ public class SendFaxStatusEvent extends AbstractFaxEvent private String fileName; - public SendFaxStatusEvent(Object source) - { + public SendFaxStatusEvent(Object source) { super(source); } @@ -40,8 +38,7 @@ public SendFaxStatusEvent(Object source) /** * @return the status */ - public String getStatus() - { + public String getStatus() { return status; } @@ -49,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; } @@ -58,8 +54,7 @@ public void setStatus(String status) /** * @return the callerId */ - public String getCallerId() - { + public String getCallerId() { return callerId; } @@ -67,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; } @@ -76,8 +70,7 @@ public void setCallerId(String callerId) /** * @return the localStationId */ - public String getLocalStationId() - { + public String getLocalStationId() { return localStationId; } @@ -85,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; } @@ -94,8 +86,7 @@ public void setLocalStationId(String localStationId) /** * @return the fileName */ - public String getFileName() - { + public String getFileName() { return fileName; } @@ -103,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 67ce040bc..913241a1c 100644 --- a/src/main/java/org/asteriskjava/manager/event/SkypeChatMessageEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SkypeChatMessageEvent.java @@ -17,8 +17,7 @@ package org.asteriskjava.manager.event; import java.nio.charset.StandardCharsets; - -import org.asteriskjava.util.Base64; +import java.util.Base64; /** * A SkypeChatMessageEvent is triggered when a Skype Chat message is sent or @@ -30,8 +29,7 @@ * * @since 1.0.0 */ -public class SkypeChatMessageEvent extends ManagerEvent -{ +public class SkypeChatMessageEvent extends ManagerEvent { /** * Serializable version identifier. */ @@ -41,8 +39,7 @@ public class SkypeChatMessageEvent extends ManagerEvent private String from; private String message; - public SkypeChatMessageEvent(Object source) - { + public SkypeChatMessageEvent(Object source) { super(source); } @@ -51,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; } @@ -61,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; } @@ -71,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; } @@ -81,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; } @@ -91,8 +84,7 @@ public void setFrom(String from) * * @return the Base64 encoded message. */ - public String getMessage() - { + public String getMessage() { return message; } @@ -101,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; } @@ -111,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), StandardCharsets.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 96aefa352..2d0d2c09e 100644 --- a/src/main/java/org/asteriskjava/manager/event/SkypeLicenseEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SkypeLicenseEvent.java @@ -25,8 +25,7 @@ * @see org.asteriskjava.manager.action.SkypeLicenseListAction * @since 1.0.0 */ -public class SkypeLicenseEvent extends ResponseEvent -{ +public class SkypeLicenseEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -37,8 +36,7 @@ public class SkypeLicenseEvent extends ResponseEvent private Integer channels; private String status; - public SkypeLicenseEvent(Object source) - { + public SkypeLicenseEvent(Object source) { super(source); } @@ -47,8 +45,7 @@ public SkypeLicenseEvent(Object source) * * @return the license key. */ - public String getKey() - { + public String getKey() { return key; } @@ -57,8 +54,7 @@ public String getKey() * * @param key the license key. */ - public void setKey(String key) - { + public void setKey(String key) { this.key = key; } @@ -67,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; } @@ -77,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; } @@ -97,8 +89,7 @@ public void setHostId(String hostId) * * @return the number of licensed channels. */ - public Integer getChannels() - { + public Integer getChannels() { return channels; } @@ -107,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 index 25523b435..6179a3e10 100644 --- a/src/main/java/org/asteriskjava/manager/event/SoftHangupRequestEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SoftHangupRequestEvent.java @@ -21,8 +21,7 @@ *

    * It is implemented in channel.c */ -public class SoftHangupRequestEvent extends AbstractChannelEvent -{ +public class SoftHangupRequestEvent extends AbstractChannelEvent { /** * Serializable version identifier. */ @@ -32,18 +31,15 @@ public class SoftHangupRequestEvent extends AbstractChannelEvent private String language; private String linkedId; - public SoftHangupRequestEvent(Object source) - { + public SoftHangupRequestEvent(Object source) { super(source); } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } @@ -53,8 +49,7 @@ public void setLanguage(String language) * @return the hangup cause. * @see org.asteriskjava.live.HangupCause */ - public Integer getCause() - { + public Integer getCause() { return cause; } @@ -63,19 +58,16 @@ public Integer getCause() * * @param cause the hangup cause. */ - public void setCause(Integer cause) - { + public void setCause(Integer cause) { this.cause = cause; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String 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 ac0763832..74e0a124c 100644 --- a/src/main/java/org/asteriskjava/manager/event/StatusCompleteEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/StatusCompleteEvent.java @@ -19,14 +19,13 @@ /** * 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 + * * @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. */ @@ -36,8 +35,7 @@ public class StatusCompleteEvent extends ResponseEvent private Integer listItems; private String eventList; - public StatusCompleteEvent(Object source) - { + public StatusCompleteEvent(Object source) { super(source); } @@ -49,8 +47,7 @@ public StatusCompleteEvent(Object source) * @return the number of channels reported. * @since 1.0.0 */ - public Integer getItems() - { + public Integer getItems() { return items; } @@ -62,34 +59,24 @@ public Integer getItems() * @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() - { + public Integer getListItems() { return listItems; } - public void setListitems(Integer listItems) - { - this.listItems = listItems; - } - - public String getEventList() - { + public String getEventList() { return eventList; } - public void setEventList(String eventList) - { + public void setEventList(String eventList) { this.eventList = eventList; } - public void setListItems(Integer listItems) - { + 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 be7009575..193a0be3d 100644 --- a/src/main/java/org/asteriskjava/manager/event/StatusEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/StatusEvent.java @@ -26,8 +26,7 @@ * @version $Id$ * @see org.asteriskjava.manager.action.StatusAction */ -public class StatusEvent extends ResponseEvent -{ +public class StatusEvent extends ResponseEvent { /** * Serial version identifier. */ @@ -57,8 +56,7 @@ public class StatusEvent extends ResponseEvent private String readtrans; private String language; - public StatusEvent(Object source) - { + public StatusEvent(Object source) { super(source); } @@ -67,8 +65,7 @@ public StatusEvent(Object source) * * @return the name of this channel. */ - public String getChannel() - { + public String getChannel() { return channel; } @@ -77,8 +74,7 @@ public String getChannel() * * @param channel the name of this channel. */ - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -89,12 +85,11 @@ public void setChannel(String channel) * {@link #getCallerIdNum()} instead. * * @return the Caller*ID Number of this channel or null if none - * is available. + * is available. * @deprecated */ @Deprecated - public String getCallerId() - { + public String getCallerId() { return callerIdNum; } @@ -105,8 +100,7 @@ public String getCallerId() * * @param callerIdNum the Caller*ID Number to set. */ - public void setCallerId(String callerIdNum) - { + public void setCallerId(String callerIdNum) { this.callerIdNum = callerIdNum; } @@ -116,8 +110,7 @@ public void setCallerId(String callerIdNum) * @return the account code of this channel. * @since 1.0.0 */ - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } @@ -127,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; } @@ -139,8 +131,7 @@ public void setAccountCode(String accountCode) * @deprecated since 1.0.0, use {@link #getAccountCode()} instead. */ @Deprecated - public String getAccount() - { + public String getAccount() { return accountCode; } @@ -152,8 +143,7 @@ public String getAccount() * * @param account the account code of this channel. */ - public void setAccount(String account) - { + public void setAccount(String account) { this.accountCode = account; } @@ -164,23 +154,19 @@ public void setAccount(String account) * @deprecated use {@link #getChannelStateDesc()} instead. */ @Deprecated - public String getState() - { + public String getState() { return getChannelStateDesc(); } - public void setState(String state) - { + public void setState(String state) { setChannelStateDesc(state); } - public String getExtension() - { + public String getExtension() { return getExten(); } - public void setExtension(String extension) - { + public void setExtension(String extension) { setExten(extension); } @@ -189,8 +175,7 @@ public void setExtension(String extension) * * @return the number of elapsed seconds. */ - public Integer getSeconds() - { + public Integer getSeconds() { return seconds; } @@ -199,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; } @@ -210,8 +194,7 @@ 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; } @@ -219,11 +202,10 @@ public String getBridgedChannel() * Sets the name of the linked channel. * * @param bridgedChannel the name of the linked channel if this channel is - * bridged. + * bridged. * @since 1.0.0 */ - public void setBridgedChannel(String bridgedChannel) - { + public void setBridgedChannel(String bridgedChannel) { this.bridgedChannel = bridgedChannel; } @@ -234,8 +216,7 @@ public void setBridgedChannel(String bridgedChannel) * @deprecated as of 1.0.0, use {@link #getBridgedChannel()} instead. */ @Deprecated - public String getLink() - { + public String getLink() { return bridgedChannel; } @@ -246,8 +227,7 @@ public String getLink() * * @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; } @@ -259,8 +239,7 @@ public void setLink(String link) * @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; } @@ -270,11 +249,10 @@ public String getBridgedUniqueId() * Available since Asterisk 1.6. * * @param bridgedUniqueId the unique id of the linked channel if this - * channel is bridged. + * channel is bridged. * @since 1.0.0 */ - public void setBridgedUniqueId(String bridgedUniqueId) - { + public void setBridgedUniqueId(String bridgedUniqueId) { this.bridgedUniqueId = bridgedUniqueId; } @@ -283,8 +261,7 @@ public void setBridgedUniqueId(String bridgedUniqueId) * * @return the unique id of this channel. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } @@ -293,8 +270,7 @@ public String getUniqueId() * * @param uniqueId the unique id of this channel. */ - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -308,8 +284,7 @@ public void setUniqueId(String uniqueId) * @return the channel variables. * @since 1.0.0 */ - public Map getVariables() - { + public Map getVariables() { return variables; } @@ -321,202 +296,167 @@ 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; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getData() - { + public String getData() { return data; } - public void setData(String data) - { + public void setData(String data) { this.data = data; } - public String getReadFormat() - { + public String getReadFormat() { return readFormat; } - public void setReadFormat(String readFormat) - { + public void setReadFormat(String readFormat) { this.readFormat = readFormat; } - public String getWriteFormat() - { + public String getWriteFormat() { return writeFormat; } - public void setWriteFormat(String writeFormat) - { + public void setWriteFormat(String writeFormat) { this.writeFormat = writeFormat; } - public String getType() - { + public String getType() { return type; } - public void setType(String type) - { + public void setType(String type) { this.type = type; } - public String getEffectiveConnectedLineName() - { + public String getEffectiveConnectedLineName() { return effectiveConnectedLineName; } - public void setEffectiveConnectedLineName(String effectiveConnectedLineName) - { + public void setEffectiveConnectedLineName(String effectiveConnectedLineName) { this.effectiveConnectedLineName = effectiveConnectedLineName; } - public String getEffectiveConnectedLineNum() - { + public String getEffectiveConnectedLineNum() { return effectiveConnectedLineNum; } - public void setEffectiveConnectedLineNum(String effectiveConnectedLineNum) - { + public void setEffectiveConnectedLineNum(String effectiveConnectedLineNum) { this.effectiveConnectedLineNum = effectiveConnectedLineNum; } - public String getApplication() - { + public String getApplication() { return application; } - public void setApplication(String application) - { + public void setApplication(String application) { this.application = application; } - public String getCallGroup() - { + public String getCallGroup() { return callGroup; } - public void setCallGroup(String callGroup) - { + public void setCallGroup(String callGroup) { this.callGroup = callGroup; } - public String getNativeFormats() - { + public String getNativeFormats() { return nativeFormats; } - public void setNativeFormats(String nativeFormats) - { + public void setNativeFormats(String nativeFormats) { this.nativeFormats = nativeFormats; } - public String getPickupGroup() - { + public String getPickupGroup() { return pickupGroup; } - public void setPickupGroup(String pickupGroup) - { + public void setPickupGroup(String pickupGroup) { this.pickupGroup = pickupGroup; } - public String getTimeToHangup() - { + public String getTimeToHangup() { return timeToHangup; } - public void setTimeToHangup(String timeToHangup) - { + public void setTimeToHangup(String timeToHangup) { this.timeToHangup = timeToHangup; } /** * @return the dnid */ - public String getDnid() - { + public String getDnid() { return dnid; } /** * @param dnid the dnid to set */ - public void setDnid(String dnid) - { + public void setDnid(String dnid) { this.dnid = dnid; } /** * @return the writetrans */ - public String getWritetrans() - { + public String getWritetrans() { return writetrans; } /** * @param writetrans the writetrans to set */ - public void setWritetrans(String writetrans) - { + public void setWritetrans(String writetrans) { this.writetrans = writetrans; } /** * @return the bridgeid */ - public String getBridgeId() - { + public String getBridgeId() { return bridgeId; } /** * @param bridgeid the bridgeid to set */ - public void setBridgeId(String bridgeid) - { + public void setBridgeId(String bridgeid) { this.bridgeId = bridgeid; } /** * @return the readtrans */ - public String getReadtrans() - { + public String getReadtrans() { return readtrans; } /** * @param readtrans the readtrans to set */ - public void setReadtrans(String readtrans) - { + public void setReadtrans(String readtrans) { this.readtrans = readtrans; } - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String 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 index 9e8b7e4df..33a4ed511 100644 --- a/src/main/java/org/asteriskjava/manager/event/SuccessfulAuthEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/SuccessfulAuthEvent.java @@ -3,125 +3,112 @@ /** * Created by plhk on 1/15/15. */ -public class SuccessfulAuthEvent extends ManagerEvent -{ - /** - * - */ - private static final long serialVersionUID = 1L; - 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; - - 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 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 dbfce1eca..a17771658 100644 --- a/src/main/java/org/asteriskjava/manager/event/UnholdEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/UnholdEvent.java @@ -30,23 +30,21 @@ * @version $Id$ * @see org.asteriskjava.manager.event.HoldEvent * @since 0.2 Enro 2015-03: No longer deprecated since Asterisk 13 uses this - * again. + * again. */ -public class UnholdEvent extends AbstractHoldEvent -{ +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 f8fa999a9..6795b6521 100644 --- a/src/main/java/org/asteriskjava/manager/event/UnparkedCallEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/UnparkedCallEvent.java @@ -23,13 +23,12 @@ * It is implemented in res/res_features.c *

    * Available since Asterisk 1.2 - * + * * @author srt * @version $Id$ * @since 0.2 */ -public class UnparkedCallEvent extends AbstractUnParkedEvent -{ +public class UnparkedCallEvent extends AbstractUnParkedEvent { /** * Serializable version identifier */ @@ -54,128 +53,103 @@ public class UnparkedCallEvent extends AbstractUnParkedEvent /** * @param source */ - public UnparkedCallEvent(Object source) - { + public UnparkedCallEvent(Object source) { super(source); } - public String getRetrieverChannel() - { + public String getRetrieverChannel() { return RetrieverChannel; } - public void setRetrieverChannel(String retrieverChannel) - { + public void setRetrieverChannel(String retrieverChannel) { RetrieverChannel = retrieverChannel; } - public Integer getRetrieverChannelState() - { + public Integer getRetrieverChannelState() { return RetrieverChannelState; } - public void setRetrieverChannelState(Integer retrieverChannelState) - { + public void setRetrieverChannelState(Integer retrieverChannelState) { RetrieverChannelState = retrieverChannelState; } - public String getRetrieverChannelStateDesc() - { + public String getRetrieverChannelStateDesc() { return RetrieverChannelStateDesc; } - public void setRetrieverChannelStateDesc(String retrieverChannelStateDesc) - { + public void setRetrieverChannelStateDesc(String retrieverChannelStateDesc) { RetrieverChannelStateDesc = retrieverChannelStateDesc; } - public String getRetrieverCallerIDNum() - { + public String getRetrieverCallerIDNum() { return RetrieverCallerIDNum; } - public void setRetrieverCallerIDNum(String retrieverCallerIDNum) - { + public void setRetrieverCallerIDNum(String retrieverCallerIDNum) { RetrieverCallerIDNum = retrieverCallerIDNum; } - public String getRetrieverCallerIDName() - { + public String getRetrieverCallerIDName() { return RetrieverCallerIDName; } - public void setRetrieverCallerIDName(String retrieverCallerIDName) - { + public void setRetrieverCallerIDName(String retrieverCallerIDName) { RetrieverCallerIDName = retrieverCallerIDName; } - public String getRetrieverConnectedLineNum() - { + public String getRetrieverConnectedLineNum() { return RetrieverConnectedLineNum; } - public void setRetrieverConnectedLineNum(String retrieverConnectedLineNum) - { + public void setRetrieverConnectedLineNum(String retrieverConnectedLineNum) { RetrieverConnectedLineNum = retrieverConnectedLineNum; } - public String getRetrieverConnectedLineName() - { + public String getRetrieverConnectedLineName() { return RetrieverConnectedLineName; } - public void setRetrieverConnectedLineName(String retrieverConnectedLineName) - { + public void setRetrieverConnectedLineName(String retrieverConnectedLineName) { RetrieverConnectedLineName = retrieverConnectedLineName; } - public String getRetrieverAccountCode() - { + public String getRetrieverAccountCode() { return RetrieverAccountCode; } - public void setRetrieverAccountCode(String retrieverAccountCode) - { + public void setRetrieverAccountCode(String retrieverAccountCode) { RetrieverAccountCode = retrieverAccountCode; } - public String getRetrieverContext() - { + public String getRetrieverContext() { return RetrieverContext; } - public void setRetrieverContext(String retrieverContext) - { + public void setRetrieverContext(String retrieverContext) { RetrieverContext = retrieverContext; } - public String getRetrieverExten() - { + public String getRetrieverExten() { return RetrieverExten; } - public void setRetrieverExten(String retrieverExten) - { + public void setRetrieverExten(String retrieverExten) { RetrieverExten = retrieverExten; } - public String getRetrieverPriority() - { + public String getRetrieverPriority() { return RetrieverPriority; } - public void setRetrieverPriority(String retrieverPriority) - { + public void setRetrieverPriority(String retrieverPriority) { RetrieverPriority = retrieverPriority; } - public String getRetrieverUniqueid() - { + public String getRetrieverUniqueid() { return RetrieverUniqueid; } - public void setRetrieverUniqueid(String 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 index 76ea9fe00..cd6196e0e 100644 --- a/src/main/java/org/asteriskjava/manager/event/UnpausedEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/UnpausedEvent.java @@ -2,33 +2,33 @@ 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; - } + 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 153a82496..6a8f6a377 100644 --- a/src/main/java/org/asteriskjava/manager/event/UserEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/UserEvent.java @@ -34,29 +34,29 @@ * 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;
      *     }
      * }
      * 
    - * + *

    * 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 @@ -67,13 +67,12 @@ *

    * 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) + * * @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 */ @@ -89,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 3b5feda69..2bf16e395 100644 --- a/src/main/java/org/asteriskjava/manager/event/VarSetEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/VarSetEvent.java @@ -28,8 +28,7 @@ * @version $Id$ * @since 1.0.0 */ -public class VarSetEvent extends ManagerEvent -{ +public class VarSetEvent extends ManagerEvent { static final long serialVersionUID = 1L; private String channel; @@ -40,18 +39,15 @@ public class VarSetEvent extends ManagerEvent private String linkedId; private String accountCode; - public String getLanguage() - { + public String getLanguage() { return language; } - public void setLanguage(String language) - { + public void setLanguage(String language) { this.language = language; } - public VarSetEvent(Object source) - { + public VarSetEvent(Object source) { super(source); } @@ -60,15 +56,13 @@ public VarSetEvent(Object source) * variables. * * @return the name of the channel or null for global - * variables. + * variables. */ - public String getChannel() - { + public String getChannel() { return channel; } - public void setChannel(String channel) - { + public void setChannel(String channel) { this.channel = channel; } @@ -77,15 +71,13 @@ public void setChannel(String channel) * variables. * * @return the unique id of the channel or null for global - * variables. + * variables. */ - public String getUniqueId() - { + public String getUniqueId() { return uniqueId; } - public void setUniqueId(String uniqueId) - { + public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } @@ -94,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; } @@ -109,34 +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; } - public String getLinkedId() - { + public String getLinkedId() { return linkedId; } - public void setLinkedId(String linkedId) - { + public void setLinkedId(String linkedId) { this.linkedId = linkedId; } - public String getAccountCode() - { + public String getAccountCode() { return accountCode; } - public void setAccountCode(String 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 ede012636..8fbc8fd14 100644 --- a/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/VoicemailUserEntryEvent.java @@ -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 062e1b391..5460927b2 100644 --- a/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsEvent.java +++ b/src/main/java/org/asteriskjava/manager/event/ZapShowChannelsEvent.java @@ -19,13 +19,12 @@ /** * A ZapShowChannelsEvent is triggered in response to a ZapShowChannelsAction * and shows the state of a zap channel. - * - * @see org.asteriskjava.manager.action.ZapShowChannelsAction + * * @author srt * @version $Id$ + * @see org.asteriskjava.manager.action.ZapShowChannelsAction */ -public class ZapShowChannelsEvent extends ResponseEvent -{ +public class ZapShowChannelsEvent extends ResponseEvent { /** * Serial version identifier */ @@ -39,24 +38,21 @@ public class ZapShowChannelsEvent extends ResponseEvent /** * @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; } @@ -90,40 +86,36 @@ 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 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. * @since 0.3 */ - public void setDnd(Boolean dnd) - { + public void setDnd(Boolean dnd) { this.dnd = dnd; } @@ -141,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/.gitignore b/src/main/java/org/asteriskjava/manager/internal/.gitignore deleted file mode 100644 index f04e334d4..000000000 --- a/src/main/java/org/asteriskjava/manager/internal/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -/AbstractBuilder.class -/ActionBuilder.class -/ActionBuilderImpl.class -/Dispatcher.class -/EventBuilder.class -/EventBuilderImpl.class -/ManagerConnectionImpl$1.class -/ManagerConnectionImpl$DefaultSendActionCallback.class -/ManagerConnectionImpl$ProtocolIdentifierWrapper.class -/ManagerConnectionImpl$ResponseEventHandler.class -/ManagerConnectionImpl$ResponseHandlerResult.class -/ManagerConnectionImpl.class -/ManagerReader.class -/ManagerReaderImpl.class -/ManagerUtil.class -/ManagerWriter.class -/ManagerWriterImpl.class -/ResponseBuilder.class -/ResponseBuilderImpl.class -/ResponseEventsImpl.class 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 531e41a18..000000000 --- a/src/main/java/org/asteriskjava/manager/internal/AbstractBuilder.java +++ /dev/null @@ -1,239 +0,0 @@ -package org.asteriskjava.manager.internal; - -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.Map.Entry; -import java.util.Set; - -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; - -/** - * Abstract base class for reflection based builders. - */ -abstract class AbstractBuilder -{ - protected final Log logger = LogFactory.getLog(getClass()); - - 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"; - } - 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)) - { - 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 (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 - { - try - { - Constructor< ? > constructor = dataType.getConstructor(String.class); - 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); - } - } - } - - @SuppressWarnings("unchecked") - private 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 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 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 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 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 09cc3d44f..eb7bd69ba 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ActionBuilder.java +++ b/src/main/java/org/asteriskjava/manager/internal/ActionBuilder.java @@ -23,15 +23,14 @@ /** * 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 targetVersion the version of the target Asterisk server. * @since 0.2 */ @@ -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 e4423b4b5..01f440d4c 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ActionBuilderImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ActionBuilderImpl.java @@ -16,14 +16,6 @@ */ package org.asteriskjava.manager.internal; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.manager.AsteriskMapping; import org.asteriskjava.manager.action.ManagerAction; @@ -33,14 +25,17 @@ import org.asteriskjava.util.LogFactory; import org.asteriskjava.util.ReflectionUtil; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + /** * Default implementation of the ActionBuilder interface. * * @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"; @@ -55,10 +50,9 @@ class ActionBuilderImpl implements ActionBuilder /** * 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 @@ -69,32 +63,26 @@ class ActionBuilderImpl implements ActionBuilder 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) - { + 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); @@ -104,19 +92,16 @@ else if (action.getActionId() != null) // 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, getters); - } - else - { + } else { getters = ReflectionUtil.getGetters(action.getClass()); appendGetters(sb, action, getters); @@ -124,26 +109,20 @@ else if (action.getActionId() != null) // actions that have the special getAttributes method will // have their Map appended without a singular key or separator - 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) - { + if (value instanceof Map) { Map attributes = (Map) value; - for (Map.Entry entry : attributes.entrySet()) - { + for (Map.Entry entry : attributes.entrySet()) { appendString(sb, entry.getKey() == null ? "null" : entry.getKey().toString(), - entry.getValue() == null ? "null" : entry.getValue().toString()); + entry.getValue() == null ? "null" : entry.getValue().toString()); } } } @@ -152,75 +131,58 @@ else if (action.getActionId() != null) return sb.toString(); } - private void appendMap(StringBuilder 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(StringBuilder 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(StringBuilder 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) - { - if (entry.getKey().equalsIgnoreCase("Content")) - { + if (entry.getValue() != null) { + if (entry.getKey().equalsIgnoreCase("Content")) { String sp[] = entry.getValue().split("\n"); - if (sp.length > 0) - { + if (sp.length > 0) { sb.append(sp[0]); - for (int i = 1; i < sp.length; i++) - { + for (int i = 1; i < sp.length; i++) { sb.append(LINE_SEPARATOR); sb.append(singularKey); sb.append(": "); @@ -230,9 +192,7 @@ private void appendMap12(StringBuilder sb, String singularKey, Map 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()); } @@ -265,134 +222,98 @@ private void appendUserEvent(StringBuilder sb, UserEvent event) } @SuppressWarnings("unchecked") - private void appendGetters(StringBuilder sb, Object action, Map getters) - { - 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 static 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) - { + = 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) - { + = 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) - { + = 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); } - static 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'"); } } - static 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'"); } } @@ -403,10 +324,8 @@ else if (accessorName.startsWith("set")) * @param s the string to convert. * @return the converted string. */ - private static String lcFirst(String s) - { - if (s == null || s.isEmpty()) - { + private static String lcFirst(String s) { + if (s == null || s.isEmpty()) { return s; } 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 8f1bfdc50..2224dfd2f 100644 --- a/src/main/java/org/asteriskjava/manager/internal/EventBuilder.java +++ b/src/main/java/org/asteriskjava/manager/internal/EventBuilder.java @@ -16,19 +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 @@ -38,23 +37,23 @@ interface EventBuilder *

    * 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}. + * {@link ManagerEvent}. * @throws IllegalArgumentException if clazz is not a valid event class */ - void registerEventClass(Class< ? extends ManagerEvent> clazz) throws IllegalArgumentException; + void registerEventClass(Class clazz) throws IllegalArgumentException; /** * 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< ? extends ManagerEvent> eventClass); + 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 bfff1b375..d007e63e8 100644 --- a/src/main/java/org/asteriskjava/manager/internal/EventBuilderImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/EventBuilderImpl.java @@ -1,42 +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.manager.internal; -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.asteriskjava.manager.event.ManagerEvent; -import org.asteriskjava.manager.event.PeerEntryEvent; -import org.asteriskjava.manager.event.PeersEvent; -import org.asteriskjava.manager.event.ResponseEvent; -import org.asteriskjava.manager.event.UserEvent; +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. * @@ -44,19 +34,17 @@ * @version $Id$ * @see org.asteriskjava.manager.event.ManagerEvent */ -class EventBuilderImpl extends AbstractBuilder implements EventBuilder -{ +class EventBuilderImpl implements EventBuilder { private static final Set ignoredAttributes = new HashSet<>(Arrays.asList("event")); - private Map> registeredEventClasses; + 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); + private final static Set> knownManagerEventClasses = new Reflections( + "org.asteriskjava.manager.event").getSubTypesOf(ManagerEvent.class); - EventBuilderImpl() - { + EventBuilderImpl() { this.registeredEventClasses = new HashMap<>(); registerBuiltinEventClasses(); } @@ -64,32 +52,30 @@ class EventBuilderImpl extends AbstractBuilder implements EventBuilder /** * register the known ManagerEventClasses for this builder */ - private void registerBuiltinEventClasses() - { - for (Class< ? extends ManagerEvent> managerEventClass : knownManagerEventClasses) - { - if (!Modifier.isAbstract(managerEventClass.getModifiers())) - { + private void registerBuiltinEventClasses() { + for (Class managerEventClass : knownManagerEventClasses) { + if (!Modifier.isAbstract(managerEventClass.getModifiers())) { registerEventClass(managerEventClass); } } } - public final void registerEventClass(Class< ? extends ManagerEvent> 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; } @@ -100,93 +86,74 @@ public final void registerEventClass(Class< ? extends ManagerEvent> clazz) throw * Registers a new event class for the event given by eventType. * * @param eventType the name of the event to register the class for. For - * example "Join". - * @param clazz the event class to register, must extend - * {@link ManagerEvent}. + * example "Join". + * @param clazz the event class to register, must extend + * {@link ManagerEvent}. * @throws IllegalArgumentException if clazz is not a valid event class. */ - public final void registerEventClass(String eventType, Class< ? extends ManagerEvent> clazz) - throws IllegalArgumentException - { - Constructor< ? > defaultConstructor; + public final void registerEventClass(String eventType, Class clazz) + throws IllegalArgumentException { + Constructor defaultConstructor; - if (Modifier.isAbstract(clazz.getModifiers())) - { + if (Modifier.isAbstract(clazz.getModifiers())) { throw new IllegalArgumentException(clazz + " is abstract"); } - if (clazz.isInterface()) - { + if (clazz.isInterface()) { throw new IllegalArgumentException(clazz + " is abstract"); } - try - { + try { defaultConstructor = clazz.getConstructor(Object.class); - if (!Modifier.isPublic(defaultConstructor.getModifiers())) - { + if (!Modifier.isPublic(defaultConstructor.getModifiers())) { throw new IllegalArgumentException(clazz + " has no public default constructor"); } - } - catch (NoSuchMethodException ex) - { + } 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 + ")"); } @SuppressWarnings("unchecked") - public ManagerEvent buildEvent(Object source, Map attributes) - { + public ManagerEvent buildEvent(Object source, Map attributes) { ManagerEvent event; String eventType = null; - Class< ? > eventClass; - Constructor< ? > constructor; + 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 List) - { - List< ? > eventNames = (List< ? >) attributes.get("event"); - if (!eventNames.isEmpty() && "PeerEntry".equals(eventNames.get(0))) - { + 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 + ? Integer.parseInt((String) attributes.get("listitems")) + : eventNames.size() - 1; // Last event is + // PeerlistComplete List> peersAttributes = new ArrayList<>(); - for (Map.Entry attribute : attributes.entrySet()) - { + for (Map.Entry attribute : attributes.entrySet()) { String key = attribute.getKey(); Object value = attribute.getValue(); - for (int i = 0; i < peersAmount; i++) - { + for (int i = 0; i < peersAmount; i++) { Map peerAttrs; - if (peersAttributes.size() > i) - { + if (peersAttributes.size() > i) { peerAttrs = peersAttributes.get(i); - } - else - { + } 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)) - { + if (value instanceof List) { + peerAttrs.put(key, ((List) value).get(i)); + } else if (value instanceof String && !"listitems".equals(key)) { peerAttrs.put(key, value); } } @@ -194,108 +161,87 @@ else if (value instanceof String && !"listitems".equals(key)) attributes.put("peersAttributes", peersAttributes); eventType = "peers"; } - } - else - { - if (!(attributes.get("event") instanceof String)) - { + } else { + if (!(attributes.get("event") instanceof String)) { logger.error("Event type is not a String or List"); return null; } - eventType = ((String) attributes.get("event")).toLowerCase(Locale.US); + 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)) - { + if ("userevent".equals(eventType)) { String userEventType; - if (attributes.get("userevent") == null) - { + if (attributes.get("userevent") == null) { logger.error("No user event type in properties"); return null; } - if (!(attributes.get("userevent") instanceof String)) - { + if (!(attributes.get("userevent") instanceof String)) { logger.error("User event type is not a String"); return null; } - userEventType = ((String) attributes.get("userevent")).toLowerCase(Locale.US); + userEventType = ((String) attributes.get("userevent")).toLowerCase(Locale.ENGLISH); eventType = eventType + userEventType; } } eventClass = registeredEventClasses.get(eventType); - if (eventClass == null) - { - if (eventClassNegativeCache.add(eventType)) - { + 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"); + + ". Please report at https://github.com/asterisk-java/asterisk-java/issues"); } return null; } - try - { + try { constructor = eventClass.getConstructor(Object.class); - } - catch (NoSuchMethodException ex) - { + } 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; } - if (attributes.get("peersAttributes") != null && attributes.get("peersAttributes") instanceof List) - { + 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")) - { + for (Map peerAttrs : (List>) attributes.get("peersAttributes")) { PeerEntryEvent peerEntryEvent = new PeerEntryEvent(source); - setAttributes(peerEntryEvent, peerAttrs, ignoredAttributes); + EventAttributesHelper.setAttributes(peerEntryEvent, peerAttrs, ignoredAttributes); List peerEntryEvents = peersEvent.getChildEvents(); - if (peerEntryEvents == null) - { + if (peerEntryEvents == null) { peerEntryEvents = new ArrayList<>(); peersEvent.setChildEvents(peerEntryEvents); } peerEntryEvents.add(peerEntryEvent); } peersEvent.setActionId(peersEvent.getChildEvents().get(0).getActionId()); - } - else - { - setAttributes(event, attributes, ignoredAttributes); + } 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)); } @@ -305,25 +251,18 @@ else if (value instanceof String && !"listitems".equals(key)) } @Override - public void deregisterEventClass(Class< ? extends ManagerEvent> eventClass) - { + public void deregisterEventClass(Class eventClass) { Set toRemove = new HashSet<>(); - for (Entry> registered : registeredEventClasses.entrySet()) - { - if (registered.getValue().equals(eventClass)) - { + for (Entry> registered : registeredEventClasses.entrySet()) { + if (registered.getValue().equals(eventClass)) { toRemove.add(registered.getKey()); } } - if (toRemove.isEmpty()) - { + if (toRemove.isEmpty()) { logger.warn("Couldn't remove event type " + eventClass); - } - else - { - for (String key : toRemove) - { + } 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 c29d0e893..9feeac04b 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerConnectionImpl.java @@ -1,27 +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.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; @@ -34,57 +42,20 @@ 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 org.asteriskjava.AsteriskVersion; -import org.asteriskjava.manager.AuthenticationFailedException; -import org.asteriskjava.manager.EventTimeoutException; -import org.asteriskjava.manager.ExpectedResponse; -import org.asteriskjava.manager.ManagerConnection; -import org.asteriskjava.manager.ManagerConnectionState; -import org.asteriskjava.manager.ManagerEventListener; -import org.asteriskjava.manager.ResponseEvents; -import org.asteriskjava.manager.SendActionCallback; -import org.asteriskjava.manager.SendEventGeneratingActionCallback; -import org.asteriskjava.manager.TimeoutException; -import org.asteriskjava.manager.action.ChallengeAction; -import org.asteriskjava.manager.action.CommandAction; -import org.asteriskjava.manager.action.CoreSettingsAction; -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.action.UserEventAction; -import org.asteriskjava.manager.event.ConnectEvent; -import org.asteriskjava.manager.event.DialBeginEvent; -import org.asteriskjava.manager.event.DialEvent; -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.CoreSettingsResponse; -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 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"; @@ -96,14 +67,22 @@ public class ManagerConnectionImpl implements ManagerConnection, Dispatcher // 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 + "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); @@ -111,7 +90,7 @@ public class ManagerConnectionImpl implements ManagerConnection, Dispatcher /** * Instance logger. */ - private final Log logger = LogFactory.getLog(getClass()); + private final static Log logger = LogFactory.getLog(ManagerConnectionImpl.class); private final long id; @@ -226,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 @@ -235,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; @@ -249,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(); } @@ -277,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; } @@ -290,14 +265,10 @@ 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; } } @@ -310,8 +281,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) { this.ssl = ssl; } @@ -321,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; } @@ -332,14 +301,12 @@ 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) - { + public void setEncoding(Charset encoding) { this.encoding = encoding; } @@ -352,8 +319,7 @@ public void setEncoding(Charset encoding) * @param defaultResponseTimeout default response timeout in milliseconds * @since 0.2 */ - public void setDefaultResponseTimeout(long defaultResponseTimeout) - { + public void setDefaultResponseTimeout(long defaultResponseTimeout) { this.defaultResponseTimeout = defaultResponseTimeout; } @@ -367,8 +333,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) { this.defaultEventTimeout = defaultEventTimeout; } @@ -378,117 +343,96 @@ public void setDefaultEventTimeout(long defaultEventTimeout) * Default is true. * * @param keepAliveAfterAuthenticationFailure true to try - * reconnecting to ther asterisk serve even if the reconnection - * attempt threw an AuthenticationFailedException, - * false otherwise. + * 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; } @Override - public Charset getEncoding() - { + public Charset getEncoding() { return encoding; } - public AsteriskVersion getVersion() - { + 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< ? extends ManagerEvent> 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; + } } } } @@ -507,169 +451,138 @@ public synchronized void login(String eventMask) throws IOException, Authenticat * the received challenge). * * - * @param timeout the maximum time to wait for the protocol identifier (in - * ms) + * @param timeout the maximum time to wait for the protocol identifier (in + * ms) * @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. - * @throws IOException if there is an i/o problem. + * 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 IOException if there is an i/o problem. * @throws AuthenticationFailedException if username or password are - * incorrect and the login action returns an error or if the MD5 - * hash cannot be computed. The connection is closed in this - * case. - * @throws TimeoutException if a timeout occurs while waiting for the - * protocol identifier. The connection is closed in this case. + * incorrect and the login action returns an error or if the MD5 + * hash cannot be computed. The connection is closed in this + * case. + * @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(); - } - - if (protocolIdentifier.getValue() == null) - { - try - { - protocolIdentifier.await(timeout); + 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(); } - catch (InterruptedException e) // NOPMD - { - Thread.currentThread().interrupt(); + + if (protocolIdentifier.getValue() == null) { + try { + protocolIdentifier.await(timeout); + } catch (InterruptedException e) // NOPMD + { + Thread.currentThread().interrupt(); + } } - } - if (protocolIdentifier.getValue() == null) - { - disconnect(); - if (reader != null && reader.getTerminationException() != null) - { - throw reader.getTerminationException(); + if (protocolIdentifier.getValue() == null) { + disconnect(); + if (reader != null && reader.getTerminationException() != null) { + throw reader.getTerminationException(); + } + 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(StandardCharsets.UTF_8)); - } - if (password != null) - { - md.update(password.getBytes(StandardCharsets.UTF_8)); + 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; logger.info("Got asterisk protocol identifier version " + protocolIdentifier.getValue()); - while (attempts++ < MAX_VERSION_ATTEMPTS) - { - try - { + while (attempts++ < MAX_VERSION_ATTEMPTS) { + try { AsteriskVersion version = determineVersionByCoreSettings(); if (version != null) return version; - } - catch (Exception e) - { + } catch (Exception e) { } - try - { + try { AsteriskVersion version = determineVersionByCoreShowVersion(); if (version != null) return version; - } - catch (Exception e) - { + } catch (Exception e) { } - try - { + try { Thread.sleep(RECONNECTION_VERSION_INTERVAL); - } - catch (Exception ex) - { + } catch (Exception ex) { // ignore } // NOPMD } @@ -686,12 +599,10 @@ protected AsteriskVersion determineVersion() throws IOException, TimeoutExceptio * @return * @throws Exception */ - protected AsteriskVersion determineVersionByCoreSettings() throws Exception - { + protected AsteriskVersion determineVersionByCoreSettings() throws Exception { ManagerResponse response = sendAction(new CoreSettingsAction()); - if (!(response instanceof CoreSettingsResponse)) - { + 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; @@ -708,20 +619,17 @@ protected AsteriskVersion determineVersionByCoreSettings() throws Exception * @return * @throws Exception */ - protected AsteriskVersion determineVersionByCoreShowVersion() throws Exception - { + protected AsteriskVersion determineVersionByCoreShowVersion() throws Exception { final ManagerResponse coreShowVersionResponse = sendAction(new CommandAction(CMD_SHOW_VERSION)); - if (coreShowVersionResponse == null || !(coreShowVersionResponse instanceof CommandResponse)) - { + if (coreShowVersionResponse == null || !(coreShowVersionResponse instanceof CommandResponse)) { // this needs 'command' permissions logger.info("Could not get response for 'core show version'"); return null; } final List coreShowVersionResult = ((CommandResponse) coreShowVersionResponse).getResult(); - if (coreShowVersionResult == null || coreShowVersionResult.isEmpty()) - { + if (coreShowVersionResult == null || coreShowVersionResult.isEmpty()) { logger.warn("Got empty response for 'core show version'"); return null; } @@ -730,96 +638,85 @@ protected AsteriskVersion determineVersionByCoreShowVersion() throws Exception 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 - { + 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.reset(); } public ManagerResponse sendAction(ManagerAction action) - throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException - { + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { return sendAction(action, defaultResponseTimeout); } @@ -829,73 +726,61 @@ public ManagerResponse sendAction(ManagerAction action) * @param timeout - in milliseconds */ public ManagerResponse sendAction(ManagerAction action, long timeout) - throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException - { - ResponseHandlerResult result = new ResponseHandlerResult(); - SendActionCallback callbackHandler = new DefaultSendActionCallback(result); + throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException { - sendAction(action, callbackHandler); + DefaultSendActionCallback callbackHandler = new DefaultSendActionCallback(); + ManagerResponse response = null; + try { + sendAction(action, callbackHandler); - // definitely return null for the response of user events - 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.await(timeout); + // definitely return null for the response of user events + if (action instanceof UserEventAction) { + return null; } - catch (InterruptedException ex) - { + 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 - { + 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))) - { + || 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) - { + 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."); } @@ -903,30 +788,25 @@ 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< ? extends ManagerResponse> responseClass = getExpectedResponseClass(action.getClass()); - if (responseClass != null) - { + Class responseClass = getExpectedResponseClass(action.getClass()); + if (responseClass != null) { reader.expectResponseClass(internalActionId, responseClass); } writer.sendAction(action, internalActionId); } - boolean isShowVersionCommandAction(ManagerAction action) - { + boolean isShowVersionCommandAction(ManagerAction action) { if (action instanceof CoreSettingsAction) return true; - if (action instanceof CommandAction) - { + if (action instanceof CommandAction) { String cmd = ((CommandAction) action).getCommand(); return CMD_SHOW_VERSION.equals(cmd); } @@ -934,11 +814,9 @@ boolean isShowVersionCommandAction(ManagerAction action) return false; } - private Class< ? extends ManagerResponse> getExpectedResponseClass(Class< ? extends ManagerAction> actionClass) - { + private Class getExpectedResponseClass(Class actionClass) { final ExpectedResponse annotation = actionClass.getAnnotation(ExpectedResponse.class); - if (annotation == null) - { + if (annotation == null) { return null; } @@ -946,8 +824,7 @@ boolean isShowVersionCommandAction(ManagerAction action) } public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) - throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException - { + throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException { return sendEventGeneratingAction(action, defaultEventTimeout); } @@ -955,30 +832,23 @@ public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) * Implements synchronous sending of event generating actions. */ public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, long timeout) - throws IOException, EventTimeoutException, IllegalArgumentException, IllegalStateException - { + 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) - { + } 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())) - { + } 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) - { + if (state != CONNECTED) { throw new IllegalStateException( "Actions may only be sent when in state " + "CONNECTED but connection is in state " + state); } @@ -988,58 +858,46 @@ else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClas internalActionId = createInternalActionId(); - try - { + try { // register response handler... - synchronized (this.responseListeners) - { + try (LockCloser closer = this.responseListeners.withLock()) { this.responseListeners.put(internalActionId, responseEventHandler); } // ...and event handler. - synchronized (this.responseEventListeners) - { + try (LockCloser closer = this.responseEventListeners.withLock()) { this.responseEventListeners.put(internalActionId, responseEventHandler); } writer.sendAction(action, internalActionId); // only wait if response has not yet arrived. - if (responseEvents.getResponse() == null || !responseEvents.isComplete()) - { - try - { + if (responseEvents.getResponse() == null || !responseEvents.isComplete()) { + try { responseEvents.await(timeout); - } - catch (InterruptedException e) - { + } 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()) - { + 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 - { + } finally { // remove the event handler - synchronized (this.responseEventListeners) - { + try (LockCloser closer = this.responseEventListeners.withLock()) { this.responseEventListeners.remove(internalActionId); } // 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. - synchronized (this.responseListeners) - { + try (LockCloser closer = this.responseListeners.withLock()) { this.responseListeners.remove(internalActionId); } @@ -1049,46 +907,36 @@ else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClas } public void sendEventGeneratingAction(EventGeneratingAction action, SendEventGeneratingActionCallback callback) - throws IOException, IllegalArgumentException, IllegalStateException - { - if (action == null) - { + throws IOException, IllegalArgumentException, IllegalStateException { + if (action == null) { throw new IllegalArgumentException("Unable to send action: action is null."); - } - else if (action.getActionCompleteEventClass() == 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())) - { + } 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) - { + 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) - { + if (callback != null) { AsyncEventGeneratingResponseHandler responseEventHandler = new AsyncEventGeneratingResponseHandler( action.getActionCompleteEventClass(), callback); // register response handler... - synchronized (this.responseListeners) - { + try (LockCloser closer = this.responseListeners.withLock()) { this.responseListeners.put(internalActionId, responseEventHandler); } // ...and event handler. - synchronized (this.responseEventListeners) - { + try (LockCloser closer = this.responseEventListeners.withLock()) { this.responseEventListeners.put(internalActionId, responseEventHandler); } } @@ -1101,12 +949,11 @@ else if (!ResponseEvent.class.isAssignableFrom(action.getActionCompleteEventClas * 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() - { + private String createInternalActionId() { final StringBuilder sb; sb = new StringBuilder(); @@ -1117,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() - { + public String getProtocolIdentifier() { return protocolIdentifier.getValue(); } - public ManagerConnectionState getState() - { + public ManagerConnectionState getState() { return state; } @@ -1160,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; } @@ -1177,49 +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)); } - if (logger.isDebugEnabled()) - { + 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 - { + } 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); + } } } } @@ -1233,17 +1063,14 @@ 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; } - dispatchLegacyEventIfNeeded(event); - if (logger.isDebugEnabled()) - { + dispatchLegacyEventIfNeeded(event, requiredHandlingTime); + if (logger.isDebugEnabled()) { logger.debug("Dispatching event:\n" + event.toString()); } @@ -1252,36 +1079,33 @@ public void dispatchEvent(ManagerEvent event) // 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 @@ -1291,26 +1115,21 @@ 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. - synchronized (this) - { - if (state == CONNECTED) - { + 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() - { + Thread reconnectThread = new Thread(new Runnable() { - public void run() - { + public void run() { reconnect(); } }); @@ -1323,17 +1142,14 @@ public void run() // (clients) and after that the ManagerReaderThread is gone. // So effectively we replaced the reader thread by a // ReconnectThread. - } - else - { + } 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; @@ -1344,19 +1160,17 @@ 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) - { - if (event instanceof DialBeginEvent) - { + private void dispatchLegacyEventIfNeeded(ManagerEvent event, Integer requiredHandlingTime) { + if (event instanceof DialBeginEvent) { DialEvent legacyEvent = new DialEvent((DialBeginEvent) event); - dispatchEvent(legacyEvent); + dispatchEvent(legacyEvent, requiredHandlingTime); } } @@ -1365,33 +1179,30 @@ private void dispatchLegacyEventIfNeeded(ManagerEvent event) * * @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) - { + private boolean isSupportedProtocolIdentifier(final String identifier) { // Normal version checks - for (String supportedVersion : SUPPORTED_AMI_VERSIONS) - { + for (String supportedVersion : SUPPORTED_AMI_VERSIONS) { String prefix = "Asterisk Call Manager/" + supportedVersion + "."; - if (identifier.startsWith(prefix)) - { + if (identifier.startsWith(prefix)) { return true; } } @@ -1414,18 +1225,13 @@ private boolean isSupportedProtocolIdentifier(final String identifier) * * @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 (identifier == null || !isSupportedProtocolIdentifier(identifier)) - { + if (identifier == null || !isSupportedProtocolIdentifier(identifier)) { logger.warn("Unsupported protocol version '" + identifier + "'. Use at your own risk."); } - protocolIdentifier.setValue(identifier); - protocolIdentifier.countDown(); - } /** @@ -1439,46 +1245,34 @@ private void setProtocolIdentifier(final String identifier) * 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 (true) - { - 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 - { - synchronized (this) - { - if (state != RECONNECTING) - { + try { + try (LockCloser closer = this.withLock()) { + if (state != RECONNECTING) { break; } connect(); - try - { + try { doLogin(defaultResponseTimeout, eventMask); logger.info("Successfully reconnected."); // everything is ok again, so we leave @@ -1486,46 +1280,33 @@ private void reconnect() // no // need to adjust it break; - } - catch (AuthenticationFailedException e1) - { - if (keepAliveAfterAuthenticationFailure) - { + } catch (AuthenticationFailedException e1) { + if (keepAliveAfterAuthenticationFailure) { logger.error("Unable to log in after reconnect: " + e1.getMessage()); - } - else - { + } else { logger.error("Unable to log in after reconnect: " + e1.getMessage() + ". Giving up."); state = DISCONNECTED; } - } - catch (TimeoutException e1) - { + } 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 String message = e.getClass().getSimpleName(); - if (e.getMessage() != null) - { + if (e.getMessage() != null) { message = e.getMessage(); } logger.warn("Exception while trying to reconnect: " + message); - try - { + 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) - { + } catch (InterruptedException e1) { logger.error(e1); } } @@ -1540,12 +1321,10 @@ private void reconnect() * * @param event */ - private void cleanupActionListeners(DisconnectEvent event) - { + private void cleanupActionListeners(DisconnectEvent event) { HashMap oldResponseListeners = null; - synchronized (responseListeners) - { + try (LockCloser closer = responseListeners.withLock()) { // Store remaining response listeners to be notified outside of // synchronized oldResponseListeners = new HashMap(responseListeners); @@ -1553,22 +1332,17 @@ private void cleanupActionListeners(DisconnectEvent event) } // Clear pending responseListeners that will not receive their responses - for (SendActionCallback responseListener : oldResponseListeners.values()) - { + for (SendActionCallback responseListener : oldResponseListeners.values()) { // Allows to unblock waiting sendAction() calls - try - { + try { responseListener.onResponse(null); - } - catch (Exception ex) - { + } catch (Exception ex) { logger.warn("Exception notifying responseListener.onResponse(null)", ex); } } HashMap oldResponseEventListeners = null; - synchronized (responseEventListeners) - { + try (LockCloser closer = responseEventListeners.withLock()) { // Store remaining responseEventListeners to be notified outside of // synchronized oldResponseEventListeners = new HashMap(responseEventListeners); @@ -1577,37 +1351,30 @@ private void cleanupActionListeners(DisconnectEvent event) // Remove those already cleaned up via oldResponseListeners // TODO or should all be notified? - for (String discardedInternalActionId : oldResponseListeners.keySet()) - { + 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 - { + for (ManagerEventListener responseEventListener : oldResponseEventListeners.values()) { + try { // Allows to unblock waiting sendAction() calls responseEventListener.onManagerEvent(event); - } - catch (Exception ex) - { + } catch (Exception ex) { logger.warn("Exception notifying responseListener.onManagerEvent(DisconnectEvent)", ex); } } } - private void cleanup() - { + private void cleanup() { disconnect(); this.readerThread = null; } @Override - public String toString() - { + public String toString() { StringBuilder sb; sb = new StringBuilder("ManagerConnection["); @@ -1624,104 +1391,57 @@ 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; - } - - private void countDown() - { + if (disposed) { + logger.error("Response arrived after Disposal and assumably Timeout " + response + " elapsed: " + + timer.timeTaken() + "(MS)"); + logger.error("" + response.getDateReceived()); + } latch.countDown(); } - /** - * @param millis - milliseconds to wait - * @throws InterruptedException - */ - private void await(long millis) throws InterruptedException - { - latch.await(millis, TimeUnit.MILLISECONDS); + private void dispose() { + disposed = true; } } - /** - * 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; - } - - public void onResponse(ManagerResponse response) - { - // null response happens when connection is lost - if (response != null) - { - result.setResponse(response); - } - result.countDown(); - } - } - /** * 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; + private final Class actionCompleteEventClass; /** * Creates a new instance. * - * @param events the ResponseEventsImpl to store the events in + * @param events the ResponseEventsImpl to store the events in * @param actionCompleteEventClass the type of event that indicates that - * all events have been received + * 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) - { - if (event instanceof DisconnectEvent) - { + 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 @@ -1732,8 +1452,7 @@ public void onManagerEvent(ManagerEvent event) } // should always be a ResponseEvent, anyway... - if (event instanceof ResponseEvent) - { + if (event instanceof ResponseEvent) { ResponseEvent responseEvent; responseEvent = (ResponseEvent) event; @@ -1741,23 +1460,19 @@ public void onManagerEvent(ManagerEvent event) } // finished? - if (actionCompleteEventClass.isAssignableFrom(event.getClass())) - { + if (actionCompleteEventClass.isAssignableFrom(event.getClass())) { events.setComplete(true); // notify if action complete event and response have been // received - if (events.getResponse() != null) - { + if (events.getResponse() != null) { events.countDown(); } } } - public void onResponse(ManagerResponse response) - { + public void onResponse(ManagerResponse response) { // If disconnected - if (response == null) - { + if (response == null) { // Set flag that must not wait for the response events.setComplete(true); // unblock potentially waiting synchronous call to @@ -1768,31 +1483,27 @@ public void onResponse(ManagerResponse response) } events.setRepsonse(response); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { events.setComplete(true); } // finished? // notify if action complete event and response have been // received - if (events.isComplete()) - { + if (events.isComplete()) { events.countDown(); } } } - private class AsyncEventGeneratingResponseHandler implements SendActionCallback, ManagerEventListener - { - private final Class< ? extends ResponseEvent> actionCompleteEventClass; + private class AsyncEventGeneratingResponseHandler implements SendActionCallback, ManagerEventListener { + private final Class actionCompleteEventClass; private final SendEventGeneratingActionCallback callback; private final ResponseEventsImpl events; - public AsyncEventGeneratingResponseHandler(Class< ? extends ResponseEvent> actionCompleteEventClass, - SendEventGeneratingActionCallback callback) - { + public AsyncEventGeneratingResponseHandler(Class actionCompleteEventClass, + SendEventGeneratingActionCallback callback) { this.actionCompleteEventClass = actionCompleteEventClass; this.callback = callback; @@ -1800,29 +1511,24 @@ public AsyncEventGeneratingResponseHandler(Class< ? extends ResponseEvent> actio } @Override - public void onManagerEvent(ManagerEvent event) - { - if (event instanceof DisconnectEvent) - { + public void onManagerEvent(ManagerEvent event) { + if (event instanceof DisconnectEvent) { callback.onResponse(events); return; } // should always be a ResponseEvent, anyway... - if (false == (event instanceof ResponseEvent)) - { + if (false == (event instanceof ResponseEvent)) { return; } ResponseEvent responseEvent = (ResponseEvent) event; events.addEvent(responseEvent); - if (actionCompleteEventClass.isAssignableFrom(event.getClass())) - { + if (actionCompleteEventClass.isAssignableFrom(event.getClass())) { events.setComplete(true); String internalActionId = responseEvent.getInternalActionId(); - synchronized (responseEventListeners) - { + try (LockCloser closer = responseEventListeners.withLock()) { responseEventListeners.remove(internalActionId); } callback.onResponse(events); @@ -1830,24 +1536,20 @@ public void onManagerEvent(ManagerEvent event) } @Override - public void onResponse(ManagerResponse response) - { + public void onResponse(ManagerResponse response) { // If disconnected - if (response == null) - { + if (response == null) { callback.onResponse(events); return; } events.setRepsonse(response); - if (response instanceof ManagerError) - { + if (response instanceof ManagerError) { events.setComplete(true); } // finished? - if (events.isComplete()) - { + if (events.isComplete()) { // invoke callback callback.onResponse(events); } @@ -1855,14 +1557,17 @@ public void onResponse(ManagerResponse response) } @Override - public void deregisterEventClass(Class< ? extends ManagerEvent> eventClass) - { - if (reader == null) - { + 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 4fe566ccd..2b3e46c19 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerReader.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerReader.java @@ -16,12 +16,12 @@ */ 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 @@ -36,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__"; /** @@ -56,9 +55,9 @@ public interface ManagerReader extends Runnable * @see EventBuilder * @see ManagerEvent */ - void registerEventClass(Class< ? extends ManagerEvent> event); + void registerEventClass(Class event); - void expectResponseClass(String internalActionId, Class< ? extends ManagerResponse> responseClass); + void expectResponseClass(String internalActionId, Class responseClass); /** * Terminates this reader. @@ -69,7 +68,7 @@ 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(); @@ -77,9 +76,9 @@ public interface ManagerReader extends Runnable * 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. + * null if not. */ IOException getTerminationException(); - void deregisterEventClass(Class< ? extends ManagerEvent> eventClass); + 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 3535a24d9..c97f268ad 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java @@ -16,32 +16,29 @@ */ package org.asteriskjava.manager.internal; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - +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; import org.asteriskjava.util.SocketConnectionFacade; +import java.io.IOException; +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. */ @@ -59,12 +56,7 @@ public class ManagerReaderImpl implements ManagerReader */ private final ResponseBuilder responseBuilder; - /** - * The dispatcher to use for dispatching events and responses. - */ - private final Dispatcher dispatcher; - - private final Map> expectedResponseClasses; + private final Map> expectedResponseClasses; /** * The source to use when creating {@link ManagerEvent}s. @@ -97,16 +89,17 @@ public class ManagerReaderImpl implements ManagerReader */ BackwardsCompatibilityForManagerEvents compatibility = new BackwardsCompatibilityForManagerEvents(); + private final Dispatcher rawDispatcher; + /** * Creates a new ManagerReaderImpl. * * @param dispatcher the dispatcher to use for dispatching events and - * responses. - * @param source the source to use when creating {@link ManagerEvent}s + * 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(); @@ -119,18 +112,15 @@ 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< ? extends ManagerEvent> eventClass) - { + public void registerEventClass(Class eventClass) { eventBuilder.registerEventClass(eventClass); } - public void expectResponseClass(String internalActionId, Class< ? extends ManagerResponse> responseClass) - { + public void expectResponseClass(String internalActionId, Class responseClass) { expectedResponseClasses.put(internalActionId, responseClass); } @@ -141,39 +131,39 @@ public void expectResponseClass(String internalActionId, Class< ? extends Manage * 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() - { + 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) - { + 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/")) - { + || 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; } @@ -182,36 +172,21 @@ public void run() * 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) - { - // begin of workaround for Astersik bug 13319 - // see AJ-77 - // Use this workaround only when line starts from "From " - // and "To " - int isFromAtStart = line.indexOf("From "); - int isToAtStart = line.indexOf("To "); - - int delimiterIndex = isFromAtStart == 0 || isToAtStart == 0 - ? line.indexOf(" ") : line.indexOf(":"); - // end of workaround for Astersik bug 13319 - - int delimiterLength = 1; - - if (delimiterIndex > 0 && line.length() > delimiterIndex + delimiterLength) - { - String name = line.substring(0, delimiterIndex).toLowerCase(Locale.ENGLISH).trim(); - String value = line.substring(delimiterIndex + delimiterLength).trim(); - - 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 + "]"); + } } } @@ -219,17 +194,17 @@ public void run() // we build // the corresponding value object and dispatch it through the // ManagerConnection. - if (line.length() == 0) - { - if (buffer.containsKey("event")) - { + 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")); ManagerEvent event = buildEvent(source, buffer); - if (event != null) - { - dispatcher.dispatchEvent(event); + if (event != null) { + cause = event; + dispatcher.dispatchEvent(event, null); // Backwards compatibility for bridge events. // Asterisk 13 uses BridgeCreate, @@ -239,131 +214,145 @@ public void run() // BridgeEvent's for them allowing legacy code to // still work with BridgeEvent's ManagerEvent secondaryEvent = compatibility.handleEvent(event); - if (secondaryEvent != null) - { - dispatcher.dispatchEvent(secondaryEvent); + if (secondaryEvent != null) { + dispatcher.dispatchEvent(secondaryEvent, null); } - } - else - { + } 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); + if (response != null) { + cause = response; + dispatcher.dispatchResponse(response, null); } - } - else - { - if (!buffer.isEmpty()) - { + } 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) - { + 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) - { + 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) - { - Class< ? extends ManagerResponse> responseClass = null; + private ManagerResponse buildResponse(Map buffer) { + Class responseClass = null; final String actionId = (String) buffer.get("actionid"); final String internalActionId = ManagerUtil.getInternalActionId(actionId); - if (internalActionId != null) - { + 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()); } @@ -371,8 +360,7 @@ private ManagerEvent buildEvent(Object source, Map buffer) } @Override - public void deregisterEventClass(Class< ? extends ManagerEvent> eventClass) - { + 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 2ddf18d9f..545b9f18a 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerUtil.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerUtil.java @@ -25,37 +25,34 @@ * 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 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]); } @@ -64,24 +61,21 @@ 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. + * 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); } return null; @@ -89,22 +83,19 @@ public static String getInternalActionId(String actionId) /** * 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. + * 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); } return null; @@ -114,16 +105,14 @@ public static String stripInternalActionId(String actionId) /** * 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; } 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 8e0a0bc28..94d844870 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ManagerWriter.java +++ b/src/main/java/org/asteriskjava/manager/internal/ManagerWriter.java @@ -16,28 +16,27 @@ */ 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 targetVersion the version of the target Asterisk server. * @since 0.2 */ @@ -45,15 +44,15 @@ public interface ManagerWriter /** * 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 index 74c1d6d9d..4f9f5b09a 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ProtocolIdentifierWrapper.java +++ b/src/main/java/org/asteriskjava/manager/internal/ProtocolIdentifierWrapper.java @@ -3,35 +3,26 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -class ProtocolIdentifierWrapper -{ - private CountDownLatch latch = new CountDownLatch(1); +class ProtocolIdentifierWrapper { + private volatile CountDownLatch latch = new CountDownLatch(1); private String value; - void reset() - { + void reset() { value = null; latch = new CountDownLatch(1); } - void await(long timeout) throws InterruptedException - { - latch.await(timeout, TimeUnit.MILLISECONDS); + boolean await(long timeout) throws InterruptedException { + return latch.await(timeout, TimeUnit.MILLISECONDS); } - String getValue() - { + String getValue() { return value; } - void countDown() - { - latch.countDown(); - } - - public void setValue(String identifier) - { + 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 223210165..c0a0b9371 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ResponseBuilderImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ResponseBuilderImpl.java @@ -1,45 +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.manager.internal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - 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 -{ +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)); + "attributes", "proxyresponse", ManagerReader.COMMAND_RESULT_RESPONSE_KEY)); private static final String RESPONSE_KEY = "response"; private static final String PROXY_RESPONSE_KEY = "proxyresponse"; @@ -47,65 +43,52 @@ class ResponseBuilderImpl extends AbstractBuilder implements ResponseBuilder private static final String OUTPUT_RESPONSE_KEY = "output"; //Asterisk 14.3.0 @SuppressWarnings("unchecked") - public ManagerResponse buildResponse(Class responseClass, Map attributes) - { + 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 - { + } else { + try { response = responseClass.getDeclaredConstructor().newInstance(); - } - catch (Exception ex) - { + } 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 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); - } - } + 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)); } diff --git a/src/main/java/org/asteriskjava/manager/internal/ResponseEventsImpl.java b/src/main/java/org/asteriskjava/manager/internal/ResponseEventsImpl.java index 664b64547..7507f7598 100644 --- a/src/main/java/org/asteriskjava/manager/internal/ResponseEventsImpl.java +++ b/src/main/java/org/asteriskjava/manager/internal/ResponseEventsImpl.java @@ -16,52 +16,49 @@ */ package org.asteriskjava.manager.internal; +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; -import org.asteriskjava.manager.ResponseEvents; -import org.asteriskjava.manager.event.ResponseEvent; -import org.asteriskjava.manager.response.ManagerResponse; - /** * 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; } @@ -69,55 +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 void await(long timeout) throws InterruptedException - { - latch.await(timeout, TimeUnit.MILLISECONDS); + public boolean await(long timeout) throws InterruptedException { + return latch.await(timeout, TimeUnit.MILLISECONDS); } - public void countDown() - { + public void countDown() { latch.countDown(); } @Override - public String toString() - { + 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 index 32d6c4fcd..51d6b3a15 100644 --- a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/BackwardsCompatibilityForManagerEvents.java +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/BackwardsCompatibilityForManagerEvents.java @@ -4,17 +4,14 @@ import org.asteriskjava.manager.internal.backwardsCompatibility.bridge.BridgesActive; import org.asteriskjava.manager.internal.backwardsCompatibility.meetme.MeetmeCompatibility; -public class BackwardsCompatibilityForManagerEvents -{ +public class BackwardsCompatibilityForManagerEvents { // Logger logger = LogManager.getLogger(); BridgesActive bridges = new BridgesActive(); MeetmeCompatibility meetme = new MeetmeCompatibility(); - public ManagerEvent handleEvent(ManagerEvent event) - { + public ManagerEvent handleEvent(ManagerEvent event) { ManagerEvent newEvent = bridges.handleEvent(event); - if (newEvent == null) - { + 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 index b104e2344..cd4ca0c36 100644 --- a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparator.java +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparator.java @@ -22,21 +22,18 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -public class BridgeEnterEventComparator implements Comparator -{ +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) - { + 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) - { + if (find1 && find2) { // 1501234567.890 -> epochtime: 1501234567 | serial: 890 long epochtime1 = Long.valueOf(uniqueId1Matcher.group(1)); long epochtime2 = Long.valueOf(uniqueId2Matcher.group(1)); @@ -44,14 +41,10 @@ public int compare(BridgeEnterEvent o1, BridgeEnterEvent o2) int serial2 = Integer.valueOf(uniqueId2Matcher.group(2)); return epochtime1 == epochtime2 ? Integer.compare(serial1, serial2) : Long.compare(epochtime1, epochtime2); - } - else if (!find1 && !find2) - { + } else if (!find1 && !find2) { // Both of inputs are invalid value: id1 == id2 return 0; - } - else - { + } 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 index edb572117..cc6d071c1 100644 --- a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeState.java +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeState.java @@ -1,19 +1,14 @@ package org.asteriskjava.manager.internal.backwardsCompatibility.bridge; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - +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.Log; -import org.asteriskjava.util.LogFactory; +import org.asteriskjava.util.DateUtil; + +import java.util.*; /** * Track the current members of a bridge, emmitting BridgeEvents when 2 members @@ -21,19 +16,16 @@ * * @author rsutton */ -class BridgeState -{ - private final Log logger = LogFactory.getLog(getClass()); +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 Map members = new HashMap<>(); + private final LockableMap members = new LockableMap<>(new HashMap<>()); - ManagerEvent destroy() - { - synchronized (members) - { + ManagerEvent destroy() { + try (LockCloser closer = members.withLock()) { members.clear(); } return null; @@ -45,8 +37,7 @@ ManagerEvent destroy() * @param event * @return */ - ManagerEvent addMember(BridgeEnterEvent event) - { + ManagerEvent addMember(BridgeEnterEvent event) { List remaining = null; if (HOLDING_BRIDGE_TECH.equals(event.getBridgeTechnology())) { @@ -54,24 +45,22 @@ ManagerEvent addMember(BridgeEnterEvent event) return null; } - synchronized (members) - { - if (members.put(event.getChannel(), event) == null && members.size() == 2) - { + try (LockCloser closer = members.withLock()) { + if (members.put(event.getChannel(), event) == null && members.size() == 2) { remaining = new ArrayList<>(members.values()); } } - if (remaining == null) - { + if (remaining == null) { return null; } - logger.info("Members size " + remaining.size() + " " + event); + // logger.info("Members size " + remaining.size() + " " + event); BridgeEvent bridgeEvent = buildBridgeEvent(BridgeEvent.BRIDGE_STATE_LINK, remaining); - logger.info("Bridge " + bridgeEvent.getChannel1() + " " + bridgeEvent.getChannel2()); + // logger.info("Bridge " + bridgeEvent.getChannel1() + " " + + // bridgeEvent.getChannel2()); return bridgeEvent; } @@ -83,8 +72,7 @@ ManagerEvent addMember(BridgeEnterEvent event) * @return */ - ManagerEvent removeMember(BridgeLeaveEvent event) - { + ManagerEvent removeMember(BridgeLeaveEvent event) { List remaining = new LinkedList<>(); if (HOLDING_BRIDGE_TECH.equals(event.getBridgeTechnology())) { @@ -92,14 +80,11 @@ ManagerEvent removeMember(BridgeLeaveEvent event) return null; } - synchronized (members) - { + try (LockCloser closer = members.withLock()) { remaining.addAll(members.values()); - if (members.remove(event.getChannel()) != null) - { - if (remaining.size() == 2) - { + if (members.remove(event.getChannel()) != null) { + if (remaining.size() == 2) { return buildBridgeEvent(BridgeEvent.BRIDGE_STATE_UNLINK, remaining); } } @@ -112,8 +97,7 @@ ManagerEvent removeMember(BridgeLeaveEvent event) } - private BridgeEvent buildBridgeEvent(String bridgeState, List members) - { + private BridgeEvent buildBridgeEvent(String bridgeState, List members) { Collections.sort(members, BRIDGE_ENTER_EVENT_COMPARATOR); BridgeEvent bridgeEvent = new BridgeEvent(this); @@ -127,7 +111,7 @@ private BridgeEvent buildBridgeEvent(String bridgeState, List bridgeEvent.setChannel2(members.get(1).getChannel()); bridgeEvent.setBridgeState(bridgeState); - bridgeEvent.setDateReceived(new Date()); + 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 index 55e675c42..d91f9cba5 100644 --- a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgesActive.java +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgesActive.java @@ -1,16 +1,12 @@ package org.asteriskjava.manager.internal.backwardsCompatibility.bridge; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.asteriskjava.manager.event.BridgeCreateEvent; -import org.asteriskjava.manager.event.BridgeDestroyEvent; -import org.asteriskjava.manager.event.BridgeEnterEvent; -import org.asteriskjava.manager.event.BridgeLeaveEvent; -import org.asteriskjava.manager.event.ManagerEvent; +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.
    *
    @@ -19,69 +15,53 @@ *
    * 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 -{ +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) - { + public ManagerEvent handleEvent(ManagerEvent event) { + if (event instanceof BridgeCreateEvent) { return createBridge((BridgeCreateEvent) event); - } - else if (event instanceof BridgeDestroyEvent) - { + } else if (event instanceof BridgeDestroyEvent) { return destroyBridge((BridgeDestroyEvent) event); - } - else if (event instanceof BridgeEnterEvent) - { + } else if (event instanceof BridgeEnterEvent) { return enterBridge((BridgeEnterEvent) event); - } - else if (event instanceof BridgeLeaveEvent) - { + } else if (event instanceof BridgeLeaveEvent) { return leaveBridge((BridgeLeaveEvent) event); } return null; } - ManagerEvent createBridge(BridgeCreateEvent event) - { + ManagerEvent createBridge(BridgeCreateEvent event) { activeBridges.putIfAbsent(event.getBridgeUniqueId(), new BridgeState()); return null; } - ManagerEvent destroyBridge(BridgeDestroyEvent event) - { + ManagerEvent destroyBridge(BridgeDestroyEvent event) { BridgeState state = activeBridges.remove(event.getBridgeUniqueId()); - if (state != null) - { + if (state != null) { return state.destroy(); } logger.info("Cant find bridge for id " + event.getBridgeUniqueId()); return null; } - ManagerEvent enterBridge(BridgeEnterEvent event) - { + ManagerEvent enterBridge(BridgeEnterEvent event) { BridgeState state = activeBridges.get(event.getBridgeUniqueId()); - if (state != null) - { + if (state != null) { return state.addMember(event); } logger.error("Cant find bridge for id " + event.getBridgeUniqueId()); return null; } - ManagerEvent leaveBridge(BridgeLeaveEvent event) - { + ManagerEvent leaveBridge(BridgeLeaveEvent event) { BridgeState state = activeBridges.get(event.getBridgeUniqueId()); - if (state != null) - { + if (state != null) { return state.removeMember(event); } logger.info("Cant find bridge for id " + event.getBridgeUniqueId()); 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 index 51fd9096c..3aea7b3af 100644 --- a/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/meetme/MeetmeCompatibility.java +++ b/src/main/java/org/asteriskjava/manager/internal/backwardsCompatibility/meetme/MeetmeCompatibility.java @@ -1,15 +1,6 @@ package org.asteriskjava.manager.internal.backwardsCompatibility.meetme; -import java.util.Date; - -import org.asteriskjava.manager.event.ConfbridgeEndEvent; -import org.asteriskjava.manager.event.ConfbridgeJoinEvent; -import org.asteriskjava.manager.event.ConfbridgeLeaveEvent; -import org.asteriskjava.manager.event.ConfbridgeStartEvent; -import org.asteriskjava.manager.event.ManagerEvent; -import org.asteriskjava.manager.event.MeetMeEndEvent; -import org.asteriskjava.manager.event.MeetMeJoinEvent; -import org.asteriskjava.manager.event.MeetMeLeaveEvent; +import org.asteriskjava.manager.event.*; /** * Backwards compatibility for bridge events.
    @@ -19,47 +10,36 @@ *
    * 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 class MeetmeCompatibility { - public ManagerEvent handleEvent(ManagerEvent event) - { - if (event instanceof ConfbridgeStartEvent) - { - } - else if (event instanceof ConfbridgeEndEvent) - { + public ManagerEvent handleEvent(ManagerEvent event) { + if (event instanceof ConfbridgeStartEvent) { + } else if (event instanceof ConfbridgeEndEvent) { MeetMeEndEvent endEvent = new MeetMeEndEvent(this); - endEvent.setDateReceived(new Date()); + endEvent.setDateReceived(event.getDateReceived()); endEvent.setMeetMe(((ConfbridgeEndEvent) event).getConference()); return endEvent; - } - else - - if (event instanceof ConfbridgeJoinEvent) - { + } 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(new Date()); + joinEvent.setDateReceived(event.getDateReceived()); return joinEvent; - } - else if (event instanceof ConfbridgeLeaveEvent) - { + } 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(new Date()); + leaveEvent.setDateReceived(event.getDateReceived()); return leaveEvent; } 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/.gitignore b/src/main/java/org/asteriskjava/manager/response/.gitignore deleted file mode 100644 index 4b0f455d7..000000000 --- a/src/main/java/org/asteriskjava/manager/response/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -/ChallengeResponse.class -/CommandResponse.class -/CoreSettingsResponse.class -/CoreStatusResponse.class -/ExtensionStateResponse.class -/GetConfigResponse.class -/GetVarResponse.class -/MailboxCountResponse.class -/MailboxStatusResponse.class -/ManagerError.class -/ManagerResponse.class -/ModuleCheckResponse.class -/PingResponse.class -/SipShowPeerResponse.class -/SkypeBuddyResponse.class -/SkypeLicenseStatusResponse.class 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 086cf9635..e9afcb964 100644 --- a/src/main/java/org/asteriskjava/manager/response/ExtensionStateResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/ExtensionStateResponse.java @@ -17,90 +17,77 @@ 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 -{ - private static final long serialVersionUID = -2044248427247227390L; - private String exten; - private String context; - private String hint; - private Integer status; - private String statusText; +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() - { - return exten; - } + public String getExten() { + return exten; + } - public void setExten(String exten) - { - this.exten = exten; - } + public void setExten(String exten) { + this.exten = exten; + } - public String getContext() - { - return context; - } + public String getContext() { + return context; + } - public void setContext(String context) - { - this.context = context; - } + public void setContext(String context) { + this.context = context; + } - public String getHint() - { - return hint; - } + public String getHint() { + return hint; + } - public void setHint(String hint) - { - this.hint = hint; - } + public void setHint(String hint) { + this.hint = hint; + } - public Integer getStatus() - { - return status; - } + public Integer getStatus() { + return status; + } - public void setStatus(Integer status) - { - this.status = status; - } + public void setStatus(Integer status) { + this.status = status; + } - public String getStatusText() - { - return statusText; - } + public String getStatusText() { + return statusText; + } - public void setStatusText(String statusText) - { - this.statusText = statusText; - } + public void setStatusText(String statusText) { + this.statusText = statusText; + } - - - @Override - public String toString() - { - StringBuilder sb; - sb = new StringBuilder(getClass().getName() + ": "); - sb.append("actionId='").append(getActionId()).append("'; "); - sb.append("message='").append(getMessage()).append("'; "); - sb.append("response='").append(getResponse()).append("'; "); - sb.append("uniqueId='").append(getUniqueId()).append("'; "); - sb.append("exten='").append(getExten()).append("'; "); - 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)); + @Override + public String toString() { + StringBuilder sb; - return sb.toString(); - } + sb = new StringBuilder(getClass().getName() + ": "); + sb.append("actionId='").append(getActionId()).append("'; "); + sb.append("message='").append(getMessage()).append("'; "); + sb.append("response='").append(getResponse()).append("'; "); + sb.append("uniqueId='").append(getUniqueId()).append("'; "); + sb.append("exten='").append(getExten()).append("'; "); + 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 7ed95d4d5..0c1f20b26 100644 --- a/src/main/java/org/asteriskjava/manager/response/GetConfigResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/GetConfigResponse.java @@ -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) - { + public Map getCategories() { + if (categories == null) { categories = new TreeMap<>(); } Map responseMap = super.getAttributes(); - for (Entry response : responseMap.entrySet()) - { + for (Entry response : responseMap.entrySet()) { String key = response.getKey(); - if (key.toLowerCase(Locale.US).contains("category")) - { + if (key.toLowerCase(Locale.ENGLISH).contains("category")) { String[] keyParts = key.split("-"); // if it doesn't have at least category-XXXXXX, skip @@ -68,12 +63,9 @@ 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; } @@ -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) - { + public Map getLines(int categoryNumber) { + if (lines == null) { lines = new TreeMap<>(); } Map responseMap = super.getAttributes(); - for (Entry response : responseMap.entrySet()) - { + for (Entry response : responseMap.entrySet()) { String key = response.getKey(); - if (key.toLowerCase(Locale.US).contains("line")) - { + 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) - { + if (linesForCategory == null) { linesForCategory = new TreeMap<>(); } // put the line we just parsed into the line map for this category linesForCategory.put(potentialLineNumber, (String) response.getValue()); - if (!lines.containsKey(potentialCategoryNumber)) - { + 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 75fb7650f..cb8e5c53c 100644 --- a/src/main/java/org/asteriskjava/manager/response/ManagerResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/ManagerResponse.java @@ -33,8 +33,7 @@ * @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; @@ -53,8 +52,7 @@ public class ManagerResponse implements Serializable private Map attributes; private String output; - public ManagerResponse() - { + public ManagerResponse() { this.attributes = null; } @@ -65,8 +63,7 @@ public ManagerResponse() * * @see #getAttribute(String) */ - public Map getAttributes() - { + public Map getAttributes() { return attributes; } @@ -74,10 +71,9 @@ public Map getAttributes() * Sets the Map with all attributes. * * @param attributes Map with containing the attributes with all lower case - * keys. + * keys. */ - public void setAttributes(Map attributes) - { + public void setAttributes(Map attributes) { this.attributes = attributes; } @@ -100,16 +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)); } @@ -117,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; } @@ -126,8 +120,7 @@ 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; } @@ -137,11 +130,10 @@ public void setDateReceived(Date dateReceived) * 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; } @@ -151,12 +143,11 @@ public String getActionId() * 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. + * 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; } @@ -165,11 +156,10 @@ public final String getServer() * received. * * @param server the name of the Asterisk server from which this response - * has been received. + * has been received. * @since 1.0.0 */ - public final void setServer(String server) - { + public final void setServer(String server) { this.server = server; } @@ -179,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; } @@ -190,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; } @@ -199,10 +187,9 @@ public void setEventList(String eventList) * Sets the action id of the ManagerAction that caused this response. * * @param actionId the action id of the ManagerAction that caused this - * response. + * response. */ - public void setActionId(String actionId) - { + public void setActionId(String actionId) { this.actionId = actionId; } @@ -210,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; } @@ -228,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; } @@ -246,43 +229,35 @@ 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()); } @@ -290,8 +265,7 @@ protected Long stringToLong(String s, String suffix) throws NumberFormatExceptio } @Override - public String toString() - { + public String toString() { StringBuilder sb; sb = new StringBuilder(100); @@ -305,21 +279,19 @@ public String toString() return sb.toString(); } - public String getEvents() - { + public String getEvents() { return events; } - public void setEvents(String events) - { + public void setEvents(String events) { this.events = events; } - public String getOutput() { - return output; - } + public String getOutput() { + return output; + } - public void setOutput(String output) { - this.output = 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 index 77609965f..ab8d3997f 100644 --- a/src/main/java/org/asteriskjava/manager/response/MixMonitorResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/MixMonitorResponse.java @@ -19,13 +19,12 @@ /** * 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 -{ +public class MixMonitorResponse extends ManagerResponse { private static final long serialVersionUID = 1L; private String mixMonitorId; @@ -34,8 +33,7 @@ public class MixMonitorResponse extends ManagerResponse * * @return the MixMonitor ID */ - public String getMixMonitorId() - { + public String getMixMonitorId() { return mixMonitorId; } @@ -44,8 +42,7 @@ public String getMixMonitorId() * * @param mixMonitorId the MixMonitor ID */ - public void setMixMonitorId(String mixMonitorId) - { + 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 ce03aa160..f131a5865 100644 --- a/src/main/java/org/asteriskjava/manager/response/ModuleCheckResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/ModuleCheckResponse.java @@ -24,8 +24,7 @@ * @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 String version; @@ -35,13 +34,11 @@ public class ModuleCheckResponse extends ManagerResponse * * @return the version (svn revision) of the module. */ - public String getVersion() - { + public String getVersion() { return version; } - public void setVersion(String 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 38a8a3f96..aee7a35b0 100644 --- a/src/main/java/org/asteriskjava/manager/response/PingResponse.java +++ b/src/main/java/org/asteriskjava/manager/response/PingResponse.java @@ -22,40 +22,36 @@ * @author srt * @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; } /** * Timestamp for the response. + * * @return Timestamp as a String, e.g 1353747825.795863 * @since 1.0.0 */ - public String getTimestamp() - { + public String getTimestamp() { return timestamp; } - public void setTimestamp(String 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 cab680b14..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; @@ -78,681 +92,595 @@ public class SipShowPeerResponse extends ManagerResponse 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() - { + 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() - { + public Boolean getRemoteSecretExist() { return remoteSecretExist; } - public void setRemoteSecretExist(Boolean 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() - { + public Boolean getSipT38support() { return sipT38support; } - public void setSipT38support(Boolean sipT38support) - { + public void setSipT38support(Boolean sipT38support) { this.sipT38support = sipT38support; } - public String getSipT38ec() - { + public String getSipT38ec() { return sipT38ec; } - public void setSipT38ec(String sipT38ec) - { + public void setSipT38ec(String sipT38ec) { this.sipT38ec = sipT38ec; } - public Long getSipT38MaxDtgrm() - { + public Long getSipT38MaxDtgrm() { return sipT38MaxDtgrm; } - public void setSipT38MaxDtgrm(Long 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) - { + if (sipT38MaxDtgrm == 4294967295L) { this.sipT38MaxDtgrm = -1L; - } - else - { - if (sipT38MaxDtgrm < Integer.MAX_VALUE && sipT38MaxDtgrm > Integer.MIN_VALUE) - { + } else { + if (sipT38MaxDtgrm < Integer.MAX_VALUE && sipT38MaxDtgrm > Integer.MIN_VALUE) { this.sipT38MaxDtgrm = sipT38MaxDtgrm; } } } - public Boolean getSipDirectMedia() - { + public Boolean getSipDirectMedia() { return sipDirectMedia; } - public void setSipDirectMedia(Boolean sipDirectMedia) - { + public void setSipDirectMedia(Boolean sipDirectMedia) { this.sipDirectMedia = sipDirectMedia; } - public Boolean getSipCanReinvite() - { + 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() - { + public String getParkingLot() { return parkingLot; } - public void setParkingLot(String 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() - { + public Map getChanVariable() { return chanVariable; } - public void setChanVariable(final Map chanVariable) - { + public void setChanVariable(final Map chanVariable) { this.chanVariable = chanVariable; } - public Integer getMaxForwards() - { + public Integer getMaxForwards() { return maxForwards; } - public void setMaxForwards(Integer maxForwards) - { + public void setMaxForwards(Integer maxForwards) { this.maxForwards = maxForwards; } - public String getToneZone() - { + public String getToneZone() { return toneZone; } - public void setToneZone(String toneZone) - { + public void setToneZone(String toneZone) { this.toneZone = toneZone; } - public String getSipUseReasonHeader() - { + public String getSipUseReasonHeader() { return sipUseReasonHeader; } - public void setSipUseReasonHeader(String sipUseReasonHeader) - { + public void setSipUseReasonHeader(String sipUseReasonHeader) { this.sipUseReasonHeader = sipUseReasonHeader; } - public String getSipEncryption() - { + public String getSipEncryption() { return sipEncryption; } - public void setSipEncryption(String sipEncryption) - { + public void setSipEncryption(String sipEncryption) { this.sipEncryption = sipEncryption; } - public String getSipForcerport() - { + public String getSipForcerport() { return sipForcerport; } - public void setSipForcerport(String sipForcerport) - { + public void setSipForcerport(String sipForcerport) { this.sipForcerport = sipForcerport; } - public String getSipRtpEngine() - { + public String getSipRtpEngine() { return sipRtpEngine; } - public void setSipRtpEngine(String sipRtpEngine) - { + public void setSipRtpEngine(String sipRtpEngine) { this.sipRtpEngine = sipRtpEngine; } - public String getSipComedia() - { + public String getSipComedia() { return sipComedia; } - public void setSipComedia(String sipComedia) - { + public void setSipComedia(String sipComedia) { this.sipComedia = sipComedia; } - public String getMohsuggest() - { + public String getMohsuggest() { return mohsuggest; } - public void setMohsuggest(String 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() - { + public String toString() { StringBuilder builder = new StringBuilder(); builder.append("SipShowPeerResponse [channelType="); builder.append(channelType); @@ -882,6 +810,16 @@ public String toString() 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(); } 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 index 393dc2992..eb6c612e0 100644 --- a/src/main/java/org/asteriskjava/pbx/Activity.java +++ b/src/main/java/org/asteriskjava/pbx/Activity.java @@ -1,21 +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(); +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(); + /** + * 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 index de6627fbc..5d607d79c 100644 --- a/src/main/java/org/asteriskjava/pbx/ActivityCallback.java +++ b/src/main/java/org/asteriskjava/pbx/ActivityCallback.java @@ -5,17 +5,16 @@ * of any of the async methods provided by iPBX. */ -public interface ActivityCallback -{ +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 status TODO * @param message */ diff --git a/src/main/java/org/asteriskjava/pbx/ActivityStatusEnum.java b/src/main/java/org/asteriskjava/pbx/ActivityStatusEnum.java index c4af0a31a..5bee17987 100644 --- a/src/main/java/org/asteriskjava/pbx/ActivityStatusEnum.java +++ b/src/main/java/org/asteriskjava/pbx/ActivityStatusEnum.java @@ -1,18 +1,15 @@ package org.asteriskjava.pbx; -public enum ActivityStatusEnum -{ +public enum ActivityStatusEnum { START("Starting"), PROGRESS("Progress"), SUCCESS("Success"), FAILURE("Failure"); String defaultMessage; - ActivityStatusEnum(String defaultMessage) - { + ActivityStatusEnum(String defaultMessage) { this.defaultMessage = defaultMessage; } - public String getDefaultMessage() - { + 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 index 8e150d008..1b56632cb 100644 --- a/src/main/java/org/asteriskjava/pbx/AgiChannelActivityAction.java +++ b/src/main/java/org/asteriskjava/pbx/AgiChannelActivityAction.java @@ -2,14 +2,14 @@ import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; +import org.asteriskjava.pbx.agi.ActivityAgi; -public interface AgiChannelActivityAction -{ +public interface AgiChannelActivityAction { - void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException; + void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException; - boolean isDisconnect(); + boolean isDisconnect(ActivityAgi activityAgi); - void cancel(); + void cancel(); } diff --git a/src/main/java/org/asteriskjava/pbx/AsteriskSettings.java b/src/main/java/org/asteriskjava/pbx/AsteriskSettings.java index 9ae400bd0..6a2f5194a 100644 --- a/src/main/java/org/asteriskjava/pbx/AsteriskSettings.java +++ b/src/main/java/org/asteriskjava/pbx/AsteriskSettings.java @@ -1,19 +1,18 @@ package org.asteriskjava.pbx; -public interface AsteriskSettings -{ +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(); @@ -21,14 +20,14 @@ public interface AsteriskSettings /** * 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(); @@ -39,7 +38,7 @@ public interface AsteriskSettings * 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(); @@ -48,7 +47,7 @@ public interface AsteriskSettings * 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(); @@ -57,7 +56,7 @@ public interface AsteriskSettings * 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(); @@ -72,7 +71,7 @@ public interface AsteriskSettings /** * The time (in seconds) to wait for a dial attempt to be answered before * giving up. Recommend a value of 30. - * + * * @return */ int getDialTimeout(); @@ -80,7 +79,7 @@ public interface AsteriskSettings /** * 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(); @@ -90,7 +89,7 @@ public interface AsteriskSettings * 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(); @@ -98,7 +97,7 @@ public interface AsteriskSettings /** * 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(); @@ -107,6 +106,7 @@ public interface AsteriskSettings * 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 index 71a7d678f..a7055a92e 100644 --- a/src/main/java/org/asteriskjava/pbx/Call.java +++ b/src/main/java/org/asteriskjava/pbx/Call.java @@ -3,8 +3,7 @@ import java.util.Date; import java.util.List; -public interface Call -{ +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 @@ -12,12 +11,11 @@ public interface Call * 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 - { + enum OperandChannel { /** * this party received (did not originate) the call */ @@ -65,7 +63,7 @@ enum OperandChannel /** * retrieves the channel associated with the give Operand. - * + * * @param lhs * @return */ @@ -75,7 +73,7 @@ enum OperandChannel * 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(); @@ -84,13 +82,14 @@ enum OperandChannel * 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(); @@ -99,12 +98,14 @@ enum OperandChannel * 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 index ac3f8a717..b055de7c4 100644 --- a/src/main/java/org/asteriskjava/pbx/CallDirection.java +++ b/src/main/java/org/asteriskjava/pbx/CallDirection.java @@ -2,11 +2,10 @@ /** * Describes the direction of the call. - * + * * @author bsutton */ -public enum CallDirection -{ +public enum CallDirection { /** * INBOUND - call */ @@ -33,19 +32,15 @@ public enum CallDirection private final int dbValue; - CallDirection(final int dbValue) - { + CallDirection(final int dbValue) { this.dbValue = dbValue; } - public static CallDirection valueOf(final int dbValue) - { + public static CallDirection valueOf(final int dbValue) { CallDirection result = null; - for (final CallDirection direction : CallDirection.values()) - { - if (direction.dbValue == dbValue) - { + for (final CallDirection direction : CallDirection.values()) { + if (direction.dbValue == dbValue) { result = direction; break; } diff --git a/src/main/java/org/asteriskjava/pbx/CallHangupListener.java b/src/main/java/org/asteriskjava/pbx/CallHangupListener.java index e0dcb79a2..92d33af3d 100644 --- a/src/main/java/org/asteriskjava/pbx/CallHangupListener.java +++ b/src/main/java/org/asteriskjava/pbx/CallHangupListener.java @@ -1,8 +1,7 @@ package org.asteriskjava.pbx; -public interface CallHangupListener -{ +public interface CallHangupListener { - void callHungup(Call call); + void callHungup(Call call); } diff --git a/src/main/java/org/asteriskjava/pbx/CallImpl.java b/src/main/java/org/asteriskjava/pbx/CallImpl.java index 9596b11f6..8073c6576 100644 --- a/src/main/java/org/asteriskjava/pbx/CallImpl.java +++ b/src/main/java/org/asteriskjava/pbx/CallImpl.java @@ -1,15 +1,16 @@ 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; -import org.asteriskjava.pbx.activities.BlindTransferActivity; -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; - /** * 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 @@ -21,12 +22,11 @@ * 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 -{ +public class CallImpl implements ChannelHangupListener, Call { private static final Log logger = LogFactory.getLog(CallImpl.class); /** @@ -43,8 +43,7 @@ public class CallImpl implements ChannelHangupListener, Call /* * transfer types */ - public enum TransferType - { + public enum TransferType { NONE, ASSISTED, BLIND } @@ -99,7 +98,7 @@ public enum TransferType /** * The primary key for the Contact record. - * + * * @return */ private Integer _contactId; @@ -114,11 +113,10 @@ public enum TransferType * 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 - { + public enum OWNER { SELF } @@ -126,35 +124,32 @@ public enum OWNER protected BlindTransferActivity _transferActivity; - public CallImpl(Channel originatingChannel, CallDirection direction) throws PBXException - { + 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 = new Date(); + this._callStarted = DateUtil.getDate(); this.setOriginatingParty(originatingChannel); } - public CallImpl(Channel originatingChannel, Channel acceptingChannel, CallDirection direction) throws PBXException - { + 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 = new Date(); + this._callStarted = DateUtil.getDate(); this.setOriginatingParty(originatingChannel); this.setAcceptingParty(acceptingChannel); } - public CallImpl(Channel agent, Channel callee) throws PBXException - { + 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 = new Date(); + this._callStarted = DateUtil.getDate(); this.setOriginatingParty(agent); this.setAcceptingParty(callee); @@ -164,18 +159,17 @@ public CallImpl(Channel agent, Channel callee) throws PBXException * 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. + * 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 - { + CallDirection direction) throws PBXException { CallImpl joinTo = (CallImpl) rhs; Channel originatingParty = null; @@ -210,19 +204,15 @@ public CallImpl join(OperandChannel originatingOperand, Call rhs, OperandChannel return joined; } - private Date minDate(Date d1, Date d2) - { + private Date minDate(Date d1, Date d2) { - if (d1 == null) - { + if (d1 == null) { return d2; } - if (d2 == null) - { + if (d2 == null) { return d1; } - if (d1.before(d2)) - { + if (d1.before(d2)) { return d1; } return d2; @@ -319,12 +309,11 @@ private Date minDate(Date d1, Date d2) /** * 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 - { + public Call split(OperandChannel channelToSplit) throws PBXException { Channel channel = this.getOperandChannel(channelToSplit); channel.removeListener(this); @@ -332,8 +321,7 @@ public Call split(OperandChannel channelToSplit) throws PBXException // If this is the operator channel we need to flip the default // direction. - if (this.getLocalParty() != null && this.getLocalParty().isSame(channel)) - { + if (this.getLocalParty() != null && this.getLocalParty().isSame(channel)) { direction = CallDirection.OUTBOUND; } @@ -341,48 +329,42 @@ public Call split(OperandChannel channelToSplit) throws PBXException call._owner = OWNER.SELF; // clear the channel have just split out. - switch (channelToSplit) - { - case ACCEPTING_PARTY : + switch (channelToSplit) { + case ACCEPTING_PARTY: this.setAcceptingParty(null); break; - case LOCAL_PARTY : - if (this._direction == CallDirection.INBOUND) - { + case LOCAL_PARTY: + if (this._direction == CallDirection.INBOUND) { this.setAcceptingParty(null); - } - else - { + } else { this.setOriginatingParty(null); } break; - case ORIGINATING_PARTY : + case ORIGINATING_PARTY: this.setOriginatingParty(null); break; - case REMOTE_PARTY : + case REMOTE_PARTY: if (this._direction == CallDirection.INBOUND) this.setOriginatingParty(null); else this.setAcceptingParty(null); break; - case TRANSFER_TARGET_PARTY : + case TRANSFER_TARGET_PARTY: this.setTransferTargetParty(null); break; - default : + default: break; } return call; } - public Call split(Channel channelToSplit) throws PBXException - { + 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)) - { + if (this.getLocalParty() != null && this.getLocalParty().isSame(channelToSplit)) { direction = CallDirection.OUTBOUND; } @@ -399,77 +381,40 @@ public Call split(Channel channelToSplit) throws PBXException } @Override - public void channelHangup(Channel channel, Integer cause, String causeText) - { - try - { - if (isSameChannel(this._originatingParty, channel)) - { + 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)) - { + } 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)) - { + } 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 - { + } 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()) - { + if (!this.isLive()) { notifyCallHangupListeners(); } - } - catch (PBXException e) - { + } catch (PBXException e) { // not much we can do here so just log it logger.error(e, e); } } - private boolean isSameChannel(Channel lhs, Channel rhs) - { + private boolean isSameChannel(Channel lhs, Channel rhs) { return lhs != null && rhs != null && lhs.isSame(rhs); } - // private int findChannel(iChannel channel) - // { - // int index = -1; - // - // synchronized (this.channelList) - // { - // for (int i = 0; i < this.channelList.size(); i++) - // { - // iChannel aChannel = this.channelList.get(i); - // if (aChannel.isSame(channel)) - // { - // index = i; - // break; - // } - // } - // } - // return index; - // } - - private void notifyCallHangupListeners() - { - for (CallHangupListener listener : this._hangupListeners) - { + private void notifyCallHangupListeners() { + for (CallHangupListener listener : this._hangupListeners) { listener.callHungup(this); } @@ -480,13 +425,12 @@ private void notifyCallHangupListeners() * 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() - { + public Channel getOriginatingParty() { return this._originatingParty; } @@ -509,7 +453,7 @@ public Channel getOriginatingParty() // { // if (this.holdStarted == null) // { - // this.holdStarted = new Date(); + // this.holdStarted = DateUtil.getDate(); // } // this._state = Call.CallState.TRANSFER; // } @@ -518,110 +462,91 @@ public Channel getOriginatingParty() * 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. + * dialing. * @throws PBXException */ - public void callDialedOut(Channel remoteChannel, CallerID fromClid, CallerID toClid) throws PBXException - { + public void callDialedOut(Channel remoteChannel, CallerID fromClid, CallerID toClid) throws PBXException { // -- moved to ANSWER } @Override - public Date getCallStartTime() - { + public Date getCallStartTime() { return this._callStarted; } - public Integer getContactId() - { + public Integer getContactId() { return this._contactId; } /** * The current transfer target. - * + * * @return */ - public EndPoint getTransferTarget() - { + public EndPoint getTransferTarget() { return this._transferTarget; } - public CallerID getTransferTargetCallerID() - { + public CallerID getTransferTargetCallerID() { return this._transferTargetCallerID; } @Override - public CallerID getAcceptingPartyCallerID() - { + public CallerID getAcceptingPartyCallerID() { return this._acceptingPartyCallerID; } @Override - public CallerID getOriginatingPartyCallerID() - { + public CallerID getOriginatingPartyCallerID() { return this._originatingPartyCallerID; } @Override - public CallerID getRemotePartyCallerID() - { + public CallerID getRemotePartyCallerID() { CallerID remoteCallerID = null; - if (this.getDirection() == CallDirection.INBOUND) - { + if (this.getDirection() == CallDirection.INBOUND) { remoteCallerID = this.getOriginatingPartyCallerID(); - } - else - { + } else { remoteCallerID = this.getAcceptingPartyCallerID(); } return remoteCallerID; } - public Date getHoldStartTime() - { + public Date getHoldStartTime() { return this._holdStarted; } - public EndPoint getParkingLot() - { + public EndPoint getParkingLot() { return this._parkingLot; } - public Date getTimeAtDialIn() - { + public Date getTimeAtDialIn() { return this._timeAtDialin; } - public TransferType getTransferType() - { + public TransferType getTransferType() { return this.transferType; } - public String getUniqueCallID() - { + public String getUniqueCallID() { /* * this is a unique call identifier. */ return "" + this._uniquecallID; //$NON-NLS-1$ } - public boolean isCallParked() - { + public boolean isCallParked() { return this._parked; } - private void setOriginatingParty(Channel originatingParty) throws PBXException - { + private void setOriginatingParty(Channel originatingParty) throws PBXException { this._originatingParty = originatingParty; - if (originatingParty != null) - { + if (originatingParty != null) { if (!this._originatingParty.canDetectHangup() && this._acceptingParty != null && !this._acceptingParty.canDetectHangup()) throw new PBXException("Call.BothWithNoHangupDetection"); //$NON-NLS-1$ @@ -630,12 +555,10 @@ private void setOriginatingParty(Channel originatingParty) throws PBXException } } - private void setAcceptingParty(Channel acceptingParty) throws PBXException - { + private void setAcceptingParty(Channel acceptingParty) throws PBXException { this._acceptingParty = acceptingParty; - if (acceptingParty != null) - { + if (acceptingParty != null) { if (!this._acceptingParty.canDetectHangup() && this._originatingParty != null && !this._originatingParty.canDetectHangup()) throw new PBXException("Call.BothWithNoHangupDetection"); //$NON-NLS-1$ @@ -644,12 +567,10 @@ private void setAcceptingParty(Channel acceptingParty) throws PBXException } } - private void setTransferTargetParty(Channel transferTargetParty) - { + private void setTransferTargetParty(Channel transferTargetParty) { this._transferTargetParty = transferTargetParty; - if (transferTargetParty != null) - { + if (transferTargetParty != null) { this._transferTargetParty.addHangupListener(this); } } @@ -658,11 +579,10 @@ private void setTransferTargetParty(Channel transferTargetParty) * 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) - { + public void setContactId(final Integer _contactId) { this._contactId = _contactId; } @@ -673,20 +593,18 @@ public void setContactId(final Integer _contactId) // } @Override - public CallDirection getDirection() - { + 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. + * already been hungup. */ - public boolean addHangupListener(CallHangupListener listener) - { + public boolean addHangupListener(CallHangupListener listener) { boolean callStillUp = true; if ((this._originatingParty != null && this._originatingParty.isLive()) @@ -701,11 +619,10 @@ public boolean addHangupListener(CallHangupListener listener) /** * returns true if the call has any active channels. - * + * * @return */ - public boolean isLive() - { + public boolean isLive() { boolean live = false; if ((this._originatingParty != null && this._originatingParty.isLive()) || (this._acceptingParty != null && this._acceptingParty.isLive()) @@ -717,48 +634,26 @@ public boolean isLive() /** * @return true if this call is owned by another instance of NJR. */ - public OWNER getOwner() - { + public OWNER getOwner() { return this._owner; } - // /** - // * Returns a shallow clone of the list of channels. - // */ - // @SuppressWarnings("unchecked") - // @Override - // public Collection getChannels() - // { - // synchronized (this.channelList) - // { - // return (Collection) this.channelList.clone(); - // } - // } - @Override - public String toString() - { + public String toString() { return "State: Originating Channel:" + getOriginatingParty() + " Direction: " //$NON-NLS-1$ //$NON-NLS-2$ - // //$NON-NLS-3$ + // //$NON-NLS-3$ + this.getDirection() + " accepting:" + this._acceptingParty; //$NON-NLS-1$ } @Override - public boolean contains(Channel parkChannel) - { + public boolean contains(Channel parkChannel) { boolean found = false; - if (isSameChannel(this._originatingParty, parkChannel)) - { + if (isSameChannel(this._originatingParty, parkChannel)) { found = true; - } - else if (isSameChannel(this._acceptingParty, parkChannel)) - { + } else if (isSameChannel(this._acceptingParty, parkChannel)) { found = true; - } - - else if (isSameChannel(this._transferTargetParty, parkChannel)) - { + } else if (isSameChannel(this._transferTargetParty, parkChannel)) { found = true; } @@ -766,14 +661,12 @@ else if (isSameChannel(this._transferTargetParty, parkChannel)) } @Override - public Channel getAcceptingParty() - { + public Channel getAcceptingParty() { return this._acceptingParty; } @Override - public Channel getTransferTargetParty() - { + public Channel getTransferTargetParty() { return this._transferTargetParty; } @@ -782,23 +675,18 @@ public Channel getTransferTargetParty() * 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() - { + public Channel getRemoteParty() { Channel remoteChannel = null; - if (this.getDirection() == CallDirection.INBOUND) - { + if (this.getDirection() == CallDirection.INBOUND) { remoteChannel = this.getOriginatingParty(); - } - else - { + } else { remoteChannel = this.getAcceptingParty(); } - if (remoteChannel == null) - { + if (remoteChannel == null) { logger.error("remoteChannel is null for {}" + this.getDirection()); } return remoteChannel; @@ -809,12 +697,11 @@ public 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 */ @Override - public Channel getLocalParty() - { + public Channel getLocalParty() { if (this.getDirection() == CallDirection.OUTBOUND) return this.getOriginatingParty(); @@ -824,46 +711,41 @@ public Channel getLocalParty() } @Override - public boolean canSplit() - { + public boolean canSplit() { return (this._originatingParty != null && this._acceptingParty != null && this._transferTargetParty == null); } @Override - public Channel getOperandChannel(OperandChannel operand) - { + public Channel getOperandChannel(OperandChannel operand) { final Channel channel; - switch (operand) - { - case ACCEPTING_PARTY : + switch (operand) { + case ACCEPTING_PARTY: channel = this._acceptingParty; break; - case ORIGINATING_PARTY : + case ORIGINATING_PARTY: channel = this._originatingParty; break; - case REMOTE_PARTY : + case REMOTE_PARTY: channel = getRemoteParty(); break; - case TRANSFER_TARGET_PARTY : + case TRANSFER_TARGET_PARTY: channel = this._transferTargetParty; break; - case LOCAL_PARTY : + case LOCAL_PARTY: channel = this.getLocalParty(); break; - default : + default: // should never happen throw new IllegalArgumentException("An unsupported operand was passed:" + operand); //$NON-NLS-1$ } - if (channel == null) - { + if (channel == null) { logger.warn("failed to get channel for " + operand); } return channel; } - public boolean isSame(Call rhs) - { + public boolean isSame(Call rhs) { return this._uniquecallID == ((CallImpl) rhs)._uniquecallID; } @@ -871,8 +753,7 @@ public boolean isSame(Call rhs) * Returns all of the Channels associated with this call. */ @Override - public List getChannels() - { + public List getChannels() { List channels = new LinkedList<>(); if (_acceptingParty != null) channels.add(_acceptingParty); diff --git a/src/main/java/org/asteriskjava/pbx/CallStateAnswered.java b/src/main/java/org/asteriskjava/pbx/CallStateAnswered.java index 30f8714b7..5d9a0309e 100644 --- a/src/main/java/org/asteriskjava/pbx/CallStateAnswered.java +++ b/src/main/java/org/asteriskjava/pbx/CallStateAnswered.java @@ -3,21 +3,18 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class CallStateAnswered extends CallStateData -{ +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) - { + public CallStateAnswered(Channel acceptingParty) { this._acceptingParty = acceptingParty; } - public Channel getAcceptingParty() - { + 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 index c840e29d3..656421811 100644 --- a/src/main/java/org/asteriskjava/pbx/CallStateData.java +++ b/src/main/java/org/asteriskjava/pbx/CallStateData.java @@ -1,5 +1,4 @@ package org.asteriskjava.pbx; -public class CallStateData -{ +public class CallStateData { } diff --git a/src/main/java/org/asteriskjava/pbx/CallStateDataNewInbound.java b/src/main/java/org/asteriskjava/pbx/CallStateDataNewInbound.java index 428030b63..4541e161f 100644 --- a/src/main/java/org/asteriskjava/pbx/CallStateDataNewInbound.java +++ b/src/main/java/org/asteriskjava/pbx/CallStateDataNewInbound.java @@ -3,8 +3,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class CallStateDataNewInbound extends CallStateData -{ +public class CallStateDataNewInbound extends CallStateData { @SuppressWarnings("unused") private static final Log logger = LogFactory.getLog(CallStateDataNewInbound.class); @@ -12,19 +11,16 @@ public class CallStateDataNewInbound extends CallStateData private final String _fromDID; - public CallStateDataNewInbound(String fromDID, CallerID originatingPartyCallerID) - { + public CallStateDataNewInbound(String fromDID, CallerID originatingPartyCallerID) { this._originatingPartyCallerID = originatingPartyCallerID; this._fromDID = fromDID; } - public CallerID getOriginatingPartyCallerID() - { + public CallerID getOriginatingPartyCallerID() { return this._originatingPartyCallerID; } - public String getFromDID() - { + 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 index 0a52bcc4d..e1ac74a7d 100644 --- a/src/main/java/org/asteriskjava/pbx/CallStateDataParked.java +++ b/src/main/java/org/asteriskjava/pbx/CallStateDataParked.java @@ -1,12 +1,10 @@ package org.asteriskjava.pbx; -public class CallStateDataParked extends CallStateData -{ +public class CallStateDataParked extends CallStateData { EndPoint _parkingLot; - public CallStateDataParked(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 index c0686ca5f..c0f2d4b96 100644 --- a/src/main/java/org/asteriskjava/pbx/CallStateDataTransfer.java +++ b/src/main/java/org/asteriskjava/pbx/CallStateDataTransfer.java @@ -3,8 +3,7 @@ import org.asteriskjava.pbx.CallImpl.TransferType; import org.asteriskjava.pbx.activities.BlindTransferActivity; -public class CallStateDataTransfer extends CallStateData -{ +public class CallStateDataTransfer extends CallStateData { private TransferType _transferType; /** @@ -17,31 +16,26 @@ public class CallStateDataTransfer extends CallStateData private BlindTransferActivity _transferActivity; public CallStateDataTransfer(TransferType transferType, EndPoint transferTarget, CallerID transferTargetCallerID, - BlindTransferActivity transferActivity) - { + BlindTransferActivity transferActivity) { this._transferType = transferType; this._transferTarget = transferTarget; this._transferTargetCallerID = transferTargetCallerID; this._transferActivity = transferActivity; } - public EndPoint getTransferTarget() - { + public EndPoint getTransferTarget() { return this._transferTarget; } - public CallerID getTransferTargetCallerID() - { + public CallerID getTransferTargetCallerID() { return this._transferTargetCallerID; } - public TransferType getTransferType() - { + public TransferType getTransferType() { return this._transferType; } - public BlindTransferActivity getActivity() - { + 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 index 833edd5f3..7c32c9ea3 100644 --- a/src/main/java/org/asteriskjava/pbx/CallerID.java +++ b/src/main/java/org/asteriskjava/pbx/CallerID.java @@ -1,40 +1,37 @@ package org.asteriskjava.pbx; -public interface CallerID -{ - /** - * Gets the number component of the caller id. - * - * @return the callerid's number - */ - String getNumber(); +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(); + /** + * 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); + /** + * 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(); + /** + * @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(); + /** + * 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 index 2299cfbf0..93302abef 100644 --- a/src/main/java/org/asteriskjava/pbx/Channel.java +++ b/src/main/java/org/asteriskjava/pbx/Channel.java @@ -5,16 +5,15 @@ /** * Provides an abstraction for an channel object which is independant of the * underlying PBX. - * + * * @author bsutton */ -public interface Channel -{ +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 */ @@ -34,7 +33,7 @@ public interface Channel /** * Compares if this channel is the same as the named channel. - * + * * @param channelName * @return */ @@ -43,27 +42,27 @@ public interface Channel /** * 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. + * 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. + * 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(); @@ -72,7 +71,7 @@ public interface Channel * 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(); @@ -81,7 +80,7 @@ public interface Channel * 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); @@ -90,7 +89,7 @@ public interface Channel /** * Returns true if the given endpont is currently connected to this channel. - * + * * @param extension * @return */ @@ -99,7 +98,7 @@ public interface Channel /** * returns a fully qualifed channel name which includes the tech. e.g. * SIP/100-00000342 - * + * * @return */ String getChannelName(); @@ -109,7 +108,7 @@ public interface Channel /** * 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(); @@ -117,7 +116,7 @@ public interface Channel /** * 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(); @@ -129,28 +128,28 @@ public interface Channel /** * 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). + * (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(); @@ -179,7 +178,7 @@ public interface Channel /** * Called to rename a channel - * + * * @param newname the new name of the channel * @throws InvalidChannelName */ diff --git a/src/main/java/org/asteriskjava/pbx/ChannelFactory.java b/src/main/java/org/asteriskjava/pbx/ChannelFactory.java index 1da871dd6..b49adb4a3 100644 --- a/src/main/java/org/asteriskjava/pbx/ChannelFactory.java +++ b/src/main/java/org/asteriskjava/pbx/ChannelFactory.java @@ -5,16 +5,14 @@ /** * 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 -{ +public class ChannelFactory { private final static AtomicLong nextChannelId = new AtomicLong(); - public static long getNextChannelId() - { + 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 index 9f0abc4f1..504e36225 100644 --- a/src/main/java/org/asteriskjava/pbx/ChannelHangupListener.java +++ b/src/main/java/org/asteriskjava/pbx/ChannelHangupListener.java @@ -2,11 +2,10 @@ /** * Used to notify channel listeners of state changes to a channel. - * + * * @author bsutton */ -public interface ChannelHangupListener -{ +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 index 71f6b4d6d..9e36e5cdc 100644 --- a/src/main/java/org/asteriskjava/pbx/CompletionAdaptor.java +++ b/src/main/java/org/asteriskjava/pbx/CompletionAdaptor.java @@ -1,48 +1,40 @@ package org.asteriskjava.pbx; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - 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. - * - * @author bsutton + * * @param + * @author bsutton */ -public class CompletionAdaptor implements ActivityCallback -{ +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) - { + 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) - { + public void waitForCompletion(long timeout, TimeUnit unit) { // wait until the activity completes - try - { - if (!_latch.await(timeout, unit)) - { + 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) - { + } 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 index ab6166e02..0eab4c25e 100644 --- a/src/main/java/org/asteriskjava/pbx/DTMFTone.java +++ b/src/main/java/org/asteriskjava/pbx/DTMFTone.java @@ -2,26 +2,22 @@ /** * 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('*'); +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; + private final String character; - DTMFTone(final char character) - { - this.character = new String(new char[] { character }); - } + DTMFTone(final char character) { + this.character = new String(new char[]{character}); + } - @Override - public String toString() - { - return this.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 index 50008aaf1..5dc7f73c2 100644 --- a/src/main/java/org/asteriskjava/pbx/DefaultAsteriskSettings.java +++ b/src/main/java/org/asteriskjava/pbx/DefaultAsteriskSettings.java @@ -3,104 +3,93 @@ /** * 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 + *

    + * If you are using handsets other than yealink or snom you should also over-ride * the getAutoAnswer settings. - * - * @author bsutton * + * @author bsutton */ -public abstract class DefaultAsteriskSettings implements AsteriskSettings -{ +public abstract class DefaultAsteriskSettings implements AsteriskSettings { - @Override - public int getManagerPortNo() - { - return 5060; - } + @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 new Integer(3000); - } + @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 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 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 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; - } + @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"; - } + /* + * 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 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; - } + @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 index cbdf2e7c3..9e0154aee 100644 --- a/src/main/java/org/asteriskjava/pbx/DialPlanExtension.java +++ b/src/main/java/org/asteriskjava/pbx/DialPlanExtension.java @@ -5,51 +5,42 @@ * 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 -{ +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) - { + public DialPlanExtension(String extension) { + if (extension == null || extension.trim().length() == 0) { this._empty = true; this._extension = ""; - } - else - { + } else { this._extension = extension.trim(); this._empty = false; } } @Override - public int compareTo(EndPoint rhs) - { + public int compareTo(EndPoint rhs) { return this._extension.compareTo(rhs.getSimpleName()); } @Override - public boolean isSame(EndPoint rhs) - { + public boolean isSame(EndPoint rhs) { return this.compareTo(rhs) == 0; } @Override - public boolean isLocal() - { + public boolean isLocal() { return false; } @Override - public boolean isSIP() - { + public boolean isSIP() { return false; } @@ -58,44 +49,37 @@ public boolean isSIP() * identifier rather than a legitimate tech that the pbx understands. */ @Override - public String getFullyQualifiedName() - { + public String getFullyQualifiedName() { return this._extension; } @Override - public String getSimpleName() - { + public String getSimpleName() { return this._extension; } @Override - public String getSIPSimpleName() - { + public String getSIPSimpleName() { throw new UnsupportedOperationException(); } @Override - public boolean isUnknown() - { + public boolean isUnknown() { // TODO Auto-generated method stub return false; } @Override - public TechType getTech() - { + public TechType getTech() { return TechType.DIALPLAN; } - public String toString() - { + public String toString() { return this._extension; } @Override - public boolean isEmpty() - { + 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 index 731e49a26..0288f3995 100644 --- a/src/main/java/org/asteriskjava/pbx/EndPoint.java +++ b/src/main/java/org/asteriskjava/pbx/EndPoint.java @@ -2,68 +2,65 @@ /** * 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); +public interface EndPoint extends Comparable { + boolean isSame(EndPoint rhs); - boolean isLocal(); + boolean isLocal(); - boolean isSIP(); + boolean isSIP(); - /** - * Returns the fully qualified name of the EndPoint including the tech. e.g. - * SIP/100 - * - * @return - */ - String getFullyQualifiedName(); + /** + * 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 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 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 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(); + /** + * Returns the Tech that is used to reach this endpoint. + * + * @return + */ + TechType getTech(); - boolean isEmpty(); + boolean isEmpty(); - /** - * Sets the tech on the end point to the specified tech. - * - * @param sip - */ - // public void setTech(Tech tech); + /** + * 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 index b1cb6de54..834ad3287 100644 --- a/src/main/java/org/asteriskjava/pbx/InvalidChannelName.java +++ b/src/main/java/org/asteriskjava/pbx/InvalidChannelName.java @@ -1,12 +1,10 @@ package org.asteriskjava.pbx; -public class InvalidChannelName extends Exception -{ - private static final long serialVersionUID = 1L; +public class InvalidChannelName extends Exception { + private static final long serialVersionUID = 1L; - public InvalidChannelName(final String message) - { - super(message); - } + 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 index 7c622ff43..de211bbb0 100644 --- a/src/main/java/org/asteriskjava/pbx/ListenerPriority.java +++ b/src/main/java/org/asteriskjava/pbx/ListenerPriority.java @@ -1,35 +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. - */ +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); + REALTIME(100), CRITICAL(10), HIGH(8), NORMAL(6), LOW(4); - // The priority of the listeners. Higher priority listeners receive - // events first. - private int _priority; + // The priority of the listeners. Higher priority listeners receive + // events first. + private int _priority; - ListenerPriority(int priority) - { - this._priority = priority; - } + ListenerPriority(int priority) { + this._priority = priority; + } - public int compare(ListenerPriority rhs) - { - return rhs._priority - this._priority; - } -} \ No newline at end of file + 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 index c4725b1ac..4f1d8241f 100644 --- a/src/main/java/org/asteriskjava/pbx/NewChannelListener.java +++ b/src/main/java/org/asteriskjava/pbx/NewChannelListener.java @@ -1,24 +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); +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 index 5bce30e85..edcf5f524 100644 --- a/src/main/java/org/asteriskjava/pbx/NewExtensionListener.java +++ b/src/main/java/org/asteriskjava/pbx/NewExtensionListener.java @@ -3,13 +3,11 @@ /** * Used to notify interested parties when a new extension has been read from the * pbx configuration. - * + * * @author bsutton - * */ -public interface NewExtensionListener -{ +public interface NewExtensionListener { - void newExtension(); + void newExtension(); } diff --git a/src/main/java/org/asteriskjava/pbx/PBX.java b/src/main/java/org/asteriskjava/pbx/PBX.java index 9b355e702..a42d81a9b 100644 --- a/src/main/java/org/asteriskjava/pbx/PBX.java +++ b/src/main/java/org/asteriskjava/pbx/PBX.java @@ -1,23 +1,16 @@ package org.asteriskjava.pbx; -import java.util.List; - import org.asteriskjava.pbx.Call.OperandChannel; -import org.asteriskjava.pbx.activities.BlindTransferActivity; -import org.asteriskjava.pbx.activities.DialActivity; -import org.asteriskjava.pbx.activities.HoldActivity; -import org.asteriskjava.pbx.activities.JoinActivity; -import org.asteriskjava.pbx.activities.ParkActivity; -import org.asteriskjava.pbx.activities.RedirectToActivity; -import org.asteriskjava.pbx.activities.SplitActivity; +import org.asteriskjava.pbx.activities.*; + +import java.util.List; /** * Provides an abstracted interface for communicating with a PBX. - * + * * @author bsutton */ -public interface PBX -{ +public interface PBX { /** * Call this method when shutting down the PBX interface to allow it to @@ -38,21 +31,21 @@ public interface PBX * 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 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); + final CallerID toCallerID, boolean autoAnswer, long timeout, String dialOptions); /** * The BlindTransferActivity is used by the AsteriksPBX to transfer a live @@ -61,24 +54,24 @@ BlindTransferActivity blindTransfer(final Call call, OperandChannel channelToTra * 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. + * @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); + 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); @@ -87,7 +80,7 @@ void blindTransfer(Call call, OperandChannel channelToTransfer, final EndPoint t * 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 */ @@ -97,7 +90,7 @@ void blindTransfer(Call call, OperandChannel channelToTransfer, final EndPoint t * 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); @@ -106,15 +99,15 @@ void blindTransfer(Call call, OperandChannel channelToTransfer, final EndPoint t * 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); + ActivityCallback callback, String dialOptions); /** * Hangs up the given channel. Not returning until the call is hungup. - * + * * @param channel * @throws PBXException */ @@ -124,7 +117,7 @@ void dial(EndPoint from, CallerID fromCallerID, EndPoint to, CallerID toCallerID * 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 */ @@ -132,14 +125,14 @@ void dial(EndPoint from, CallerID fromCallerID, EndPoint to, CallerID toCallerID /** * 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 */ @@ -159,10 +152,10 @@ void dial(EndPoint from, CallerID fromCallerID, EndPoint to, CallerID toCallerID * (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 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); @@ -176,17 +169,17 @@ void dial(EndPoint from, CallerID fromCallerID, EndPoint to, CallerID toCallerID * 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 the call which is to be parked. * @param parkChannel - the channel which is going to be redirect to the - * njr-park extension. + * 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 */ @@ -196,7 +189,7 @@ void dial(EndPoint from, CallerID fromCallerID, EndPoint to, CallerID toCallerID * 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 */ @@ -218,18 +211,18 @@ void dial(EndPoint from, CallerID fromCallerID, EndPoint to, CallerID toCallerID * only have one active channel */ JoinActivity join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel acceptingOperand, - CallDirection direction); + CallDirection direction); void join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel acceptingOperand, - CallDirection direction, ActivityCallback listener); + 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. + * not currently in a call. */ Channel getChannelByEndPoint(EndPoint endPoint); @@ -248,7 +241,7 @@ void join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel * 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 */ @@ -258,7 +251,7 @@ void join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel * 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 */ diff --git a/src/main/java/org/asteriskjava/pbx/PBXException.java b/src/main/java/org/asteriskjava/pbx/PBXException.java index 6d12bf3fe..5d7a6136c 100644 --- a/src/main/java/org/asteriskjava/pbx/PBXException.java +++ b/src/main/java/org/asteriskjava/pbx/PBXException.java @@ -1,21 +1,17 @@ package org.asteriskjava.pbx; -public class PBXException extends Exception -{ +public class PBXException extends Exception { private static final long serialVersionUID = 1L; - public PBXException(String message, final Exception e) - { + public PBXException(String message, final Exception e) { super(message, e); } - public PBXException(final String message) - { + public PBXException(final String message) { super(message); } - public PBXException(Throwable e) - { + 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 index 7a64e7e40..3e99f79fa 100644 --- a/src/main/java/org/asteriskjava/pbx/PBXFactory.java +++ b/src/main/java/org/asteriskjava/pbx/PBXFactory.java @@ -1,32 +1,27 @@ package org.asteriskjava.pbx; -import java.util.concurrent.atomic.AtomicReference; - import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class PBXFactory -{ +import java.util.concurrent.atomic.AtomicReference; + +public class PBXFactory { - public static PBX getActivePBX() - { + public static PBX getActivePBX() { return AsteriskPBX.SELF; } final static AtomicReference profile = new AtomicReference<>(); - public static void init(AsteriskSettings newProfile) - { + public static void init(AsteriskSettings newProfile) { profile.set(newProfile); getActivePBX().performPostCreationTasks(); } - public static AsteriskSettings getActiveProfile() - { + public static AsteriskSettings getActiveProfile() { AsteriskSettings activeProfile = profile.get(); - if (activeProfile == null) - { + if (activeProfile == null) { throw new RuntimeException( "you must call setAsteriskSettings() before getActiveProfile() is called the first time"); } diff --git a/src/main/java/org/asteriskjava/pbx/PhoneNumber.java b/src/main/java/org/asteriskjava/pbx/PhoneNumber.java index 31c99e165..501e3cc2c 100644 --- a/src/main/java/org/asteriskjava/pbx/PhoneNumber.java +++ b/src/main/java/org/asteriskjava/pbx/PhoneNumber.java @@ -3,16 +3,14 @@ /** * 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 +public interface PhoneNumber { + // TODO } diff --git a/src/main/java/org/asteriskjava/pbx/Tech.java b/src/main/java/org/asteriskjava/pbx/Tech.java index 954834e22..2699cb641 100644 --- a/src/main/java/org/asteriskjava/pbx/Tech.java +++ b/src/main/java/org/asteriskjava/pbx/Tech.java @@ -1,6 +1,5 @@ package org.asteriskjava.pbx; -public interface Tech -{ - // TODO: do we need this? +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 index eb767ddc6..f3307f150 100644 --- a/src/main/java/org/asteriskjava/pbx/TechType.java +++ b/src/main/java/org/asteriskjava/pbx/TechType.java @@ -3,8 +3,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public enum TechType implements Tech -{ +public enum TechType implements Tech { // UNKNOWN, SIP, DAHDI, LOCAL, IAX, IAX2 @@ -27,14 +26,12 @@ public enum TechType implements Tech /** * 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)) - { + 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$ } @@ -45,24 +42,19 @@ public static TechType getTech(final String fullyQualifiedEndPoint) /** * returns true if the endPoint name contains a valid tech descriptor. - * + * * @param endPointName * @return */ - public static boolean hasValidTech(final String endPointName) - { + public static boolean hasValidTech(final String endPointName) { TechType tech = UNKNOWN; final int index = endPointName.indexOf("/"); //$NON-NLS-1$ - if (index >= 1) - { + if (index >= 1) { final String techName = endPointName.substring(0, index); - try - { + try { tech = TechType.valueOf(techName.toUpperCase()); - } - catch (final IllegalArgumentException e) - { + } catch (final IllegalArgumentException e) { TechType.logger.error("Invalid tech for endpoint:" + endPointName); //$NON-NLS-1$ } } @@ -74,18 +66,16 @@ public static boolean hasValidTech(final String endPointName) /** * 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) - { + public static boolean hasTech(final String endPointName) { boolean hasTech = false; final int index = endPointName.indexOf("/"); //$NON-NLS-1$ - if (index != -1) - { + if (index != -1) { hasTech = true; } diff --git a/src/main/java/org/asteriskjava/pbx/Trunk.java b/src/main/java/org/asteriskjava/pbx/Trunk.java index 981591102..005165b1f 100644 --- a/src/main/java/org/asteriskjava/pbx/Trunk.java +++ b/src/main/java/org/asteriskjava/pbx/Trunk.java @@ -3,7 +3,6 @@ /** * Provides an abstraction of a trunk * @author bsutton */ -public interface Trunk -{ +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 index e18527f6e..802cc3104 100644 --- a/src/main/java/org/asteriskjava/pbx/activities/BlindTransferActivity.java +++ b/src/main/java/org/asteriskjava/pbx/activities/BlindTransferActivity.java @@ -1,64 +1,56 @@ package org.asteriskjava.pbx.activities; -import org.asteriskjava.pbx.Activity; -import org.asteriskjava.pbx.Call; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.PBXException; - -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"); - - 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; +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 index 11fbd13dc..62a6aa8d5 100644 --- a/src/main/java/org/asteriskjava/pbx/activities/BridgeActivity.java +++ b/src/main/java/org/asteriskjava/pbx/activities/BridgeActivity.java @@ -2,7 +2,6 @@ import org.asteriskjava.pbx.Activity; -public interface BridgeActivity extends Activity -{ - // TODO +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 index 46a7ceab4..0565676ca 100644 --- a/src/main/java/org/asteriskjava/pbx/activities/DialActivity.java +++ b/src/main/java/org/asteriskjava/pbx/activities/DialActivity.java @@ -5,49 +5,49 @@ 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(); +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 index bd743ea86..27a17dda6 100644 --- a/src/main/java/org/asteriskjava/pbx/activities/DialToAgiActivity.java +++ b/src/main/java/org/asteriskjava/pbx/activities/DialToAgiActivity.java @@ -4,8 +4,7 @@ import org.asteriskjava.pbx.Channel; import org.asteriskjava.pbx.EndPoint; -public interface DialToAgiActivity extends Activity -{ +public interface DialToAgiActivity extends Activity { void markCancelled(); diff --git a/src/main/java/org/asteriskjava/pbx/activities/HoldActivity.java b/src/main/java/org/asteriskjava/pbx/activities/HoldActivity.java index e932204e6..bc4e62322 100644 --- a/src/main/java/org/asteriskjava/pbx/activities/HoldActivity.java +++ b/src/main/java/org/asteriskjava/pbx/activities/HoldActivity.java @@ -3,8 +3,7 @@ import org.asteriskjava.pbx.Activity; import org.asteriskjava.pbx.Channel; -public interface HoldActivity extends Activity -{ - // Returns the Channel that is on hold - Channel getChannel(); +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 index 30acf65cd..e7430dc7c 100644 --- a/src/main/java/org/asteriskjava/pbx/activities/JoinActivity.java +++ b/src/main/java/org/asteriskjava/pbx/activities/JoinActivity.java @@ -3,8 +3,7 @@ import org.asteriskjava.pbx.Activity; import org.asteriskjava.pbx.Call; -public interface JoinActivity extends Activity -{ - Call getJoinedCall(); +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 index 5d4282115..ab15228ad 100644 --- a/src/main/java/org/asteriskjava/pbx/activities/ParkActivity.java +++ b/src/main/java/org/asteriskjava/pbx/activities/ParkActivity.java @@ -3,14 +3,13 @@ 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(); +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 index ff2342b46..1352d8077 100644 --- a/src/main/java/org/asteriskjava/pbx/activities/RedirectToActivity.java +++ b/src/main/java/org/asteriskjava/pbx/activities/RedirectToActivity.java @@ -3,16 +3,15 @@ import org.asteriskjava.pbx.Activity; import org.asteriskjava.pbx.Call; -public interface RedirectToActivity extends Activity -{ +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 + * 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 index cfd99fcd9..3af630d70 100644 --- a/src/main/java/org/asteriskjava/pbx/activities/SplitActivity.java +++ b/src/main/java/org/asteriskjava/pbx/activities/SplitActivity.java @@ -3,30 +3,29 @@ import org.asteriskjava.pbx.Activity; import org.asteriskjava.pbx.Call; -public interface SplitActivity extends Activity -{ +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 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(); + /** + * 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 index c2ddf7198..f3a08c1b1 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/ActivityAgi.java +++ b/src/main/java/org/asteriskjava/pbx/agi/ActivityAgi.java @@ -1,25 +1,21 @@ package org.asteriskjava.pbx.agi; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - +import com.google.common.util.concurrent.RateLimiter; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiHangupException; -import org.asteriskjava.pbx.AgiChannelActivityAction; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ChannelHangupListener; -import org.asteriskjava.pbx.InvalidChannelName; -import org.asteriskjava.pbx.PBXFactory; +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; -public abstract class ActivityAgi extends ServiceAgiScriptImpl -{ +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"; @@ -27,13 +23,11 @@ public abstract class ActivityAgi extends ServiceAgiScriptImpl private static final Map arrivalListeners = new ConcurrentHashMap<>(); - public static AutoCloseable addArrivalListener(OriginateAction originate, ActivityArrivalListener listener) - { + public static AutoCloseable addArrivalListener(OriginateAction originate, ActivityArrivalListener listener) { final String key = UUID.randomUUID().toString(); arrivalListeners.put(key, listener); - if (arrivalListeners.size() > 100) - { + 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()); @@ -42,12 +36,10 @@ public static AutoCloseable addArrivalListener(OriginateAction originate, Activi Map vars = new HashMap<>(); vars.put("_" + ARRIVAL_KEY, key); originate.setVariables(vars); - return new AutoCloseable() - { + return new AutoCloseable() { @Override - public void close() throws Exception - { + public void close() throws Exception { arrivalListeners.remove(key); } @@ -55,21 +47,17 @@ public void close() throws Exception } @Override - public void service() throws AgiException - { + public void service() throws AgiException { Channel channelProxy = null; String channelName = channel.getName(); - try - { + try { AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); String proxyId = getVariable("proxyId"); - if (proxyId != null && proxyId.length() > 0) - { + if (proxyId != null && proxyId.length() > 0) { channelProxy = pbx.getProxyById(proxyId); } - if (channelProxy == null) - { + 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()); @@ -79,15 +67,12 @@ public void service() throws AgiException logger.info("Channel " + channelName + " arrived in agi"); channelProxy.setIsInAgi(true); - channelProxy.addHangupListener(new ChannelHangupListener() - { + channelProxy.addHangupListener(new ChannelHangupListener() { @Override - public void channelHangup(Channel channel, Integer cause, String causeText) - { + public void channelHangup(Channel channel, Integer cause, String causeText) { final AgiChannelActivityAction currentActivityAction = channel.getCurrentActivityAction(); - if (currentActivityAction != null) - { + if (currentActivityAction != null) { currentActivityAction.cancel(); } @@ -95,41 +80,32 @@ public void channelHangup(Channel channel, Integer cause, String causeText) }); AgiChannelActivityAction action = channelProxy.getCurrentActivityAction(); - if (action == null) - { + if (action == null) { action = new AgiChannelActivityHold(); } String arrivalKey = channel.getVariable(ARRIVAL_KEY); - if (arrivalKey != null && arrivalKey.length() > 0) - { + if (arrivalKey != null && arrivalKey.length() > 0) { ActivityArrivalListener listener = arrivalListeners.get(arrivalKey); - if (listener != null) - { + if (listener != null) { listener.channelArrived(channelProxy); } } boolean isAlive = true; - RateLimiter rateLimiter = new RateLimiter(2); - while (!action.isDisconnect() && isAlive) - { - + 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(); - rateLimiter.acquire(); + slowRateLimiter.acquire(); } - } - catch (AgiHangupException e) - { + } catch (AgiHangupException e) { logger.warn("Channel hungup " + channelName); - } - catch (InvalidChannelName | InterruptedException e) - { + } catch (InvalidChannelName | InterruptedException e) { logger.error(e, e); } @@ -137,16 +113,11 @@ public void channelHangup(Channel channel, Integer cause, String causeText) } - private boolean checkChannelIsStillUp() - { - try - - { + private boolean checkChannelIsStillUp() { + try { this.answer(); return true; - } - catch (Exception e) - { + } 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 index d475f0e41..877de668b 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/ActivityArrivalListener.java +++ b/src/main/java/org/asteriskjava/pbx/agi/ActivityArrivalListener.java @@ -2,8 +2,7 @@ import org.asteriskjava.pbx.Channel; -public interface ActivityArrivalListener -{ +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 index c942c52aa..c25e89a4b 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBlindTransfer.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBlindTransfer.java @@ -1,14 +1,13 @@ package org.asteriskjava.pbx.agi; -import java.util.concurrent.CountDownLatch; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.pbx.AgiChannelActivityAction; import org.asteriskjava.pbx.Channel; -public class AgiChannelActivityBlindTransfer implements AgiChannelActivityAction -{ +import java.util.concurrent.CountDownLatch; + +public class AgiChannelActivityBlindTransfer implements AgiChannelActivityAction { CountDownLatch latch = new CountDownLatch(1); private String target; @@ -16,39 +15,41 @@ public class AgiChannelActivityBlindTransfer implements AgiChannelActivityAction int timeout = 30; private String callerId; private String dialOptions; + private BlindTransferResultListener listener; - public AgiChannelActivityBlindTransfer(String fullyQualifiedName, String sipHeader, String callerId, String dialOptions) - { + 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) - { + if (sipHeader == null) { this.sipHeader = ""; } + this.listener = listener; } @Override - public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException - { + 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() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return false; } @Override - public void cancel() - { + 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 index 617a90ab7..458c8920a 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBridge.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityBridge.java @@ -1,7 +1,5 @@ package org.asteriskjava.pbx.agi; -import java.util.concurrent.CountDownLatch; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiHangupException; @@ -10,24 +8,22 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AgiChannelActivityBridge implements AgiChannelActivityAction -{ +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) - { + public AgiChannelActivityBridge(Channel target) { this.target = target; } @Override - public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException - { - try - { + 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. @@ -36,33 +32,26 @@ public void execute(AgiChannel channel, Channel ichannel) throws AgiException, I // I can't currently see it causing problems. channel.bridge(target.getChannelName(), ""); channel.hangup(); - } - catch (AgiHangupException e) - { + } catch (AgiHangupException e) { logger.warn(e); - } - finally - { + } finally { latch.countDown(); } } @Override - public boolean isDisconnect() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return false; } @Override - public void cancel() - { + public void cancel() { latch.countDown(); } // Logger logger = LogManager.getLogger(); - public void sleepWhileBridged() throws InterruptedException - { + 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 index bbfdeaeca..9b3ae4f07 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityDial.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityDial.java @@ -1,38 +1,33 @@ package org.asteriskjava.pbx.agi; -import java.util.concurrent.CountDownLatch; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.pbx.AgiChannelActivityAction; import org.asteriskjava.pbx.Channel; -public class AgiChannelActivityDial implements AgiChannelActivityAction -{ +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) - { + public AgiChannelActivityDial(String target, String dialOptions) { this.target = target; this.dialOptions = dialOptions; } - public AgiChannelActivityDial(String fullyQualifiedName, String sipHeader, String 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) - { + 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 @@ -47,14 +42,12 @@ public void execute(AgiChannel channel, Channel ichannel) throws AgiException, I } @Override - public boolean isDisconnect() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return false; } @Override - public void cancel() - { + 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 index dbc2bc240..6963e04cd 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHangup.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHangup.java @@ -1,7 +1,5 @@ package org.asteriskjava.pbx.agi; -import java.util.concurrent.CountDownLatch; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiHangupException; @@ -10,37 +8,32 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AgiChannelActivityHangup implements AgiChannelActivityAction -{ +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 - { + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + try { channel.hangup(); logger.info("Hungup"); - } - catch (AgiHangupException e) - { + } catch (AgiHangupException e) { // don't care } } @Override - public boolean isDisconnect() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return false; } @Override - public void cancel() - { + 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 index 308a224f3..8a80ba9eb 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHold.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHold.java @@ -1,8 +1,5 @@ package org.asteriskjava.pbx.agi; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiHangupException; @@ -11,8 +8,10 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AgiChannelActivityHold implements AgiChannelActivityAction -{ +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); @@ -20,65 +19,48 @@ public class AgiChannelActivityHold implements AgiChannelActivityAction long timer = System.currentTimeMillis(); @Override - public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException - { - try - { + 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) - { + if (secondsOnHold > 600) { logger.info(ichannel + " is still on hold after " + secondsOnHold + " seconds"); } - if (latch.await(10, TimeUnit.SECONDS)) - { - try - { + if (latch.await(10, TimeUnit.SECONDS)) { + try { channel.stopMusicOnHold(); - } - catch (AgiHangupException e) - { + } catch (AgiHangupException e) { logger.info("Channel hungup " + channel.getName()); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn(e); } - } - else - { - if (channel.getName().startsWith("Local") && secondsOnHold > 3600) - { + } 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) - { + } catch (AgiHangupException e) { logger.warn(e); } } @Override - public boolean isDisconnect() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return false; } @Override - public void cancel() - { + public void cancel() { latch.countDown(); } - public boolean hasCallReachedAgi() - { + 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 index 1be5c4506..5760a21cf 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHoldForBridge.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityHoldForBridge.java @@ -8,46 +8,37 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AgiChannelActivityHoldForBridge implements AgiChannelActivityAction -{ +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) - { + public AgiChannelActivityHoldForBridge(AgiChannelActivityBridge bridgeActivity) { this.bridgeActivity = bridgeActivity; } @Override - public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException - { - try - { + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + try { channel.playMusicOnHold(); bridgeActivity.sleepWhileBridged(); - if (hangup) - { + if (hangup) { channel.hangup(); } - } - catch (AgiHangupException e) - { + } catch (AgiHangupException e) { logger.warn(e.getMessage() + " " + channel.getName()); } } @Override - public boolean isDisconnect() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return false; } @Override - public void cancel() - { + 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 @@ -56,8 +47,7 @@ public void cancel() } - public void hangupAfterBridge(boolean b) - { + 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 index 7746b2568..3c5acad65 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityMeetme.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityMeetme.java @@ -1,8 +1,5 @@ package org.asteriskjava.pbx.agi; -import java.io.IOException; -import java.util.concurrent.CountDownLatch; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.manager.TimeoutException; @@ -15,8 +12,10 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AgiChannelActivityMeetme implements AgiChannelActivityAction -{ +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); @@ -29,31 +28,24 @@ public class AgiChannelActivityMeetme implements AgiChannelActivityAction private String userProfile; - public AgiChannelActivityMeetme(String room, String bridgeProfile, 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) - { + 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 - { + if (hangup) { + try { channel.hangup(); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn(e); } } @@ -62,26 +54,21 @@ public void execute(AgiChannel channel, Channel ichannel) throws AgiException, I } @Override - public boolean isDisconnect() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return false; } @Override - public void cancel() - { + 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 - { + try { pbx.sendAction(redirect, 1000); - } - catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) - { + } 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 index 5e4318828..f45646b22 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityPlayMessage.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityPlayMessage.java @@ -1,28 +1,24 @@ package org.asteriskjava.pbx.agi; -import java.util.concurrent.TimeUnit; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.pbx.AgiChannelActivityAction; import org.asteriskjava.pbx.Channel; -public class AgiChannelActivityPlayMessage implements AgiChannelActivityAction -{ +import java.util.concurrent.TimeUnit; + +public class AgiChannelActivityPlayMessage implements AgiChannelActivityAction { private String file; private boolean hangup = false; - public AgiChannelActivityPlayMessage(String file) - { + public AgiChannelActivityPlayMessage(String file) { this.file = file; } @Override - public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException - { - if (ichannel == null) - { + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + if (ichannel == null) { throw new NullPointerException("ichannel cannot be null"); } String tmp = file; @@ -32,12 +28,9 @@ public void execute(AgiChannel channel, Channel ichannel) throws AgiException, I // file, escape, offset, forward, rewind, pause // # to exit, 6 forward, 4 back, 5 pause - try - { + try { channel.controlStreamFile(tmp, "#", 15000, "6", "4", "5"); - } - catch (Exception e) - { + } catch (Exception e) { TimeUnit.MILLISECONDS.sleep(100); throw e; } @@ -50,14 +43,12 @@ public void execute(AgiChannel channel, Channel ichannel) throws AgiException, I } @Override - public boolean isDisconnect() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return hangup; } @Override - public void cancel() - { + 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 index 327c68314..d6d50d8dd 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityQueue.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityQueue.java @@ -1,8 +1,5 @@ package org.asteriskjava.pbx.agi; -import java.io.IOException; -import java.util.concurrent.CountDownLatch; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiHangupException; @@ -16,8 +13,10 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AgiChannelActivityQueue implements AgiChannelActivityAction -{ +import java.io.IOException; +import java.util.concurrent.CountDownLatch; + +public class AgiChannelActivityQueue implements AgiChannelActivityAction { private final Log logger = LogFactory.getLog(this.getClass()); @@ -29,29 +28,21 @@ public class AgiChannelActivityQueue implements AgiChannelActivityAction private Channel ichannel; - public AgiChannelActivityQueue(String queue) - { + public AgiChannelActivityQueue(String queue) { this.queue = queue; } @Override - public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException - { + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { this.ichannel = ichannel; channel.queue(queue); - if (hangup) - { - try - { + if (hangup) { + try { channel.hangup(); - } - catch (AgiHangupException e) - { + } catch (AgiHangupException e) { logger.warn("Channel " + channel.getName() + " hungup"); - } - catch (Exception e) - { + } catch (Exception e) { logger.warn(e); } } @@ -60,14 +51,12 @@ public void execute(AgiChannel channel, Channel ichannel) throws AgiException, I } @Override - public boolean isDisconnect() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return false; } @Override - public void cancel() - { + public void cancel() { hangup = false; final AsteriskSettings profile = PBXFactory.getActiveProfile(); @@ -75,13 +64,10 @@ public void cancel() AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); final RedirectAction redirect = new RedirectAction(ichannel, profile.getManagementContext(), pbx.getExtensionAgi(), 1); - try - { + try { pbx.sendAction(redirect, 1000); - } - catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) - { + } 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 index a488030bc..77e235a20 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityTransientHoldSilence.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityTransientHoldSilence.java @@ -1,8 +1,5 @@ package org.asteriskjava.pbx.agi; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiException; import org.asteriskjava.fastagi.AgiHangupException; @@ -11,14 +8,16 @@ 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 -{ +public class AgiChannelActivityTransientHoldSilence implements AgiChannelActivityAction { private final Log logger = LogFactory.getLog(this.getClass()); CountDownLatch latch = new CountDownLatch(1); @@ -26,48 +25,38 @@ public class AgiChannelActivityTransientHoldSilence implements AgiChannelActivit boolean firstPass = true; @Override - public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException - { - try - { + public void execute(AgiChannel channel, Channel ichannel) throws AgiException, InterruptedException { + try { callReachedAgi = true; channel.answer(); - if (!firstPass) - { + 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"); + } } - else - { - latch.await(10, TimeUnit.SECONDS); - } - } - catch (AgiHangupException e) - { + } catch (AgiHangupException e) { logger.warn(e); - } - finally - { + } finally { firstPass = false; } } @Override - public boolean isDisconnect() - { + public boolean isDisconnect(ActivityAgi activityAgi) { return false; } @Override - public void cancel() - { + public void cancel() { latch.countDown(); } - public boolean hasCallReachedAgi() - { + 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 index 560b35c48..c47945720 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityVoicemail.java +++ b/src/main/java/org/asteriskjava/pbx/agi/AgiChannelActivityVoicemail.java @@ -5,33 +5,28 @@ 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() - { - // TODO Auto-generated method stub - return false; - } - - @Override - public void cancel() - { - // TODO Auto-generated method stub - - } - // Logger logger = LogManager.getLogger(); +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/RateLimiter.java b/src/main/java/org/asteriskjava/pbx/agi/RateLimiter.java deleted file mode 100644 index 0efadab42..000000000 --- a/src/main/java/org/asteriskjava/pbx/agi/RateLimiter.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.asteriskjava.pbx.agi; - -import java.util.LinkedList; -import java.util.List; - -public class RateLimiter -{ - private static final long ONE_THOUSAND_MILLIS = 1000L; - List available = new LinkedList<>(); - - /** - * this is NOT thread safe! - * - * @param perSecond - number of 'acquire()' calls allowed per second, a call - * to acquire() will block(sleep) if the per second limit is - * exceeded - */ - RateLimiter(int perSecond) - { - long now = System.currentTimeMillis(); - for (int i = 0; i < perSecond; i++) - { - available.add(now - ONE_THOUSAND_MILLIS); - } - } - - void acquire() throws InterruptedException - { - long now = System.currentTimeMillis(); - Long next = available.remove(0); - long timeRemaining = next - now; - if (timeRemaining > 0) - { - Thread.sleep(timeRemaining); - } - available.add(System.currentTimeMillis() + ONE_THOUSAND_MILLIS); - } -} diff --git a/src/main/java/org/asteriskjava/pbx/agi/config/AgiConfiguration.java b/src/main/java/org/asteriskjava/pbx/agi/config/AgiConfiguration.java index 14bbd70e1..6c107d824 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/config/AgiConfiguration.java +++ b/src/main/java/org/asteriskjava/pbx/agi/config/AgiConfiguration.java @@ -2,9 +2,8 @@ import java.util.List; -public interface AgiConfiguration -{ +public interface AgiConfiguration { - List> getAgiHandlers(); + 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 index 3f1bf3038..ccd8cf424 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/config/AgiMappingStragegy.java +++ b/src/main/java/org/asteriskjava/pbx/agi/config/AgiMappingStragegy.java @@ -1,33 +1,28 @@ /* * 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 java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - import org.asteriskjava.fastagi.AgiChannel; import org.asteriskjava.fastagi.AgiRequest; import org.asteriskjava.fastagi.AgiScript; @@ -35,34 +30,34 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AgiMappingStragegy implements MappingStrategy -{ +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) - { + public AgiScript determineScript(AgiRequest request, AgiChannel channel) { AgiScript ret = null; String script = request.getScript(); - if (script.indexOf(".") != -1) - { + if (script.indexOf(".") != -1) { script = script.substring(0, script.indexOf(".")); } - if (script.startsWith("/")) - { + 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()) - { + while (itr.hasNext()) { String key = itr.next(); String val = request.getParameter(key); if (key.compareToIgnoreCase("cardNumber") == 0) @@ -71,15 +66,11 @@ public AgiScript determineScript(AgiRequest request, AgiChannel channel) } logger.debug("******"); - if (handlers.containsKey(script)) - { - try - { + if (handlers.containsKey(script)) { + try { ret = handlers.get(script).getDeclaredConstructor().newInstance(); - } - catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException - | InstantiationException | IllegalAccessException e) - { + } catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException + | InstantiationException | IllegalAccessException e) { logger.error(e, e); } @@ -91,7 +82,7 @@ public AgiScript determineScript(AgiRequest request, AgiChannel channel) /** * 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 @@ -102,23 +93,20 @@ public AgiScript determineScript(AgiRequest request, AgiChannel channel) * @throws IllegalArgumentException */ @SuppressWarnings("unchecked") - public void addServiceAgiScript(Class< ? extends ServiceAgiScript> handler) + public void addServiceAgiScript(Class handler) throws DuplicateScriptException, InstantiationException, IllegalAccessException, IllegalArgumentException, - InvocationTargetException, NoSuchMethodException, SecurityException - { + InvocationTargetException, NoSuchMethodException, SecurityException { logger.info("loading agi handler {}" + handler.getCanonicalName()); ServiceAgiScript tmpHandler = handler.getDeclaredConstructor().newInstance(); - if (handlers.containsKey(tmpHandler.getScriptName())) - { + 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++) - { + for (int i = 0; i < parameters.length; i++) { logger.info("parameter: " + parameters[i]); if (i == 0) sample += "?" + parameters[i] + "=testdata"; diff --git a/src/main/java/org/asteriskjava/pbx/agi/config/ConfiguableAGIServer.java b/src/main/java/org/asteriskjava/pbx/agi/config/ConfiguableAGIServer.java index aeccd167e..aef536075 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/config/ConfiguableAGIServer.java +++ b/src/main/java/org/asteriskjava/pbx/agi/config/ConfiguableAGIServer.java @@ -1,19 +1,19 @@ /* - * Copyright 2004-2006 by S. Brett Sutton. + * 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 + * 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 + * + * 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 * @@ -22,20 +22,17 @@ */ package org.asteriskjava.pbx.agi.config; -import java.lang.reflect.InvocationTargetException; -import java.util.List; +import org.asteriskjava.fastagi.DefaultAgiServer; import javax.naming.ConfigurationException; +import java.lang.reflect.InvocationTargetException; +import java.util.List; -import org.asteriskjava.fastagi.DefaultAgiServer; - -public class ConfiguableAGIServer extends DefaultAgiServer implements Runnable -{ +public class ConfiguableAGIServer extends DefaultAgiServer implements Runnable { public ConfiguableAGIServer(AgiConfiguration configuration) throws DuplicateScriptException, InstantiationException, IllegalAccessException, ConfigurationException, - IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException - { + IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { AgiMappingStragegy mappingStrategy = new AgiMappingStragegy(); setMaximumPoolSize(500); loadHandlers(mappingStrategy, configuration); @@ -47,11 +44,9 @@ public ConfiguableAGIServer(AgiConfiguration configuration) private void loadHandlers(AgiMappingStragegy mappingStrategy, AgiConfiguration configuration) throws DuplicateScriptException, InstantiationException, IllegalAccessException, IllegalArgumentException, - InvocationTargetException, NoSuchMethodException, SecurityException - { - List> handlers = configuration.getAgiHandlers(); - for (Class< ? extends ServiceAgiScript> clazz : handlers) - { + 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 index 9221273aa..ed091c99f 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/config/DuplicateScriptException.java +++ b/src/main/java/org/asteriskjava/pbx/agi/config/DuplicateScriptException.java @@ -1,14 +1,12 @@ package org.asteriskjava.pbx.agi.config; -public class DuplicateScriptException extends Exception -{ - public DuplicateScriptException(String string) - { - super(string); +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 index 23f29de2d..ffb52f82b 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScript.java +++ b/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScript.java @@ -2,8 +2,7 @@ import org.asteriskjava.fastagi.AgiScript; -public interface ServiceAgiScript extends AgiScript -{ +public interface ServiceAgiScript extends AgiScript { String getScriptName(); diff --git a/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScriptImpl.java b/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScriptImpl.java index 286114f7e..16f865b6e 100644 --- a/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScriptImpl.java +++ b/src/main/java/org/asteriskjava/pbx/agi/config/ServiceAgiScriptImpl.java @@ -15,17 +15,15 @@ *
    * 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 -{ +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 - { + public synchronized void service(AgiRequest request, AgiChannel channel) throws AgiException { this.request = request; this.channel = channel; service(); @@ -34,21 +32,19 @@ public synchronized void service(AgiRequest request, AgiChannel channel) throws /** * 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 - { + 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 - { + protected String getParameter(String name) throws AgiException { return required(name, request.getParameter(name)); } 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 index 04c33680a..30f7a8f62 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/AbstractManagerAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/AbstractManagerAction.java @@ -5,18 +5,16 @@ /** * Automatically generates a globally unique action id (based on the systems mac * address - * + * * @author bsutton */ -abstract public class AbstractManagerAction implements ManagerAction -{ +abstract public class AbstractManagerAction implements ManagerAction { private final static AtomicLong _nextActionId = new AtomicLong(); private final String _actionId = "" + _nextActionId.incrementAndGet(); - public String getActionId() - { + 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 index 2961cf4bb..b0bd14a69 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/BridgeAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/BridgeAction.java @@ -2,30 +2,26 @@ import org.asteriskjava.pbx.Channel; -public class BridgeAction extends AbstractManagerAction -{ +public class BridgeAction extends AbstractManagerAction { - private final Channel _lhs; - private final Channel _rhs; + private final Channel _lhs; + private final Channel _rhs; - public BridgeAction(final Channel lhs, final Channel rhs) - { - this._lhs = lhs; - this._rhs = 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; - } + @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$ - } + 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 index 2c6b37988..128fa5b44 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/CommandAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/CommandAction.java @@ -1,32 +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$ - } +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 index af3535b0e..7be64573b 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ConfbridgeListAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ConfbridgeListAction.java @@ -2,19 +2,16 @@ import org.asteriskjava.manager.action.ManagerAction; -public class ConfbridgeListAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class ConfbridgeListAction extends AbstractManagerAction implements EventGeneratingAction { @Override - public ManagerAction getAJAction() - { + public ManagerAction getAJAction() { return new org.asteriskjava.manager.action.ConfbridgeListAction(); } // Logger logger = LogManager.getLogger(); @Override - public org.asteriskjava.manager.action.EventGeneratingAction getAJEventGeneratingAction() - { + 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 index 75ef3a8b5..549cc25d6 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/DbGetAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/DbGetAction.java @@ -2,32 +2,28 @@ 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$ - } +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 index 2f554fca3..781c11b44 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/EventGeneratingAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/EventGeneratingAction.java @@ -1,8 +1,7 @@ package org.asteriskjava.pbx.asterisk.wrap.actions; -public interface EventGeneratingAction -{ +public interface EventGeneratingAction { - org.asteriskjava.manager.action.EventGeneratingAction getAJEventGeneratingAction(); + 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 index a222726be..1680df51f 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/GetVarAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/GetVarAction.java @@ -2,32 +2,28 @@ 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$ - } +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 index 8bcf97441..bbbcfdc73 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/HangupAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/HangupAction.java @@ -2,36 +2,31 @@ 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$ - } +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 index cd2c77a1a..df9d7f195 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ListCommandsAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ListCommandsAction.java @@ -1,19 +1,16 @@ package org.asteriskjava.pbx.asterisk.wrap.actions; -public class ListCommandsAction extends AbstractManagerAction -{ +public class ListCommandsAction extends AbstractManagerAction { @Override - public org.asteriskjava.manager.action.ManagerAction getAJAction() - { + 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() - { + 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 index a573d7c0d..66dd34fbf 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ManagerAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/ManagerAction.java @@ -1,9 +1,8 @@ package org.asteriskjava.pbx.asterisk.wrap.actions; -public interface ManagerAction -{ +public interface ManagerAction { - // Converts an iManagerAction into an asterisk-java ManagerAction. - org.asteriskjava.manager.action.ManagerAction getAJAction(); + // 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 index 7d7c1a6cf..521a68804 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/MonitorAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/MonitorAction.java @@ -2,35 +2,31 @@ 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$ - } +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 index 2c507d8b5..75184235c 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/OriginateAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/OriginateAction.java @@ -1,14 +1,13 @@ package org.asteriskjava.pbx.asterisk.wrap.actions; -import java.util.Map; - import org.asteriskjava.pbx.CallerID; import org.asteriskjava.pbx.Channel; import org.asteriskjava.pbx.EndPoint; import org.asteriskjava.pbx.internal.asterisk.CallerIDImpl; -public class OriginateAction extends AbstractManagerAction -{ +import java.util.Map; + +public class OriginateAction extends AbstractManagerAction { /** * Asterisk uses the term channel but it actually appears to be an endpoint @@ -39,26 +38,22 @@ public class OriginateAction extends AbstractManagerAction private String channelId; private String otherChannelId; - public OriginateAction() - { + public OriginateAction() { } - public String toString() - { + 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() - { + 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) - { + if (this._option != null) { channel += this._option; } action.setChannel((channel)); @@ -77,87 +72,71 @@ public org.asteriskjava.manager.action.ManagerAction getAJAction() return action; } - public void setEndPoint(final EndPoint endPoint) - { + public void setEndPoint(final EndPoint endPoint) { this._endPoint = endPoint; this._channel = null; } - public void setChannel(Channel channel) - { + public void setChannel(Channel channel) { this._channel = channel; this._endPoint = null; } - public void setOption(final String option) - { + public void setOption(final String option) { this._option = option; } - public void setContext(final String context) - { + public void setContext(final String context) { this._context = context; } - public void setExten(final EndPoint extension) - { + public void setExten(final EndPoint extension) { this._extension = extension; } - public void setPriority(final int priority) - { + public void setPriority(final int priority) { this._priority = priority; } - public void setCallingPres(final int callingPres) - { + public void setCallingPres(final int callingPres) { this._callingPres = callingPres; } - public void setCallerId(final CallerID callerID) - { + public void setCallerId(final CallerID callerID) { this._callerID = callerID; } - public void setVariables(final Map variables) - { - if (_variables == null) - { + public void setVariables(final Map variables) { + if (_variables == null) { this._variables = variables; - } - else - { + } else { this._variables.putAll(variables); } } - public void setAsync(final boolean async) - { + public void setAsync(final boolean async) { this._async = async; } - public void setTimeout(final long timeout) - { + public void setTimeout(final long timeout) { this._timeout = timeout; } - public void setChannelId(String channelId) - { + public void setChannelId(String channelId) { this.channelId = channelId; } - public void setOtherChannelId(String otherChannelId) - { + 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 index 320526670..9c2e46b02 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PingAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PingAction.java @@ -1,18 +1,15 @@ package org.asteriskjava.pbx.asterisk.wrap.actions; -public class PingAction extends AbstractManagerAction -{ +public class PingAction extends AbstractManagerAction { @Override - public org.asteriskjava.manager.action.ManagerAction getAJAction() - { + 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() - { + 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 index 59218af9e..7c0082fc5 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PlayDtmfAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/PlayDtmfAction.java @@ -4,32 +4,28 @@ 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$ - } +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 index 52805adfa..d2dd82d2f 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/RedirectAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/RedirectAction.java @@ -3,8 +3,7 @@ import org.asteriskjava.pbx.Channel; import org.asteriskjava.pbx.EndPoint; -public class RedirectAction extends AbstractManagerAction -{ +public class RedirectAction extends AbstractManagerAction { private final Channel _channel; private final String _context; @@ -15,18 +14,14 @@ public class RedirectAction extends AbstractManagerAction private EndPoint _extraExten; private Integer _extraPriority; - public RedirectAction(final Channel channel, final String context, final EndPoint extension, final int priority) - { - if (channel == null) - { + 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) - { + if (context == null) { throw new NullPointerException("context cannot be null"); } - if (extension == null) - { + if (extension == null) { throw new NullPointerException("extension cannot be null"); } @@ -37,8 +32,7 @@ public RedirectAction(final Channel channel, final String context, final EndPoin } @Override - public String toString() - { + 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$ @@ -47,8 +41,7 @@ public String toString() } @Override - public org.asteriskjava.manager.action.ManagerAction getAJAction() - { + 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()); @@ -65,23 +58,19 @@ public org.asteriskjava.manager.action.ManagerAction getAJAction() return action; } - public void setExtraChannel(final Channel extraChannel) - { + public void setExtraChannel(final Channel extraChannel) { this._extraChannel = extraChannel; } - public void setExtraContext(final String extraContext) - { + public void setExtraContext(final String extraContext) { this._extraContext = extraContext; } - public void setExtraExten(final EndPoint extraExten) - { + public void setExtraExten(final EndPoint extraExten) { this._extraExten = extraExten; } - public void setExtraPriority(final int priority) - { + 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 index 4f89aa5a4..9657f32aa 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SetVarAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SetVarAction.java @@ -2,41 +2,36 @@ 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$ - } +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 index b24ee11be..4ff04c8f0 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipPeersAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipPeersAction.java @@ -1,29 +1,24 @@ package org.asteriskjava.pbx.asterisk.wrap.actions; -public class SipPeersAction extends AbstractManagerAction implements EventGeneratingAction -{ +public class SipPeersAction extends AbstractManagerAction implements EventGeneratingAction { - public SipPeersAction() - { - } + public SipPeersAction() { + } - @Override - public org.asteriskjava.manager.action.ManagerAction getAJAction() - { - return new org.asteriskjava.manager.action.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; - } + @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$ - } + 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 index f29bbfd1c..1b524b8e1 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipShowPeerAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/SipShowPeerAction.java @@ -3,28 +3,24 @@ import org.asteriskjava.manager.action.ManagerAction; import org.asteriskjava.pbx.EndPoint; -public class SipShowPeerAction extends AbstractManagerAction -{ +public class SipShowPeerAction extends AbstractManagerAction { - private final EndPoint _peer; + private final EndPoint _peer; - public SipShowPeerAction(final EndPoint peer) - { - this._peer = 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; - } + @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$ - } + 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 index 8a10e941c..be7ab9b1f 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/StatusAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/StatusAction.java @@ -5,50 +5,44 @@ 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$ - } +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 index ad8c045bb..9ef4d54fb 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/UserEventAction.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/actions/UserEventAction.java @@ -2,23 +2,19 @@ import org.asteriskjava.pbx.asterisk.wrap.userEvents.UserEvent; -abstract public class UserEventAction extends AbstractManagerAction -{ +abstract public class UserEventAction extends AbstractManagerAction { private String _actionId; - public UserEventAction(UserEvent event) - { + public UserEventAction(UserEvent event) { // NOOP } - public void setActionId(String actionId) - { + public void setActionId(String actionId) { this._actionId = actionId; } - public String getActionId() - { + 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 index 8e192da87..477f58890 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractChannelStateEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractChannelStateEvent.java @@ -4,8 +4,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public abstract class AbstractChannelStateEvent extends ChannelEventHelper -{ +public abstract class AbstractChannelStateEvent extends ChannelEventHelper { private static final long serialVersionUID = 1L; @@ -15,20 +14,17 @@ public abstract class AbstractChannelStateEvent extends ChannelEventHelper private final ChannelState channelState; private final String channelStateDesc; - AbstractChannelStateEvent(final org.asteriskjava.manager.event.AbstractChannelStateEvent event) throws InvalidChannelName - { + 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() - { + public ChannelState getChannelState() { return this.channelState; } - public String getChannelStateDesc() - { + 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 index 0984a2ab7..723a080ed 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractMeetMeEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractMeetMeEvent.java @@ -4,8 +4,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AbstractMeetMeEvent extends ChannelEventHelper -{ +public class AbstractMeetMeEvent extends ChannelEventHelper { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") @@ -14,20 +13,17 @@ public class AbstractMeetMeEvent extends ChannelEventHelper private final String meetMe; private final Integer userNum; - public AbstractMeetMeEvent(final org.asteriskjava.manager.event.AbstractMeetMeEvent event) throws InvalidChannelName - { + 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() - { + public String getMeetMe() { return this.meetMe; } - public Integer getUserNum() - { + 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 index 25902d984..921424b68 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractParkedCallEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AbstractParkedCallEvent.java @@ -4,8 +4,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AbstractParkedCallEvent extends ChannelEventHelper -{ +public class AbstractParkedCallEvent extends ChannelEventHelper { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") @@ -14,20 +13,17 @@ public class AbstractParkedCallEvent extends ChannelEventHelper private final String exten; private final String parkingLot; - AbstractParkedCallEvent(final org.asteriskjava.manager.event.AbstractParkedCallEvent event) throws InvalidChannelName - { + 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() - { + public String getExten() { return this.exten; } - public String getParkingLot() - { + 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 index 1b03387a6..e06daa5cd 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentCalledEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentCalledEvent.java @@ -4,8 +4,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AgentCalledEvent extends ChannelEventHelper -{ +public class AgentCalledEvent extends ChannelEventHelper { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") @@ -15,21 +14,18 @@ public class AgentCalledEvent extends ChannelEventHelper private String agentInterface; - public AgentCalledEvent(final org.asteriskjava.manager.event.AgentCalledEvent event) throws InvalidChannelName - { + 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() - { + public String getQueueName() { return queue; } - public String getAgentInterface() - { + 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 index 50fcf1f99..73095025c 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentConnectEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/AgentConnectEvent.java @@ -4,8 +4,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class AgentConnectEvent extends ChannelEventHelper -{ +public class AgentConnectEvent extends ChannelEventHelper { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") @@ -15,21 +14,18 @@ public class AgentConnectEvent extends ChannelEventHelper private String agentInterface; - public AgentConnectEvent(final org.asteriskjava.manager.event.AgentConnectEvent event) throws InvalidChannelName - { + 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() - { + public String getQueueName() { return queue; } - public String getAgentInterface() - { + 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 index 2e12b2e24..9f4689383 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BlindTransferEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BlindTransferEvent.java @@ -1,7 +1,5 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -import java.util.Date; - import org.asteriskjava.pbx.Channel; import org.asteriskjava.pbx.InvalidChannelName; import org.asteriskjava.pbx.PBXFactory; @@ -9,8 +7,9 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class BlindTransferEvent extends ManagerEvent -{ +import java.util.Date; + +public class BlindTransferEvent extends ManagerEvent { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") @@ -22,8 +21,7 @@ public class BlindTransferEvent extends ManagerEvent private final Channel transfererChannel; - public BlindTransferEvent(final org.asteriskjava.manager.event.BlindTransferEvent event) throws InvalidChannelName - { + public BlindTransferEvent(final org.asteriskjava.manager.event.BlindTransferEvent event) throws InvalidChannelName { super(event); rawEvent = event; @@ -34,293 +32,235 @@ public BlindTransferEvent(final org.asteriskjava.manager.event.BlindTransferEven } - public String getBridgeUniqueId() - { + public String getBridgeUniqueId() { return rawEvent.getBridgeUniqueId(); } - public String getBridgeType() - { + public String getBridgeType() { return rawEvent.getBridgeType(); } - public Integer getBridgeNumChannels() - { + public Integer getBridgeNumChannels() { return rawEvent.getBridgeNumChannels(); } - public String getBridgeCreator() - { + public String getBridgeCreator() { return rawEvent.getBridgeCreator(); } - public String getBridgeName() - { + public String getBridgeName() { return rawEvent.getBridgeName(); } - public String getBridgeTechnology() - { + public String getBridgeTechnology() { return rawEvent.getBridgeTechnology(); } - public String getCallerIdName() - { + public String getCallerIdName() { return rawEvent.getCallerIdName(); } - public String getAccountCode() - { + public String getAccountCode() { return rawEvent.getAccountCode(); } - public String getBridgevideosourcemode() - { + public String getBridgevideosourcemode() { return rawEvent.getBridgevideosourcemode(); } - public String getConnectedLineNum() - { + public String getConnectedLineNum() { return rawEvent.getConnectedLineNum(); } - public String getConnectedLineName() - { + public String getConnectedLineName() { return rawEvent.getConnectedLineName(); } - public Integer getPriority() - { + public Integer getPriority() { return rawEvent.getPriority(); } - public Integer getChannelState() - { + public Integer getChannelState() { return rawEvent.getChannelState(); } - public String getChannelStateDesc() - { + public String getChannelStateDesc() { return rawEvent.getChannelStateDesc(); } - public String getExten() - { + public String getExten() { return rawEvent.getExten(); } - public String getCallerIdNum() - { + public String getCallerIdNum() { return rawEvent.getCallerIdNum(); } - public String getContext() - { + public String getContext() { return rawEvent.getContext(); } - public Date getDateReceived() - { + public Date getDateReceived() { return rawEvent.getDateReceived(); } - public String getPrivilege() - { + public String getPrivilege() { return rawEvent.getPrivilege(); } - public String getExtension() - { + public String getExtension() { return rawEvent.getExtension(); } - public String getIsexternal() - { + public String getIsexternal() { return rawEvent.getIsexternal(); } - public String getResult() - { + public String getResult() { return rawEvent.getResult(); } - public final String getServer() - { + public final String getServer() { return rawEvent.getServer(); } - public String getFile() - { + public String getFile() { return rawEvent.getFile(); } - public Integer getLine() - { + public Integer getLine() { return rawEvent.getLine(); } - public String getFunc() - { + public String getFunc() { return rawEvent.getFunc(); } - public Integer getSequenceNumber() - { + public Integer getSequenceNumber() { return rawEvent.getSequenceNumber(); } - public Object getSource() - { + public Object getSource() { return rawEvent.getSource(); } - public String getTransfererUniqueId() - { + public String getTransfererUniqueId() { return rawEvent.getTransfererUniqueId(); } - public String getTransfererConnectedLineNum() - { + public String getTransfererConnectedLineNum() { return rawEvent.getTransfererConnectedLineNum(); } - public String getTransfererConnectedLineName() - { + public String getTransfererConnectedLineName() { return rawEvent.getTransfererConnectedLineName(); } - public String getTransfererCallerIdName() - { + public String getTransfererCallerIdName() { return rawEvent.getTransfererCallerIdName(); } - public String getTransfererCallerIdNum() - { + public String getTransfererCallerIdNum() { return rawEvent.getTransfererCallerIdNum(); } - public Channel getTransfererChannel() - { + public Channel getTransfererChannel() { return transfererChannel; } - public String getTransfererChannelState() - { + public String getTransfererChannelState() { return rawEvent.getTransfererChannelState(); } - public String getTransfererChannelStateDesc() - { + public String getTransfererChannelStateDesc() { return rawEvent.getTransfererChannelStateDesc(); } - public Integer getTransfererPriority() - { + public Integer getTransfererPriority() { return rawEvent.getTransfererPriority(); } - public String getTransfererContext() - { + public String getTransfererContext() { return rawEvent.getTransfererContext(); } - public String getTransfereeUniqueId() - { + public String getTransfereeUniqueId() { return rawEvent.getTransfereeUniqueId(); } - public String getTransfereeConnectedLineNum() - { + public String getTransfereeConnectedLineNum() { return rawEvent.getTransfereeConnectedLineNum(); } - public String getTransfereeConnectedLineName() - { + public String getTransfereeConnectedLineName() { return rawEvent.getTransfereeConnectedLineName(); } - public String getTransfereeCallerIdName() - { + public String getTransfereeCallerIdName() { return rawEvent.getTransfereeCallerIdName(); } - public String getTransfereeCallerIdNum() - { + public String getTransfereeCallerIdNum() { return rawEvent.getTransfereeCallerIdNum(); } - public Channel getTransfereeChannel() - { + public Channel getTransfereeChannel() { return transfereeChannel; } - public String getTransfereeChannelState() - { + public String getTransfereeChannelState() { return rawEvent.getTransfereeChannelState(); } - public String getTransfereeChannelStateDesc() - { + public String getTransfereeChannelStateDesc() { return rawEvent.getTransfereeChannelStateDesc(); } - public Integer getTransfereePriority() - { + public Integer getTransfereePriority() { return rawEvent.getTransfereePriority(); } - public final Double getTimestamp() - { + public final Double getTimestamp() { return rawEvent.getTimestamp(); } - public String getTransfereeContext() - { + public String getTransfereeContext() { return rawEvent.getTransfereeContext(); } - public String getTransfereeExten() - { + public String getTransfereeExten() { return rawEvent.getTransfereeExten(); } - public String getTransfereeLinkedId() - { + public String getTransfereeLinkedId() { return rawEvent.getTransfereeLinkedId(); } - public String getTransfererAccountCode() - { + public String getTransfererAccountCode() { return rawEvent.getTransfererAccountCode(); } - public String getTransfererExten() - { + public String getTransfererExten() { return rawEvent.getTransfererExten(); } - public String getTransfererLanguage() - { + public String getTransfererLanguage() { return rawEvent.getTransfererLanguage(); } - public String getSystemName() - { + public String getSystemName() { return rawEvent.getSystemName(); } - public String getTransfererLinkedId() - { + public String getTransfererLinkedId() { return rawEvent.getTransfererLinkedId(); } - public String getTransfereeLanguage() - { + public String getTransfereeLanguage() { return rawEvent.getTransfereeLanguage(); } - public String toString() - { + 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 index 7119db605..fd572411b 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BridgeEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/BridgeEvent.java @@ -7,15 +7,13 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class BridgeEvent extends ManagerEvent -{ +public class BridgeEvent extends ManagerEvent { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") private static final Log logger = LogFactory.getLog(BridgeEvent.class); - enum BridgeState - { + enum BridgeState { Link, Unlink } @@ -23,8 +21,7 @@ enum BridgeState private final Channel channel1; private final Channel channel2; - public BridgeEvent(final org.asteriskjava.manager.event.BridgeEvent event) throws InvalidChannelName - { + public BridgeEvent(final org.asteriskjava.manager.event.BridgeEvent event) throws InvalidChannelName { super(event); final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -33,47 +30,41 @@ public BridgeEvent(final org.asteriskjava.manager.event.BridgeEvent event) throw this.channel2 = pbx.internalRegisterChannel(event.getChannel2(), event.getUniqueId2()); } - public BridgeState getBridgeState() - { + public BridgeState getBridgeState() { return this.bridgeState; } - public Channel getChannel1() - { + public Channel getChannel1() { return this.channel1; } - public Channel getChannel2() - { + 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. + * false if they have been unlinked. * @since 1.0.0 */ - public boolean isLink() - { + 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. + * false if they have been linked. * @since 1.0.0 */ - public boolean isUnlink() - { + public boolean isUnlink() { return this.bridgeState == BridgeState.Unlink; } - public String toString() - { + 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 index 489076680..5cec903e3 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEvent.java @@ -2,7 +2,6 @@ import org.asteriskjava.pbx.Channel; -public interface ChannelEvent -{ - Channel getChannel(); +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 index 05810b560..93dbcb111 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEventHelper.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelEventHelper.java @@ -5,8 +5,7 @@ import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public abstract class ChannelEventHelper extends ManagerEvent implements ChannelEvent -{ +public abstract class ChannelEventHelper extends ManagerEvent implements ChannelEvent { private static final long serialVersionUID = 1L; /** @@ -14,50 +13,39 @@ public abstract class ChannelEventHelper extends ManagerEvent implements Channel */ private final Channel channel; - protected ChannelEventHelper(final org.asteriskjava.manager.event.AbstractChannelEvent event) throws InvalidChannelName - { + 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 - { + final String callerIdName) throws InvalidChannelName { super(""); // we must have a source but since don't have one pass - // anything. - if (channel != null) - { + // anything. + if (channel != null) { this.channel = ChannelEventHelper.registerChannel(channel, uniqueId, callerIdNum, callerIdName); - } - else - { + } else { this.channel = null; } } - public ChannelEventHelper(final String channel, final String uniqueId) throws InvalidChannelName - { + public ChannelEventHelper(final String channel, final String uniqueId) throws InvalidChannelName { super("");// we must have a source but since don't have one pass - // anything. + // anything. final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); - if (channel != null) - { + if (channel != null) { this.channel = pbx.internalRegisterChannel(channel, uniqueId); - } - else - { + } else { this.channel = null; } } @Override - public Channel getChannel() - { + 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 String callerIdName) throws InvalidChannelName { final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); final Channel channel = pbx.internalRegisterChannel(channelName, uniqueId); 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 index 57163d544..4e7414ba7 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelState.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ChannelState.java @@ -2,41 +2,34 @@ /** * Holds the state of a channel as used by NewStateEvent and NewChannelEvent. - * - * @author bsutton * + * @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$ +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; + String _text; - static ChannelState valueOfDesc(String description) - { - ChannelState theState = null; + static ChannelState valueOfDesc(String description) { + ChannelState theState = null; - for (ChannelState aState : ChannelState.values()) - { - if (aState._text.compareToIgnoreCase(description) == 0) - { - theState = aState; - break; - } - } + for (ChannelState aState : ChannelState.values()) { + if (aState._text.compareToIgnoreCase(description) == 0) { + theState = aState; + break; + } + } - return theState; + return theState; - } + } - ChannelState(String text) - { - this._text = text; - } + ChannelState(String text) { + this._text = text; + } - ChannelState() - { - this._text = this.name(); - } + ChannelState() { + this._text = this.name(); + } -} \ No newline at end of file +} 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 index a01b32ca9..e4427d66a 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListCompleteEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListCompleteEvent.java @@ -1,12 +1,10 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class ConfbridgeListCompleteEvent extends ManagerEvent -{ +public class ConfbridgeListCompleteEvent extends ManagerEvent { private static final long serialVersionUID = 1L; - public ConfbridgeListCompleteEvent(org.asteriskjava.manager.event.ConfbridgeListCompleteEvent source) - { + 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 index 5073f111b..a6e738f9f 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConfbridgeListEvent.java @@ -1,26 +1,22 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class ConfbridgeListEvent extends ResponseEvent -{ +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) - { + public ConfbridgeListEvent(org.asteriskjava.manager.event.ConfbridgeListEvent source) { super(source); conference = source.getConference(); channel = source.getChannel(); } - - public String getChannel() - { + + public String getChannel() { return channel; } - public String getConference() - { + 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 index a33a30204..08c6f7023 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConnectEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ConnectEvent.java @@ -1,7 +1,6 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class ConnectEvent extends ManagerEvent -{ +public class ConnectEvent extends ManagerEvent { private static final long serialVersionUID = 1L; /** @@ -9,14 +8,12 @@ public class ConnectEvent extends ManagerEvent */ private final String protocolIdentifier; - public ConnectEvent(final org.asteriskjava.manager.event.ConnectEvent event) - { + public ConnectEvent(final org.asteriskjava.manager.event.ConnectEvent event) { super(event); this.protocolIdentifier = event.getProtocolIdentifier(); } - public String 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 index 9939a4a40..f76c4bc2d 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DbGetResponseEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DbGetResponseEvent.java @@ -1,33 +1,28 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class DbGetResponseEvent extends ManagerEvent -{ +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) - { + 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() - { + public String getVal() { return this.val; } - public String getFamily() - { + public String getFamily() { return this.family; } - public String getKey() - { + 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 index 0585813d0..c91133940 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialBeginEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialBeginEvent.java @@ -1,14 +1,13 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -import java.util.Date; - import org.asteriskjava.pbx.Channel; import org.asteriskjava.pbx.InvalidChannelName; import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class DialBeginEvent extends ChannelEventHelper -{ +import java.util.Date; + +public class DialBeginEvent extends ChannelEventHelper { private static final long serialVersionUID = 1L; /** @@ -18,8 +17,7 @@ public class DialBeginEvent extends ChannelEventHelper final org.asteriskjava.manager.event.DialBeginEvent rawEvent; - public DialBeginEvent(final org.asteriskjava.manager.event.DialBeginEvent event) throws InvalidChannelName - { + 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(); @@ -32,221 +30,178 @@ public DialBeginEvent(final org.asteriskjava.manager.event.DialBeginEvent event) } - public String getDestination() - { + public String getDestination() { return rawEvent.getDestination(); } - public String getLanguage() - { + public String getLanguage() { return rawEvent.getLanguage(); } - public String getDestLanguage() - { + public String getDestLanguage() { return rawEvent.getDestLanguage(); } - public String getDestAccountCode() - { + public String getDestAccountCode() { return rawEvent.getDestAccountCode(); } - public String getDestLinkedId() - { + public String getDestLinkedId() { return rawEvent.getDestLinkedId(); } - public String getLinkedId() - { + public String getLinkedId() { return rawEvent.getLinkedId(); } - public String getCallerIdName() - { + public String getCallerIdName() { return rawEvent.getCallerIdName(); } - public String getConnectedLineNum() - { + public String getConnectedLineNum() { return rawEvent.getConnectedLineNum(); } - public String getConnectedLineName() - { + public String getConnectedLineName() { return rawEvent.getConnectedLineName(); } - public Integer getPriority() - { + public Integer getPriority() { return rawEvent.getPriority(); } - public Integer getChannelState() - { + public Integer getChannelState() { return rawEvent.getChannelState(); } - public String getChannelStateDesc() - { + public String getChannelStateDesc() { return rawEvent.getChannelStateDesc(); } - public String getExten() - { + public String getExten() { return rawEvent.getExten(); } - public String getCallerIdNum() - { + public String getCallerIdNum() { return rawEvent.getCallerIdNum(); } - public String getContext() - { + public String getContext() { return rawEvent.getContext(); } - public String getSubEvent() - { + public String getSubEvent() { return rawEvent.getSubEvent(); } - public Date getDateReceived() - { + public Date getDateReceived() { return rawEvent.getDateReceived(); } @SuppressWarnings("deprecation") - public String getSrc() - { + public String getSrc() { return rawEvent.getSrc(); } - public String getPrivilege() - { + public String getPrivilege() { return rawEvent.getPrivilege(); } - public final Double getTimestamp() - { + public final Double getTimestamp() { return rawEvent.getTimestamp(); } - public Channel getDestChannel() - { + public Channel getDestChannel() { return destChannel; } @SuppressWarnings("deprecation") - public String getCallerId() - { + public String getCallerId() { return rawEvent.getCallerId(); } - public final String getServer() - { + public final String getServer() { return rawEvent.getServer(); } - public String getUniqueId() - { + public String getUniqueId() { return rawEvent.getUniqueId(); } - public String getSystemName() - { + public String getSystemName() { return rawEvent.getSystemName(); } @SuppressWarnings("deprecation") - public String getSrcUniqueId() - { + public String getSrcUniqueId() { return rawEvent.getSrcUniqueId(); } - public String getFile() - { + public String getFile() { return rawEvent.getFile(); } - public String getDestUniqueId() - { + public String getDestUniqueId() { return rawEvent.getDestUniqueId(); } - public Integer getLine() - { + public Integer getLine() { return rawEvent.getLine(); } - public String getDialString() - { + public String getDialString() { return rawEvent.getDialString(); } - public String getDialStatus() - { + public String getDialStatus() { return rawEvent.getDialStatus(); } - public String getFunc() - { + public String getFunc() { return rawEvent.getFunc(); } - public Integer getSequenceNumber() - { + public Integer getSequenceNumber() { return rawEvent.getSequenceNumber(); } - public Integer getDestChannelState() - { + public Integer getDestChannelState() { return rawEvent.getDestChannelState(); } - public String getDestContext() - { + public String getDestContext() { return rawEvent.getDestContext(); } - public Integer getDestPriority() - { + public Integer getDestPriority() { return rawEvent.getDestPriority(); } - public String getDestChannelStateDesc() - { + public String getDestChannelStateDesc() { return rawEvent.getDestChannelStateDesc(); } - public String getDestExten() - { + public String getDestExten() { return rawEvent.getDestExten(); } - public String getDestConnectedLineName() - { + public String getDestConnectedLineName() { return rawEvent.getDestConnectedLineName(); } - public String getDestConnectedLineNum() - { + public String getDestConnectedLineNum() { return rawEvent.getDestConnectedLineNum(); } - public String getDestCallerIdName() - { + public String getDestCallerIdName() { return rawEvent.getDestCallerIdName(); } - public String getDestCallerIdNum() - { + public String getDestCallerIdNum() { return rawEvent.getDestCallerIdNum(); } - public Object getSource() - { + 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 index 49d5cc2d0..89632e4a5 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEndEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEndEvent.java @@ -1,14 +1,13 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -import java.util.Date; - import org.asteriskjava.pbx.Channel; import org.asteriskjava.pbx.InvalidChannelName; import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class DialEndEvent extends ChannelEventHelper -{ +import java.util.Date; + +public class DialEndEvent extends ChannelEventHelper { private static final long serialVersionUID = 1L; /** @@ -18,8 +17,7 @@ public class DialEndEvent extends ChannelEventHelper final org.asteriskjava.manager.event.DialEndEvent rawEvent; - public DialEndEvent(final org.asteriskjava.manager.event.DialEndEvent event) throws InvalidChannelName - { + 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(); @@ -32,231 +30,186 @@ public DialEndEvent(final org.asteriskjava.manager.event.DialEndEvent event) thr } - public String getDestination() - { + public String getDestination() { return rawEvent.getDestination(); } - public String getLanguage() - { + public String getLanguage() { return rawEvent.getLanguage(); } - public String getDestLanguage() - { + public String getDestLanguage() { return rawEvent.getDestLanguage(); } - public String getAccountCode() - { + public String getAccountCode() { return rawEvent.getAccountCode(); } - public String getDestAccountCode() - { + public String getDestAccountCode() { return rawEvent.getDestAccountCode(); } - public String getDestLinkedId() - { + public String getDestLinkedId() { return rawEvent.getDestLinkedId(); } - public String getLinkedId() - { + public String getLinkedId() { return rawEvent.getLinkedId(); } - public String getForward() - { + public String getForward() { return rawEvent.getForward(); } - public String getCallerIdName() - { + public String getCallerIdName() { return rawEvent.getCallerIdName(); } - public String getConnectedLineNum() - { + public String getConnectedLineNum() { return rawEvent.getConnectedLineNum(); } - public String getConnectedLineName() - { + public String getConnectedLineName() { return rawEvent.getConnectedLineName(); } - public Integer getPriority() - { + public Integer getPriority() { return rawEvent.getPriority(); } - public Integer getChannelState() - { + public Integer getChannelState() { return rawEvent.getChannelState(); } - public String getChannelStateDesc() - { + public String getChannelStateDesc() { return rawEvent.getChannelStateDesc(); } - public String getExten() - { + public String getExten() { return rawEvent.getExten(); } - public String getCallerIdNum() - { + public String getCallerIdNum() { return rawEvent.getCallerIdNum(); } - public String getContext() - { + public String getContext() { return rawEvent.getContext(); } - public String getSubEvent() - { + public String getSubEvent() { return rawEvent.getSubEvent(); } - public Date getDateReceived() - { + public Date getDateReceived() { return rawEvent.getDateReceived(); } @SuppressWarnings("deprecation") - public String getSrc() - { + public String getSrc() { return rawEvent.getSrc(); } - public String getPrivilege() - { + public String getPrivilege() { return rawEvent.getPrivilege(); } - public final Double getTimestamp() - { + public final Double getTimestamp() { return rawEvent.getTimestamp(); } - public Channel getDestChannel() - { + public Channel getDestChannel() { return destChannel; } @SuppressWarnings("deprecation") - public String getCallerId() - { + public String getCallerId() { return rawEvent.getCallerId(); } - public final String getServer() - { + public final String getServer() { return rawEvent.getServer(); } - public String getUniqueId() - { + public String getUniqueId() { return rawEvent.getUniqueId(); } - public String getSystemName() - { + public String getSystemName() { return rawEvent.getSystemName(); } @SuppressWarnings("deprecation") - public String getSrcUniqueId() - { + public String getSrcUniqueId() { return rawEvent.getSrcUniqueId(); } - public String getFile() - { + public String getFile() { return rawEvent.getFile(); } - public String getDestUniqueId() - { + public String getDestUniqueId() { return rawEvent.getDestUniqueId(); } - public Integer getLine() - { + public Integer getLine() { return rawEvent.getLine(); } - public String getDialString() - { + public String getDialString() { return rawEvent.getDialString(); } - public String getDialStatus() - { + public String getDialStatus() { return rawEvent.getDialStatus(); } - public String getFunc() - { + public String getFunc() { return rawEvent.getFunc(); } - public Integer getSequenceNumber() - { + public Integer getSequenceNumber() { return rawEvent.getSequenceNumber(); } - public Integer getDestChannelState() - { + public Integer getDestChannelState() { return rawEvent.getDestChannelState(); } - public String getDestContext() - { + public String getDestContext() { return rawEvent.getDestContext(); } - public Integer getDestPriority() - { + public Integer getDestPriority() { return rawEvent.getDestPriority(); } - public String getDestChannelStateDesc() - { + public String getDestChannelStateDesc() { return rawEvent.getDestChannelStateDesc(); } - public String getDestExten() - { + public String getDestExten() { return rawEvent.getDestExten(); } - public String getDestConnectedLineName() - { + public String getDestConnectedLineName() { return rawEvent.getDestConnectedLineName(); } - public String getDestConnectedLineNum() - { + public String getDestConnectedLineNum() { return rawEvent.getDestConnectedLineNum(); } - public String getDestCallerIdName() - { + public String getDestCallerIdName() { return rawEvent.getDestCallerIdName(); } - public String getDestCallerIdNum() - { + public String getDestCallerIdNum() { return rawEvent.getDestCallerIdNum(); } - public Object getSource() - { + 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 index e8e1ba6e2..3574bc5dd 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DialEvent.java @@ -5,8 +5,7 @@ import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class DialEvent extends ChannelEventHelper -{ +public class DialEvent extends ChannelEventHelper { private static final long serialVersionUID = 1L; /** @@ -17,8 +16,7 @@ public class DialEvent extends ChannelEventHelper private final String dialString; private final String dialStatus; - public DialEvent(final org.asteriskjava.manager.event.DialEvent event) throws InvalidChannelName - { + 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(); @@ -32,18 +30,15 @@ public DialEvent(final org.asteriskjava.manager.event.DialEvent event) throws In } - public Channel getDestination() - { + public Channel getDestination() { return this.destination; } - public String getDialString() - { + public String getDialString() { return this.dialString; } - public String getDialStatus() - { + 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 index f69fef8a6..2e457cba0 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DisconnectEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DisconnectEvent.java @@ -1,11 +1,9 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class DisconnectEvent extends ManagerEvent -{ +public class DisconnectEvent extends ManagerEvent { private static final long serialVersionUID = 1L; - public DisconnectEvent(final org.asteriskjava.manager.event.DisconnectEvent event) - { + 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 index 4e68e61a4..50ac20832 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DndStateEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/DndStateEvent.java @@ -6,8 +6,7 @@ import org.asteriskjava.pbx.internal.core.AsteriskPBX; import org.asteriskjava.pbx.internal.core.ChannelImpl; -public class DndStateEvent extends ManagerEvent implements ChannelEvent -{ +public class DndStateEvent extends ManagerEvent implements ChannelEvent { private static final long serialVersionUID = 1L; /** @@ -20,8 +19,7 @@ public class DndStateEvent extends ManagerEvent implements ChannelEvent */ private final Boolean state; - public DndStateEvent(final org.asteriskjava.manager.event.DndStateEvent event) throws InvalidChannelName - { + 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); @@ -29,13 +27,11 @@ public DndStateEvent(final org.asteriskjava.manager.event.DndStateEvent event) t } @Override - public Channel getChannel() - { + public Channel getChannel() { return this.channel; } - public Boolean getState() - { + 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 index 4c58223a8..1951b7886 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ExtensionStatusEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ExtensionStatusEvent.java @@ -1,11 +1,9 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class ExtensionStatusEvent extends ManagerEvent -{ +public class ExtensionStatusEvent extends ManagerEvent { private static final long serialVersionUID = 1L; - enum Status - { + enum Status { /** * No device INUSE or BUSY. @@ -34,18 +32,14 @@ enum Status int _status; - Status(int status) - { + Status(int status) { this._status = status; } - static Status valueOf(Integer status) - { + static Status valueOf(Integer status) { Status theStatus = null; - for (Status aStatus : Status.values()) - { - if (aStatus._status == status) - { + for (Status aStatus : Status.values()) { + if (aStatus._status == status) { theStatus = aStatus; break; } @@ -59,8 +53,7 @@ static Status valueOf(Integer status) private final String hint; private final Status status; - public ExtensionStatusEvent(final org.asteriskjava.manager.event.ExtensionStatusEvent event) - { + public ExtensionStatusEvent(final org.asteriskjava.manager.event.ExtensionStatusEvent event) { super(event); this.exten = event.getExten(); this.context = event.getContext(); @@ -68,23 +61,19 @@ public ExtensionStatusEvent(final org.asteriskjava.manager.event.ExtensionStatus this.status = Status.valueOf(event.getStatus()); } - public String getExten() - { + public String getExten() { return this.exten; } - public String getContext() - { + public String getContext() { return this.context; } - public String getHint() - { + public String getHint() { return this.hint; } - public Status getStatus() - { + 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 index e18aef5c2..144766626 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/HangupEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/HangupEvent.java @@ -5,8 +5,7 @@ import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class HangupEvent extends ManagerEvent implements ChannelEvent -{ +public class HangupEvent extends ManagerEvent implements ChannelEvent { private static final long serialVersionUID = 1L; /** @@ -18,8 +17,7 @@ public class HangupEvent extends ManagerEvent implements ChannelEvent private final String causeTxt; private final String uniqueId; - public HangupEvent(final org.asteriskjava.manager.event.HangupEvent event) throws InvalidChannelName - { + public HangupEvent(final org.asteriskjava.manager.event.HangupEvent event) throws InvalidChannelName { super(event); final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -30,29 +28,24 @@ public HangupEvent(final org.asteriskjava.manager.event.HangupEvent event) throw } - public Integer getCause() - { + public Integer getCause() { return this.cause; } - public String getCauseTxt() - { + public String getCauseTxt() { return this.causeTxt; } @Override - public Channel getChannel() - { + public Channel getChannel() { return this.channel; } - public String getUniqueId() - { + public String getUniqueId() { return this.uniqueId; } - public String toString() - { + 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 index 5a1b48f7c..13c6dfc1a 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/LinkEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/LinkEvent.java @@ -2,13 +2,11 @@ import org.asteriskjava.pbx.InvalidChannelName; -public class LinkEvent extends BridgeEvent -{ +public class LinkEvent extends BridgeEvent { private static final long serialVersionUID = 1L; @SuppressWarnings("deprecation") - public LinkEvent(final org.asteriskjava.manager.event.LinkEvent event) throws InvalidChannelName - { + 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 index 9427c1514..1f2cff256 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ManagerEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ManagerEvent.java @@ -2,12 +2,10 @@ import java.util.EventObject; -public class ManagerEvent extends EventObject -{ +public class ManagerEvent extends EventObject { private static final long serialVersionUID = 1L; - public ManagerEvent(Object source) - { + 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 index 4e8a43365..f6695509f 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MasqueradeEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MasqueradeEvent.java @@ -92,11 +92,10 @@ * 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 -{ +public class MasqueradeEvent extends ManagerEvent { private static final long serialVersionUID = 1L; private final Channel _original; @@ -107,8 +106,7 @@ public class MasqueradeEvent extends ManagerEvent private ChannelState originalState; - public MasqueradeEvent(final org.asteriskjava.manager.event.MasqueradeEvent event) throws InvalidChannelName - { + public MasqueradeEvent(final org.asteriskjava.manager.event.MasqueradeEvent event) throws InvalidChannelName { super(event); final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -120,31 +118,26 @@ public MasqueradeEvent(final org.asteriskjava.manager.event.MasqueradeEvent even /** * Returns the original channel - * + * * @return */ - public Channel getOriginal() - { + public Channel getOriginal() { return this._original; } - public Channel getClone() - { + public Channel getClone() { return this._clone; } - public ChannelState getCloneState() - { + public ChannelState getCloneState() { return this.cloneState; } - public ChannelState getOriginalState() - { + public ChannelState getOriginalState() { return this.originalState; } - public String toString() - { + 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 index d86b8b43e..54e5a1e71 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeJoinEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeJoinEvent.java @@ -5,14 +5,12 @@ import org.asteriskjava.pbx.PBX; import org.asteriskjava.pbx.PBXFactory; -public class MeetMeJoinEvent extends AbstractMeetMeEvent -{ +public class MeetMeJoinEvent extends AbstractMeetMeEvent { private static final long serialVersionUID = 1L; CallerID callerID; - public MeetMeJoinEvent(final org.asteriskjava.manager.event.MeetMeJoinEvent event) throws InvalidChannelName - { + public MeetMeJoinEvent(final org.asteriskjava.manager.event.MeetMeJoinEvent event) throws InvalidChannelName { super(event); final PBX pbx = PBXFactory.getActivePBX(); @@ -20,8 +18,7 @@ public MeetMeJoinEvent(final org.asteriskjava.manager.event.MeetMeJoinEvent even } - public CallerID getCallerID() - { + 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 index b83049fcb..45cb81e22 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeLeaveEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/MeetMeLeaveEvent.java @@ -5,15 +5,13 @@ import org.asteriskjava.pbx.PBX; import org.asteriskjava.pbx.PBXFactory; -public class MeetMeLeaveEvent extends AbstractMeetMeEvent -{ +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 - { + public MeetMeLeaveEvent(final org.asteriskjava.manager.event.MeetMeLeaveEvent event) throws InvalidChannelName { super(event); final PBX pbx = PBXFactory.getActivePBX(); @@ -22,13 +20,11 @@ public MeetMeLeaveEvent(final org.asteriskjava.manager.event.MeetMeLeaveEvent ev this.duration = event.getDuration(); } - public CallerID getCallerID() - { + public CallerID getCallerID() { return this.callerID; } - public Long getDuration() - { + 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 index eaf939e81..74df7d71a 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewChannelEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewChannelEvent.java @@ -4,16 +4,14 @@ import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class NewChannelEvent extends AbstractChannelStateEvent -{ +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 - { + public NewChannelEvent(final org.asteriskjava.manager.event.NewChannelEvent event) throws InvalidChannelName { super(event); this.accountCode = event.getAccountCode(); this.context = event.getContext(); @@ -25,23 +23,19 @@ public NewChannelEvent(final org.asteriskjava.manager.event.NewChannelEvent even } - public String getAccountCode() - { + public String getAccountCode() { return this.accountCode; } - public String getContext() - { + public String getContext() { return this.context; } - public String getExten() - { + public String getExten() { return this.exten; } - public String toString() - { + 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 index 34a6594ac..608f705c4 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewExtenEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewExtenEvent.java @@ -5,8 +5,7 @@ import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class NewExtenEvent extends ManagerEvent implements ChannelEvent -{ +public class NewExtenEvent extends ManagerEvent implements ChannelEvent { private static final long serialVersionUID = 1L; private final String context; @@ -16,8 +15,7 @@ public class NewExtenEvent extends ManagerEvent implements ChannelEvent private final Integer priority; private final Channel channel; - public NewExtenEvent(final org.asteriskjava.manager.event.NewExtenEvent event) throws InvalidChannelName - { + public NewExtenEvent(final org.asteriskjava.manager.event.NewExtenEvent event) throws InvalidChannelName { super(event); final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -29,34 +27,28 @@ public NewExtenEvent(final org.asteriskjava.manager.event.NewExtenEvent event) t this.priority = event.getPriority(); } - public String getContext() - { + public String getContext() { return this.context; } - public String getExtension() - { + public String getExtension() { return this.extension; } - public String getApplication() - { + public String getApplication() { return this.application; } - public String getAppData() - { + public String getAppData() { return this.appData; } - public Integer getPriority() - { + public Integer getPriority() { return this.priority; } @Override - public Channel getChannel() - { + 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 index e7138cfbb..e010919b4 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewStateEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/NewStateEvent.java @@ -4,23 +4,19 @@ import org.asteriskjava.pbx.InvalidChannelName; import org.asteriskjava.pbx.internal.core.ChannelProxy; -public class NewStateEvent extends AbstractChannelStateEvent -{ +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 - { + public NewStateEvent(final org.asteriskjava.manager.event.NewStateEvent event) throws InvalidChannelName { super(event); } - public Channel getDestination() - { + public Channel getDestination() { return destChannel; } - public String toString() - { + 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 index 5ae4bd8e0..ce056a3ab 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/OriginateResponseEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/OriginateResponseEvent.java @@ -1,15 +1,9 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.InvalidChannelName; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXFactory; -import org.asteriskjava.pbx.TechType; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.internal.core.ChannelImpl; -public class OriginateResponseEvent extends ResponseEvent implements ChannelEvent -{ +public class OriginateResponseEvent extends ResponseEvent implements ChannelEvent { private static final long serialVersionUID = 1L; @@ -23,8 +17,7 @@ public class OriginateResponseEvent extends ResponseEvent implements ChannelEven private final Integer reason; public OriginateResponseEvent(final org.asteriskjava.manager.event.OriginateResponseEvent event) - throws InvalidChannelName - { + throws InvalidChannelName { super(event); PBX pbx = PBXFactory.getActivePBX(); @@ -32,15 +25,12 @@ public OriginateResponseEvent(final org.asteriskjava.manager.event.OriginateResp // 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) - { + 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 - { + } else { this.endPoint = pbx.buildEndPoint(TechType.SIP, event.getChannel()); this.channel = null; } @@ -52,44 +42,36 @@ public OriginateResponseEvent(final org.asteriskjava.manager.event.OriginateResp } - public String getResponse() - { + public String getResponse() { return this.response; } - public String getContext() - { + public String getContext() { return this.context; } - public String getExten() - { + public String getExten() { return this.exten; } - public Integer getReason() - { + public Integer getReason() { return this.reason; } - public boolean isChannel() - { + public boolean isChannel() { return this.isChannel; } @Override - public Channel getChannel() - { + public Channel getChannel() { return this.channel; } - public EndPoint getEndPoint() - { + public EndPoint getEndPoint() { return this.endPoint; } - public boolean isSuccess() - { + 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 index 5426bbd03..5ebd2b5bc 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ParkedCallEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ParkedCallEvent.java @@ -6,8 +6,7 @@ import org.asteriskjava.pbx.internal.core.AsteriskPBX; import org.asteriskjava.pbx.internal.core.ChannelImpl; -public class ParkedCallEvent extends ManagerEvent -{ +public class ParkedCallEvent extends ManagerEvent { private static final long serialVersionUID = 1L; @@ -15,8 +14,7 @@ public class ParkedCallEvent extends ManagerEvent private final Integer timeout; private String exten; - public ParkedCallEvent(final org.asteriskjava.manager.event.ParkedCallEvent event) throws InvalidChannelName - { + public ParkedCallEvent(final org.asteriskjava.manager.event.ParkedCallEvent event) throws InvalidChannelName { super(event); final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -30,21 +28,18 @@ public ParkedCallEvent(final org.asteriskjava.manager.event.ParkedCallEvent even /** * The channel that parked the call. In some circumstances this can be null. - * + * * @return */ - public Channel getFromChannel() - { + public Channel getFromChannel() { return this.fromChannel; } - public Integer getTimeout() - { + public Integer getTimeout() { return this.timeout; } - public String getExten() - { + 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 index 524dfbdd2..4bab04390 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerEntryEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerEntryEvent.java @@ -5,22 +5,19 @@ import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.TechType; -public class PeerEntryEvent extends ResponseEvent -{ +public class PeerEntryEvent extends ResponseEvent { private static final long serialVersionUID = 1L; private final EndPoint peer; - public PeerEntryEvent(final org.asteriskjava.manager.event.PeerEntryEvent event) - { + 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() - { + 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 index 7fa0dc1e5..fbab23813 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerStatusEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerStatusEvent.java @@ -4,23 +4,20 @@ import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class PeerStatusEvent extends ManagerEvent -{ +public class PeerStatusEvent extends ManagerEvent { private static final long serialVersionUID = 1L; private final EndPoint peer; - public PeerStatusEvent(final org.asteriskjava.manager.event.PeerStatusEvent event) - { + 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); + // Channel.UNKNOWN_UNIQUE_ID); } - public EndPoint getPeer() - { + 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 index 3044f9468..e9f7f998c 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerlistCompleteEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/PeerlistCompleteEvent.java @@ -1,11 +1,9 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class PeerlistCompleteEvent extends ResponseEvent -{ +public class PeerlistCompleteEvent extends ResponseEvent { private static final long serialVersionUID = 1L; - public PeerlistCompleteEvent(final org.asteriskjava.manager.event.PeerlistCompleteEvent event) - { + 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 index 8c51bf203..10230480f 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/QueueCallerLeaveEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/QueueCallerLeaveEvent.java @@ -2,21 +2,18 @@ import org.asteriskjava.pbx.InvalidChannelName; -public class QueueCallerLeaveEvent extends ChannelEventHelper -{ +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 - { + 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() - { + 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 index 71424c7a9..702bfb817 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ReloadEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ReloadEvent.java @@ -1,12 +1,10 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class ReloadEvent extends ManagerEvent -{ +public class ReloadEvent extends ManagerEvent { private static final long serialVersionUID = 1L; - public ReloadEvent(final org.asteriskjava.manager.event.ReloadEvent event) - { + 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 index 9a4d88456..95f9fa13c 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/RenameEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/RenameEvent.java @@ -8,8 +8,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class RenameEvent extends ManagerEvent implements ChannelEvent -{ +public class RenameEvent extends ManagerEvent implements ChannelEvent { private static final long serialVersionUID = 1L; private static final Log logger = LogFactory.getLog(RenameEvent.class); @@ -26,8 +25,7 @@ public class RenameEvent extends ManagerEvent implements ChannelEvent private String uniqueId; - public RenameEvent(final org.asteriskjava.manager.event.RenameEvent event) throws InvalidChannelName - { + public RenameEvent(final org.asteriskjava.manager.event.RenameEvent event) throws InvalidChannelName { super(event); final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -45,24 +43,20 @@ public RenameEvent(final org.asteriskjava.manager.event.RenameEvent event) throw } @Override - public final Channel getChannel() - { + public final Channel getChannel() { return this._channel; } - public final String getNewName() - { + public final String getNewName() { return this._newName; } - public final String getUniqueId() - { + public final String getUniqueId() { return uniqueId; } @Override - public String toString() - { + 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$ 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 index 444598af5..bd29067e4 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvent.java @@ -1,26 +1,22 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class ResponseEvent extends ManagerEvent -{ +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) - { + public ResponseEvent(final org.asteriskjava.manager.event.ResponseEvent event) { super(event); this.actionId = event.getActionId(); this.internalActionId = event.getInternalActionId(); } - public String getActionId() - { + public String getActionId() { return this.actionId; } - public String getInternalActionId() - { + 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 index ba6c3dfcc..8a095bfdd 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvents.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/ResponseEvents.java @@ -3,25 +3,22 @@ import java.util.ArrayList; import java.util.Collection; -public class ResponseEvents -{ +public class ResponseEvents { - ArrayList events = new ArrayList<>(); + 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; - } + /** + * 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); + 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 index cb0d576e3..a4c6907a1 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusCompleteEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusCompleteEvent.java @@ -1,11 +1,9 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -public class StatusCompleteEvent extends ResponseEvent -{ +public class StatusCompleteEvent extends ResponseEvent { private static final long serialVersionUID = 1L; - public StatusCompleteEvent(final org.asteriskjava.manager.event.StatusCompleteEvent event) - { + 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 index 597956be9..1446400ba 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/StatusEvent.java @@ -1,16 +1,11 @@ package org.asteriskjava.pbx.asterisk.wrap.events; -import java.util.Map; - -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.DialPlanExtension; -import org.asteriskjava.pbx.InvalidChannelName; -import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class StatusEvent extends ResponseEvent implements ChannelEvent -{ +import java.util.Map; + +public class StatusEvent extends ResponseEvent implements ChannelEvent { private static final long serialVersionUID = 1L; private final Channel channel; @@ -26,8 +21,7 @@ public class StatusEvent extends ResponseEvent implements ChannelEvent private final Map variables; private final String uniqueId; - public StatusEvent(final org.asteriskjava.manager.event.StatusEvent event) throws InvalidChannelName - { + public StatusEvent(final org.asteriskjava.manager.event.StatusEvent event) throws InvalidChannelName { super(event); final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -49,63 +43,51 @@ public StatusEvent(final org.asteriskjava.manager.event.StatusEvent event) throw } @Override - public final Channel getChannel() - { + public final Channel getChannel() { return this.channel; } - public final CallerID getCallerId() - { + public final CallerID getCallerId() { return this.callerId; } - public final String getAccountCode() - { + public final String getAccountCode() { return this.accountCode; } - public final ChannelState getState() - { + public final ChannelState getState() { return this.channelState; } - public final String getChannelStateDesc() - { + public final String getChannelStateDesc() { return this.channelStateDesc; } - public final String getContext() - { + public final String getContext() { return this.context; } - public final DialPlanExtension getExtension() - { + public final DialPlanExtension getExtension() { return this.extension; } - public final Integer getPriority() - { + public final Integer getPriority() { return this.priority; } - public final Integer getSeconds() - { + public final Integer getSeconds() { return this.seconds; } - public final Channel getBridgedChannel() - { + public final Channel getBridgedChannel() { return this.bridgedChannel; } - public final Map getVariables() - { + public final Map getVariables() { return this.variables; } - public String getUniqueId() - { + 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 index d537291e5..3389983bd 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnlinkEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnlinkEvent.java @@ -2,13 +2,11 @@ import org.asteriskjava.pbx.InvalidChannelName; -public class UnlinkEvent extends BridgeEvent -{ +public class UnlinkEvent extends BridgeEvent { private static final long serialVersionUID = 1L; @SuppressWarnings("deprecation") - public UnlinkEvent(final org.asteriskjava.manager.event.UnlinkEvent event) throws InvalidChannelName - { + 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 index fdd0bda97..1f71857ca 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnparkedCallEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/UnparkedCallEvent.java @@ -6,22 +6,19 @@ import org.asteriskjava.pbx.internal.core.AsteriskPBX; import org.asteriskjava.pbx.internal.core.ChannelImpl; -public class UnparkedCallEvent extends AbstractParkedCallEvent -{ +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 - { + 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() - { + 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 index d4d586dbd..5df6731d6 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/VarSetEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/events/VarSetEvent.java @@ -5,8 +5,7 @@ import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class VarSetEvent extends ManagerEvent implements ChannelEvent -{ +public class VarSetEvent extends ManagerEvent implements ChannelEvent { private static final long serialVersionUID = 1L; /** @@ -18,8 +17,7 @@ public class VarSetEvent extends ManagerEvent implements ChannelEvent private String _variableValue; - public VarSetEvent(final org.asteriskjava.manager.event.VarSetEvent event) throws InvalidChannelName - { + 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()); @@ -28,18 +26,15 @@ public VarSetEvent(final org.asteriskjava.manager.event.VarSetEvent event) throw } @Override - public Channel getChannel() - { + public Channel getChannel() { return this._channel; } - public String getVariableName() - { + public String getVariableName() { return this._variableName; } - public String getVariableValue() - { + 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 index 13d6706b0..135e76138 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/CommandResponse.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/CommandResponse.java @@ -3,31 +3,27 @@ import java.util.Collections; import java.util.List; -public class CommandResponse extends ManagerResponse -{ +public class CommandResponse extends ManagerResponse { private List result; - private boolean error; + private boolean error; - public CommandResponse(org.asteriskjava.manager.response.ManagerResponse response) - { + 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(); + result = ((org.asteriskjava.manager.response.CommandResponse) response).getResult(); } else if (response instanceof org.asteriskjava.manager.response.ManagerError) { - error = true; - result = Collections.singletonList(response.getOutput()); + error = true; + result = Collections.singletonList(response.getOutput()); } } - public List getResult() - { + public List getResult() { return this.result; } - public boolean isError() - { - return error; - } + 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 index c82e5fad9..68479b634 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerError.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerError.java @@ -1,10 +1,8 @@ package org.asteriskjava.pbx.asterisk.wrap.response; -public class ManagerError extends CommandResponse -{ +public class ManagerError extends CommandResponse { - public ManagerError(org.asteriskjava.manager.response.ManagerResponse error) - { + 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 index c035eb46c..bd5715997 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerResponse.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/response/ManagerResponse.java @@ -1,92 +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; -import org.asteriskjava.manager.response.ManagerError; -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$ - } +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 index 24bfc3078..d9dada2b9 100644 --- a/src/main/java/org/asteriskjava/pbx/asterisk/wrap/userEvents/UserEvent.java +++ b/src/main/java/org/asteriskjava/pbx/asterisk/wrap/userEvents/UserEvent.java @@ -6,28 +6,24 @@ import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; import org.asteriskjava.pbx.internal.core.AsteriskPBX; -public class UserEvent extends ManagerEvent -{ +public class UserEvent extends ManagerEvent { private static final long serialVersionUID = 1L; private Channel channel; - public UserEvent(org.asteriskjava.manager.event.UserEvent source, 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 - { + 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() - { + 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 index b12d012e1..fb490819d 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/ActivityHelper.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/ActivityHelper.java @@ -1,15 +1,7 @@ package org.asteriskjava.pbx.internal.activity; -import java.util.HashSet; -import java.util.Set; - -import org.asteriskjava.pbx.Activity; -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.ActivityStatusEnum; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +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; @@ -18,8 +10,10 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public abstract class ActivityHelper implements Runnable, Activity -{ +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); /** @@ -41,46 +35,37 @@ public abstract class ActivityHelper implements Runnable, Ac Exception callSite = new Exception("Invoked from here"); - public ActivityHelper(final String activityName, final ActivityCallback callback) - { + public ActivityHelper(final String activityName, final ActivityCallback callback) { this.callback = callback; this.activityName = activityName; } - private AutoCloseable getManagerListener() - { - if (!_sendEvents) - { - return new AutoCloseable() - { + private AutoCloseable getManagerListener() { + if (!_sendEvents) { + return new AutoCloseable() { @Override - public void close() throws Exception - { + public void close() throws Exception { // do nothing, we never started anything } }; } - EventListenerBaseClass listener = new EventListenerBaseClass(activityName, PBXFactory.getActivePBX()) - { + EventListenerBaseClass listener = new EventListenerBaseClass(activityName, PBXFactory.getActivePBX()) { @Override - public Set> requiredEvents() - { + public Set> requiredEvents() { return ActivityHelper.this.requiredEvents(); } @Override - public void onManagerEvent(ManagerEvent event) - { + public void onManagerEvent(ManagerEvent event) { ActivityHelper.this.onManagerEvent(event); } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ActivityHelper.this.getPriority(); } }; @@ -90,11 +75,9 @@ public ListenerPriority getPriority() } @SuppressWarnings("unchecked") - public void startActivity(final boolean sendEvents) - { + public void startActivity(final boolean sendEvents) { this._sendEvents = sendEvents; - if (this.callback != null) - { + if (this.callback != null) { this.callback.progress((T) this, ActivityStatusEnum.START, ActivityStatusEnum.START.getDefaultMessage()); } @@ -106,35 +89,23 @@ public void startActivity(final boolean sendEvents) @Override @SuppressWarnings("unchecked") - public void run() - { - try (AutoCloseable closer = getManagerListener()) - { + public void run() { + try (AutoCloseable closer = getManagerListener()) { this._success = this.doActivity(); - } - catch (final PBXException e) - { + } catch (final PBXException e) { this.lastException = e; ActivityHelper.logger.error(e, e); logger.error(callSite, callSite); - } - catch (final Throwable e) - { + } 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) - { + } finally { + if (this.callback != null) { + if (this._success) { this.callback.progress((T) this, ActivityStatusEnum.SUCCESS, ActivityStatusEnum.SUCCESS.getDefaultMessage()); - } - else - { + } else { // This went badly so make certain we hang everything up this.callback.progress((T) this, ActivityStatusEnum.FAILURE, ActivityStatusEnum.FAILURE.getDefaultMessage()); @@ -150,25 +121,20 @@ public void run() * 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) - { + public boolean validateChannel(final Channel channel) { boolean ret = false; final SetVarAction var = new SetVarAction(channel, "testState", "1"); ManagerResponse response = null; - try - { + try { AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); response = pbx.sendAction(var, 500); - } - catch (final Exception e) - { + } catch (final Exception e) { ActivityHelper.logger.debug(e, e); ActivityHelper.logger.error("getVariable: " + e); } - if ((response != null) && (response.getAttribute("Response").compareToIgnoreCase("success") == 0)) - { + if ((response != null) && (response.getAttribute("Response").compareToIgnoreCase("success") == 0)) { ret = true; } @@ -177,29 +143,25 @@ public boolean validateChannel(final Channel channel) } @Override - public boolean isSuccess() - { + public boolean isSuccess() { return this._success; } - protected void setLastException(final PBXException e) - { + protected void setLastException(final PBXException e) { this.lastException = e; } @Override - public Throwable getLastException() - { + public Throwable getLastException() { return this.lastException; } - public void progess(final T activity, final String message) - { + public void progess(final T activity, final String message) { this.callback.progress(activity, ActivityStatusEnum.PROGRESS, message); } - abstract HashSet> requiredEvents(); + abstract HashSet> requiredEvents(); abstract void onManagerEvent(final ManagerEvent event); diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/BlindTransferActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/BlindTransferActivityImpl.java index a224c4ec6..73f63ae9a 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/BlindTransferActivityImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/BlindTransferActivityImpl.java @@ -1,41 +1,28 @@ package org.asteriskjava.pbx.internal.activity; -import java.util.HashSet; -import java.util.Objects; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.Call; +import org.asteriskjava.lock.Locker.LockCloser; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.Call.OperandChannel; -import org.asteriskjava.pbx.CallDirection; -import org.asteriskjava.pbx.CallImpl; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.activities.BlindTransferActivity; import org.asteriskjava.pbx.agi.AgiChannelActivityBlindTransfer; -import org.asteriskjava.pbx.asterisk.wrap.events.BridgeEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.DialEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.HangupEvent; -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.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 -{ +public class BlindTransferActivityImpl extends ActivityHelper implements BlindTransferActivity { private static final Log logger = LogFactory.getLog(BlindTransferActivityImpl.class); private final Call _call; @@ -70,18 +57,17 @@ public class BlindTransferActivityImpl extends ActivityHelper listener, String dialOptions) - { + final CallerID toCallerID, boolean autoAnswer, long timeout, + final ActivityCallback listener, String dialOptions) { super("BlindTransferActivity", listener); this._call = Objects.requireNonNull(call); @@ -98,8 +84,7 @@ public BlindTransferActivityImpl(Call call, final Call.OperandChannel channelToT } public BlindTransferActivityImpl(Channel agentChannel, EndPoint transferTarget, CallerID toCallerID, boolean autoAnswer, - int timeout, ActivityCallback iCallback, String dialOptions) throws PBXException - { + int timeout, ActivityCallback iCallback, String dialOptions) throws PBXException { super("BlindTransferActivity", iCallback); this._transferTarget = transferTarget; @@ -115,8 +100,7 @@ public BlindTransferActivityImpl(Channel agentChannel, EndPoint transferTarget, } @Override - public boolean doActivity() throws PBXException - { + public boolean doActivity() throws PBXException { boolean success = false; AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -125,8 +109,7 @@ public boolean doActivity() throws PBXException * when a link event occurs this call will be removed from the active * call list. */ - try - { + try { logger.debug("*******************************************************************************"); logger.info("*********** begin blind transfer ****************"); @@ -135,8 +118,7 @@ public boolean doActivity() throws PBXException logger.debug("*********** " + this._toCallerID + " ****************"); logger.debug("*******************************************************************************"); - if (!pbx.moveChannelToAgi(actualChannelToTransfer)) - { + if (!pbx.moveChannelToAgi(actualChannelToTransfer)) { throw new PBXException("Channel: " + this._channelToTransfer + " couldn't be moved to agi"); } @@ -149,48 +131,50 @@ public boolean doActivity() throws PBXException // 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) - { + if (this._autoAnswer) { sipHeader = PBXFactory.getActiveProfile().getAutoAnswer(); } - actualChannelToTransfer.setCurrentActivityAction(new AgiChannelActivityBlindTransfer( - this._transferTarget.getFullyQualifiedName(), sipHeader, _toCallerID.getNumber(), dialOptions)); + + 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. - this._latch = new CountDownLatch(1); success = this._latch.await(this._timeout, TimeUnit.SECONDS); - if (!success) - { + if (!success) { this._completionCause = CompletionCause.TIMEOUT; - } - else if (_completionCause == CompletionCause.CANCELLED) - { + } else if (_completionCause == CompletionCause.CANCELLED) { logger.warn("Cancelled, hanging up dialed channel"); pbx.hangup(dialedChannel); - } - - else - { + } else { Call call = ((CallImpl) _call).split(actualChannelToTransfer); Call rhsCall = new CallImpl(_transferTargetChannel, CallDirection.OUTBOUND); - try - { + try { _newCall = ((CallImpl) call).join(OperandChannel.ORIGINATING_PARTY, rhsCall, OperandChannel.ORIGINATING_PARTY, CallDirection.OUTBOUND); - } - catch (Exception e) - { + } catch (Exception e) { logger.error("New call doesn't seem to exist!?"); } } - } - catch (final Exception e) - { + } catch (final Exception e) { logger.error("error occurred in blindtransfer", e); this.setLastException(new PBXException(e)); } @@ -199,9 +183,8 @@ else if (_completionCause == CompletionCause.CANCELLED) } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(BridgeEvent.class); required.add(LinkEvent.class); @@ -212,51 +195,39 @@ else if (_completionCause == CompletionCause.CANCELLED) } @Override - synchronized public void onManagerEvent(final ManagerEvent event) - { - 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(); + 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(); } - else if (bridge.getChannel2().isSame(_call.getOperandChannel(this._channelToTransfer))) - { - this._completionCause = CompletionCause.BRIDGED; - this._transferTargetChannel = bridge.getChannel1(); + if (hangup.getChannel().isSame(dialedChannel)) { + this._completionCause = CompletionCause.HANGUP; 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(); + } 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(); + } } } } @@ -264,14 +235,12 @@ else if (event instanceof DialEvent) } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.NORMAL; } @Override - public CompletionCause getCompletionCause() - { + public CompletionCause getCompletionCause() { return this._completionCause; } @@ -279,39 +248,33 @@ public CompletionCause getCompletionCause() * cancels the BlindTransfer. */ @Override - public void cancel() - { + public void cancel() { this._completionCause = CompletionCause.CANCELLED; this._latch.countDown(); } @Override - public Channel getChannelToTransfer() - { + public Channel getChannelToTransfer() { return _call.getOperandChannel(this._channelToTransfer); } @Override - public CallerID getTransferTargetCallerID() - { + public CallerID getTransferTargetCallerID() { return this._toCallerID; } @Override - public EndPoint getTransferTarget() - { + public EndPoint getTransferTarget() { return this._transferTarget; } @Override - public Channel getTransferTargetChannel() - { + public Channel getTransferTargetChannel() { return this._transferTargetChannel; } @Override - public Call getNewCall() throws PBXException - { + 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 index cd51e531a..0229b3499 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/BridgeActivityImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/BridgeActivityImpl.java @@ -1,30 +1,21 @@ package org.asteriskjava.pbx.internal.activity; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +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.BridgeEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.LinkEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.StatusCompleteEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.StatusEvent; +import org.asteriskjava.pbx.asterisk.wrap.events.*; import org.asteriskjava.pbx.internal.core.AsteriskPBX; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class BridgeActivityImpl extends ActivityHelper implements BridgeActivity -{ +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; @@ -32,8 +23,7 @@ public class BridgeActivityImpl extends ActivityHelper implement private CountDownLatch _bridgeLatch; public BridgeActivityImpl(final Channel lhsChannel, final Channel rhsChannel, - final ActivityCallback callback) - { + final ActivityCallback callback) { super("Bridge", callback); this._lhsChannel = lhsChannel; @@ -42,8 +32,7 @@ public BridgeActivityImpl(final Channel lhsChannel, final Channel rhsChannel, } @Override - public boolean doActivity() throws PBXException - { + public boolean doActivity() throws PBXException { boolean success = false; BridgeActivityImpl.logger.debug("*******************************************************************************"); @@ -51,17 +40,14 @@ public boolean doActivity() throws PBXException BridgeActivityImpl.logger.info("*********** lhs:" + this._lhsChannel + " ****************"); BridgeActivityImpl.logger.debug("*********** rhs:" + this._rhsChannel + " ****************"); BridgeActivityImpl.logger.debug("*******************************************************************************"); - try - { + try { final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); - if (!pbx.moveChannelToAgi(_lhsChannel)) - { + if (!pbx.moveChannelToAgi(_lhsChannel)) { throw new PBXException("Channel: " + _lhsChannel + " couldn't be moved to agi"); } - if (!pbx.moveChannelToAgi(_rhsChannel)) - { + if (!pbx.moveChannelToAgi(_rhsChannel)) { throw new PBXException("Channel: " + _rhsChannel + " couldn't be moved to agi"); } @@ -70,10 +56,8 @@ public boolean doActivity() throws PBXException 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()) - { + try { + if (pbx.isBridgeSupported()) { this._bridgeLatch = new CountDownLatch(1); final AgiChannelActivityBridge action = new AgiChannelActivityBridge(_lhsChannel); @@ -84,15 +68,11 @@ public boolean doActivity() throws PBXException success = this._bridgeLatch.await(3, TimeUnit.SECONDS); } - } - catch (IllegalArgumentException | IllegalStateException | InterruptedException e) - { + } catch (IllegalArgumentException | IllegalStateException | InterruptedException e) { throw new PBXException(e); } - } - catch (IllegalArgumentException | IllegalStateException e) - { + } catch (IllegalArgumentException | IllegalStateException e) { BridgeActivityImpl.logger.error(e, e); BridgeActivityImpl.logger.error(e, e); throw new PBXException(e); @@ -101,9 +81,8 @@ public boolean doActivity() throws PBXException } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(StatusCompleteEvent.class); required.add(StatusEvent.class); required.add(BridgeEvent.class); @@ -112,17 +91,14 @@ public boolean doActivity() throws PBXException } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.NORMAL; } @Override - public void onManagerEvent(ManagerEvent event) - { + public void onManagerEvent(ManagerEvent event) { - if (event instanceof BridgeEvent) - { + if (event instanceof BridgeEvent) { BridgeEvent bridge = (BridgeEvent) event; if (bridge.isLink() && (bridge.getChannel1().isSame(this._lhsChannel) || bridge.getChannel1().isSame(this._rhsChannel)) diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/DialActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/DialActivityImpl.java index b3e11d2bb..106fc4762 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/DialActivityImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/DialActivityImpl.java @@ -1,21 +1,6 @@ package org.asteriskjava.pbx.internal.activity; -import java.util.HashSet; -import java.util.Map; - -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.Call; -import org.asteriskjava.pbx.CallDirection; -import org.asteriskjava.pbx.CallImpl; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.NewChannelListener; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +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; @@ -26,8 +11,10 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class DialActivityImpl extends ActivityHelper implements DialActivity, NewChannelListener -{ +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; @@ -57,9 +44,8 @@ public class DialActivityImpl extends ActivityHelper implements Di private String dialOptions; public DialActivityImpl(final EndPoint originating, final EndPoint accepting, final CallerID toCallerID, - final boolean hideToCallerID, final ActivityCallback listener, - Map channelVarsToSet, String dialOptions) - { + final boolean hideToCallerID, final ActivityCallback listener, + Map channelVarsToSet, String dialOptions) { super("Dial", listener); this._originating = originating; this._accepting = accepting; @@ -73,12 +59,10 @@ public DialActivityImpl(final EndPoint originating, final EndPoint accepting, fi } @Override - public boolean doActivity() throws PBXException - { + public boolean doActivity() throws PBXException { boolean success = false; - try (Dial nr = new Dial(this.toCallerID.toString())) - { + try (Dial nr = new Dial(this.toCallerID.toString())) { DialActivityImpl.logger.debug("*******************************************************************************"); DialActivityImpl.logger.info("*********** begin dial out ****************"); DialActivityImpl.logger.info("*********** " + this._accepting + " ****************"); @@ -89,20 +73,16 @@ public boolean doActivity() throws PBXException 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)) - { + if ((resultChannels[0] == null) || (resultChannels[1] == null)) { // the dial failed // so notify the operator. // Unless the operated cancelled the call - if (!this.cancelledByOperator) - { + if (!this.cancelledByOperator) { this.setLastException(new PBXException(("OperatorEndedCall"))); DialActivityImpl.logger.error("dialout to " + this._accepting.getFullyQualifiedName() + " failed."); } - } - else - { + } else { // Dial succeeded. // - get new channel name from result @@ -113,45 +93,33 @@ public boolean doActivity() throws PBXException DialActivityImpl.logger.debug("dialout succeeded: dest channel is :" + this.acceptingChannel); - if (!this.validateChannel(this.acceptingChannel)) - { + if (!this.validateChannel(this.acceptingChannel)) { this.setLastException(new PBXException(("dialed extension hungup unexpectedly"))); DialActivityImpl.logger.error("dialed extension hungup unexpectedly"); - } - else - { + } else { success = true; } } - } - finally - { - if (!success) - { + } finally { + if (!success) { this.hangup(); } } return success; } - private void hangup() - { - try - { + private void hangup() { + try { final PBX pbx = PBXFactory.getActivePBX(); - if (this.acceptingChannel != null) - { + if (this.acceptingChannel != null) { logger.warn("Hanging up"); pbx.hangup(this.acceptingChannel); } - if (this.originatingChannel != null) - { + if (this.originatingChannel != null) { logger.warn("Hanging up"); pbx.hangup(this.originatingChannel); } - } - catch (final Exception e) - { + } catch (final Exception e) { DialActivityImpl.logger.error(e, e); } } @@ -161,45 +129,37 @@ private void hangup() * hangup the associated channels. */ @Override - public void markCancelled() - { + public void markCancelled() { this.cancelledByOperator = true; } @Override - public Channel getOriginatingChannel() - { + public Channel getOriginatingChannel() { return this.originatingChannel; } @Override - public Channel getAcceptingChannel() - { + public Channel getAcceptingChannel() { return this.acceptingChannel; } @Override - public EndPoint getOriginatingEndPoint() - { + public EndPoint getOriginatingEndPoint() { return this._originating; } @Override - public EndPoint getAcceptingEndPoint() - { + public EndPoint getAcceptingEndPoint() { return this._accepting; } @Override - public void channelUpdate(final Channel channel) - { - if (channel.sameEndPoint(this._accepting)) - { + public void channelUpdate(final Channel channel) { + if (channel.sameEndPoint(this._accepting)) { this.acceptingChannel = channel; } - if (channel.sameEndPoint(this._originating)) - { + if (channel.sameEndPoint(this._originating)) { this.originatingChannel = channel; } @@ -212,25 +172,20 @@ public void channelUpdate(final Channel channel) * @param channel the channel which is to be tested. */ @Override - public boolean validateChannel(final Channel channel) - { + public boolean validateChannel(final Channel channel) { boolean ret = false; final SetVarAction var = new SetVarAction(channel, "testState", "1"); ManagerResponse response = null; - try - { + try { AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); response = pbx.sendAction(var, 500); - } - catch (final Exception e) - { + } catch (final Exception e) { DialActivityImpl.logger.debug(e, e); DialActivityImpl.logger.error("getVariable: " + e); } - if ((response != null) && (response.getAttribute("Response").compareToIgnoreCase("success") == 0)) - { + if ((response != null) && (response.getAttribute("Response").compareToIgnoreCase("success") == 0)) { ret = true; } @@ -239,34 +194,29 @@ public boolean validateChannel(final Channel channel) } @Override - public boolean cancelledByOperator() - { + public boolean cancelledByOperator() { return this.cancelledByOperator; } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); // no required. return required; } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.NORMAL; } @Override - public void onManagerEvent(ManagerEvent event) - { + public void onManagerEvent(ManagerEvent event) { // NOOP } @Override - public Call getNewCall() - { + 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 index 46deff592..7304e5565 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/DialToAgiActivityImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/DialToAgiActivityImpl.java @@ -1,18 +1,6 @@ package org.asteriskjava.pbx.internal.activity; -import java.util.HashSet; -import java.util.Map; - -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.AgiChannelActivityAction; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.NewChannelListener; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +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; @@ -23,8 +11,10 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class DialToAgiActivityImpl extends ActivityHelper implements DialToAgiActivity, NewChannelListener -{ +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; @@ -49,9 +39,8 @@ public class DialToAgiActivityImpl extends ActivityHelper imp private Integer timeout; public DialToAgiActivityImpl(final EndPoint originating, final CallerID toCallerID, Integer timeout, - final boolean hideToCallerID, final ActivityCallback listener, - Map channelVarsToSet, AgiChannelActivityAction action) - { + final boolean hideToCallerID, final ActivityCallback listener, + Map channelVarsToSet, AgiChannelActivityAction action) { super("Dial", listener); this.timeout = timeout; this.action = action; @@ -63,18 +52,15 @@ public DialToAgiActivityImpl(final EndPoint originating, final CallerID toCaller } - public void dial() - { + public void dial() { this.startActivity(false); } @Override - public boolean doActivity() throws PBXException - { + public boolean doActivity() throws PBXException { boolean success = false; - try (DialToAgi nr = new DialToAgi(this.toCallerID.toString())) - { + try (DialToAgi nr = new DialToAgi(this.toCallerID.toString())) { DialToAgiActivityImpl.logger.debug("**************************************************************************"); DialToAgiActivityImpl.logger .info("*********** begin dial out to agi " + _originating + " ***********"); @@ -85,20 +71,16 @@ public boolean doActivity() throws PBXException final OriginateResult[] resultChannels = nr.dial(this, this._originating, this.action, this.toCallerID, this.timeout, this.hideToCallerId, channelVarsToSet); - if (resultChannels[0] == null || !resultChannels[0].isSuccess()) - { + if (resultChannels[0] == null || !resultChannels[0].isSuccess()) { // the dial failed // so notify the operator. // Unless the operated cancelled the call - if (!this.cancelledByOperator) - { + if (!this.cancelledByOperator) { this.setLastException(new PBXException(("OperatorEndedCall"))); logger.warn("dialout to " + _originating + " failed."); } - } - else - { + } else { // Dial succeeded. // - get new channel name from result @@ -109,35 +91,25 @@ public boolean doActivity() throws PBXException success = true; } - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { logger.error(e); - } - finally - { - if (!success) - { + } finally { + if (!success) { this.hangup(); } } return success; } - private void hangup() - { - try - { + private void hangup() { + try { final PBX pbx = PBXFactory.getActivePBX(); - if (this.originatingChannel != null) - { + if (this.originatingChannel != null) { logger.info("Hanging up"); pbx.hangup(this.originatingChannel); } - } - catch (final Exception e) - { + } catch (final Exception e) { DialToAgiActivityImpl.logger.error(e, e); } } @@ -147,29 +119,24 @@ private void hangup() * also hangup the trc channel. */ @Override - public void markCancelled() - { + public void markCancelled() { this.cancelledByOperator = true; } @Override - public Channel getOriginatingChannel() - { + public Channel getOriginatingChannel() { return this.originatingChannel; } @Override - public EndPoint getOriginatingEndPoint() - { + public EndPoint getOriginatingEndPoint() { return this._originating; } @Override - public void channelUpdate(final Channel channel) - { + public void channelUpdate(final Channel channel) { - if (channel.sameEndPoint(this._originating)) - { + if (channel.sameEndPoint(this._originating)) { this.originatingChannel = channel; } @@ -182,25 +149,20 @@ public void channelUpdate(final Channel channel) * @param channel the channel which is to be tested. */ @Override - public boolean validateChannel(final Channel channel) - { + public boolean validateChannel(final Channel channel) { boolean ret = false; final SetVarAction var = new SetVarAction(channel, "testState", "1"); ManagerResponse response = null; - try - { + try { AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); response = pbx.sendAction(var, 500); - } - catch (final Exception e) - { + } catch (final Exception e) { DialToAgiActivityImpl.logger.debug(e, e); DialToAgiActivityImpl.logger.error("getVariable: " + e); } - if ((response != null) && (response.getAttribute("Response").compareToIgnoreCase("success") == 0)) - { + if ((response != null) && (response.getAttribute("Response").compareToIgnoreCase("success") == 0)) { ret = true; } @@ -209,39 +171,31 @@ public boolean validateChannel(final Channel channel) } @Override - public boolean cancelledByOperator() - { + public boolean cancelledByOperator() { return this.cancelledByOperator; } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); // no required. return required; } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.NORMAL; } @Override - public void onManagerEvent(ManagerEvent event) - { + public void onManagerEvent(ManagerEvent event) { // NOOP } - public void abort() - { - if (originator != null) - { + public void abort() { + if (originator != null) { originator.abort(); - } - else - { + } 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 index f8fd68287..835cda768 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/HoldActivityImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/HoldActivityImpl.java @@ -1,12 +1,6 @@ package org.asteriskjava.pbx.internal.activity; -import java.util.HashSet; - -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.activities.HoldActivity; import org.asteriskjava.pbx.agi.AgiChannelActivityHold; import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; @@ -14,13 +8,13 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class HoldActivityImpl extends ActivityHelper implements HoldActivity -{ +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) - { + public HoldActivityImpl(final Channel channel, final ActivityCallback callback) { super("HoldCall", callback); this._channel = channel; @@ -28,29 +22,24 @@ public HoldActivityImpl(final Channel channel, final ActivityCallback> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); // no events requried. return required; } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.NORMAL; } @Override - public void onManagerEvent(ManagerEvent event) - { + 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 index 7538d1d97..fc0caacd8 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/JoinActivityImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/JoinActivityImpl.java @@ -1,35 +1,27 @@ package org.asteriskjava.pbx.internal.activity; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.Call; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.Call.OperandChannel; -import org.asteriskjava.pbx.CallDirection; -import org.asteriskjava.pbx.CallImpl; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; 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 -{ +public class JoinActivityImpl extends ActivityHelper implements JoinActivity { private static final Log logger = LogFactory.getLog(JoinActivityImpl.class); @@ -48,19 +40,18 @@ public class JoinActivityImpl extends ActivityHelper implements Jo * 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 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. + * 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) - { + OperandChannel acceptingOperand, CallDirection direction, final ActivityCallback listener) { super("JoinActivity", listener); callSite = new Exception("Call site"); @@ -71,23 +62,19 @@ public JoinActivityImpl(final Call lhsCall, OperandChannel originatingOperand, f this._acceptingOperand = acceptingOperand; this._direction = direction; - if (this._lhsCall == null) - { + if (this._lhsCall == null) { throw new IllegalArgumentException("lhsCall may not be null"); } - if (this._originatingOperand == null) - { + if (this._originatingOperand == null) { throw new IllegalArgumentException("lhsOperand may not be null"); } - if (this._rhsCall == null) - { + if (this._rhsCall == null) { throw new IllegalArgumentException("rhsCall may not be null"); } - if (this._acceptingOperand == null) - { + if (this._acceptingOperand == null) { throw new IllegalArgumentException("rhsOperand may not be null"); } @@ -95,8 +82,7 @@ public JoinActivityImpl(final Call lhsCall, OperandChannel originatingOperand, f } @Override - public boolean doActivity() throws PBXException - { + public boolean doActivity() throws PBXException { boolean success = false; final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -106,25 +92,21 @@ public boolean doActivity() throws PBXException JoinActivityImpl.logger.debug("*********** " + this._rhsCall + " ****************"); JoinActivityImpl.logger.debug("*******************************************************************************"); - try - { + try { final Channel rhsChannel = this._rhsCall.getOperandChannel(this._acceptingOperand); final Channel lhsChannel = this._lhsCall.getOperandChannel(this._originatingOperand); - if (!pbx.moveChannelToAgi(rhsChannel)) - { + if (!pbx.moveChannelToAgi(rhsChannel)) { throw new PBXException("Channel: " + rhsChannel + " couldn't be moved to agi"); } - if (!pbx.moveChannelToAgi(lhsChannel)) - { + 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)) - { + if (!pbx.waitForChannelsToQuiescent(channels, 3000)) { logger.error(callSite, callSite); throw new PBXException("Channel: " + rhsChannel + " cannot be joined as it is still in transition."); } @@ -134,9 +116,7 @@ public boolean doActivity() throws PBXException this._direction); success = true; - } - catch (RuntimeException e) - { + } catch (RuntimeException e) { logger.error(e, e); logger.error(callSite, callSite); throw new PBXException(e); @@ -146,28 +126,24 @@ public boolean doActivity() throws PBXException } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); return required; } @Override - synchronized public void onManagerEvent(final ManagerEvent event) - { + synchronized public void onManagerEvent(final ManagerEvent event) { // NOOP } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.NORMAL; } @Override - public Call getJoinedCall() - { + 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 index 5d4343a72..53000e297 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/ParkActivityImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/ParkActivityImpl.java @@ -1,21 +1,8 @@ package org.asteriskjava.pbx.internal.activity; -import java.io.IOException; -import java.util.HashSet; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - +import org.asteriskjava.lock.Locker.LockCloser; import org.asteriskjava.manager.TimeoutException; -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.Call; -import org.asteriskjava.pbx.CallDirection; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; -import org.asteriskjava.pbx.TechType; +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; @@ -25,6 +12,11 @@ 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 @@ -32,11 +24,10 @@ * 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 -{ +public class ParkActivityImpl extends ActivityHelper implements ParkActivity { private static final Log logger = LogFactory.getLog(ParkActivityImpl.class); /** @@ -59,16 +50,13 @@ public class ParkActivityImpl extends ActivityHelper implements Pa * @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) - { + public ParkActivityImpl(final Call call, final Channel parkChannel, final ActivityCallback listener) { super("ParkActivity", listener); - if (call == null) - { + if (call == null) { throw new IllegalArgumentException("call may not be null"); } - if (parkChannel == null) - { + if (parkChannel == null) { throw new IllegalArgumentException("parkChannel may not be null"); } this._parkChannel = parkChannel; @@ -81,8 +69,7 @@ public ParkActivityImpl(final Call call, final Channel parkChannel, final Activi } @Override - public boolean doActivity() throws PBXException - { + public boolean doActivity() throws PBXException { boolean success = false; final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); @@ -91,8 +78,7 @@ public boolean doActivity() throws PBXException ParkActivityImpl.logger.info("*********** " + this._parkChannel + " ****************"); ParkActivityImpl.logger.debug("*******************************************************************************"); - try - { + try { final AsteriskSettings profile = PBXFactory.getActiveProfile(); if (!pbx.waitForChannelToQuiescent(this._parkChannel, 3000)) @@ -104,50 +90,39 @@ public boolean doActivity() throws PBXException pbx.getExtensionPark(), 1); final ManagerResponse response = pbx.sendAction(redirect, 1000); - if ((response != null) && (response.getResponse().compareToIgnoreCase("success") == 0)) - { + 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) - { + if (this._call.getDirection() == CallDirection.INBOUND) { logger.warn("Hanging up"); pbx.hangup(this._call.getAcceptingParty()); - } - else - { + } else { logger.warn("Hanging up"); pbx.hangup(this._call.getOriginatingParty()); } success = true; } - } - catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) - { + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { ParkActivityImpl.logger.error(e, e); throw new PBXException(e); - } - finally - { + } finally { // we wait at most 2 seconds for the parking extension to // arrive. - try - { - if (success) - { - this._latch.await(2, TimeUnit.SECONDS); + try { + if (success) { + if (!this._latch.await(2, TimeUnit.SECONDS)) { + logger.warn("Timeout, continuing"); + } } - if (this._parkingLot == null) - { + 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) - { + } catch (final InterruptedException e) { ParkActivityImpl.logger.error(e, e); } @@ -157,15 +132,13 @@ public boolean doActivity() throws PBXException } @Override - public EndPoint getParkingLot() - { + public EndPoint getParkingLot() { return this._parkingLot; } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(ParkedCallEvent.class); @@ -173,20 +146,20 @@ public EndPoint getParkingLot() } @Override - synchronized public void onManagerEvent(final ManagerEvent event) - { - assert event instanceof ParkedCallEvent : "Unexpected event"; + 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(); + final ParkedCallEvent parkedEvent = (ParkedCallEvent) event; + final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); - this._parkingLot = pbx.buildEndPoint(TechType.LOCAL, parkedEvent.getExten()); - this._latch.countDown(); + this._parkingLot = pbx.buildEndPoint(TechType.LOCAL, parkedEvent.getExten()); + this._latch.countDown(); + } } @Override - public ListenerPriority getPriority() - { + 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 index 1ab3fa7aa..5c30dfa3a 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/RedirectToActivityImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/RedirectToActivityImpl.java @@ -1,19 +1,6 @@ package org.asteriskjava.pbx.internal.activity; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.Call; -import org.asteriskjava.pbx.CallDirection; -import org.asteriskjava.pbx.CallImpl; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.activities.RedirectToActivity; import org.asteriskjava.pbx.agi.AgiChannelActivityHold; import org.asteriskjava.pbx.asterisk.wrap.actions.RedirectAction; @@ -23,16 +10,19 @@ 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 -{ +public class RedirectToActivityImpl extends ActivityHelper implements RedirectToActivity { private static final Log logger = LogFactory.getLog(RedirectToActivityImpl.class); private Channel channel1; @@ -43,12 +33,11 @@ public class RedirectToActivityImpl extends ActivityHelper i * 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) - { + public RedirectToActivityImpl(final Channel channel1, final ActivityCallback listener) { super("SplitActivity", listener); this.channel1 = channel1; @@ -57,8 +46,7 @@ public RedirectToActivityImpl(final Channel channel1, final ActivityCallback> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); // No events required. return required; } @Override - synchronized public void onManagerEvent(final ManagerEvent event) - { + synchronized public void onManagerEvent(final ManagerEvent event) { // NOOP } @Override - public ListenerPriority getPriority() - { + 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() - { + 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 @@ -135,15 +117,13 @@ public Call getCall() * @return * @throws PBXException */ - private boolean splitTwo() 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)) - { + if (!pbx.waitForChannelsToQuiescent(channels, 3000)) { logger.error(callSite, callSite); throw new PBXException("Channel: " + channel1 + " cannot be split as they are still in transition."); } @@ -169,27 +149,22 @@ private boolean splitTwo() throws PBXException boolean ret = false; { - try - { + try { // final ManagerResponse response = pbx.sendAction(redirect, 1000); double ctr = 0; - while (!agi1.hasCallReachedAgi() && ctr < 10) - { + while (!agi1.hasCallReachedAgi() && ctr < 10) { Thread.sleep(100); ctr += 100.0 / 1000.0; - if (!agi1.hasCallReachedAgi()) - { + if (!agi1.hasCallReachedAgi()) { logger.warn("Waiting on (agi1) " + channel1); } } ret = agi1.hasCallReachedAgi(); - } - catch (final Exception e) - { + } catch (final Exception e) { logger.error(e, e); } } diff --git a/src/main/java/org/asteriskjava/pbx/internal/activity/SplitActivityImpl.java b/src/main/java/org/asteriskjava/pbx/internal/activity/SplitActivityImpl.java index 0396db628..9fa432ca1 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/activity/SplitActivityImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/activity/SplitActivityImpl.java @@ -1,21 +1,7 @@ package org.asteriskjava.pbx.internal.activity; -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; - -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.Call; -import org.asteriskjava.pbx.CallImpl; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +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; @@ -27,16 +13,22 @@ 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 -{ +public class SplitActivityImpl extends ActivityHelper implements SplitActivity { private static final Log logger = LogFactory.getLog(SplitActivityImpl.class); private Call _callToSplit; @@ -53,20 +45,18 @@ public class SplitActivityImpl extends ActivityHelper implements * 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) - { + 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) - { + if (tmp.size() > 1) { channel1 = tmp.get(0); channel2 = tmp.get(1); } @@ -75,8 +65,7 @@ public SplitActivityImpl(final Call callToSplit, final ActivityCallback> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(RenameEvent.class); return required; @@ -115,51 +101,47 @@ public boolean doActivity() throws PBXException final AtomicReference renameEventReceived = new AtomicReference<>(); @Override - synchronized public void onManagerEvent(final ManagerEvent event) - { - if (event instanceof RenameEvent) - { - RenameEvent rename = (RenameEvent) event; - if (rename.getChannel().isSame(channel1) || rename.getChannel().isSame(channel2)) - { - renameEventReceived.get().countDown(); + 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() - { + 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() - { + 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() - { + public Call getRHSCall() { return this._rhsCall; } /** * Splits two channels moving them to defined endpoints. - * + * * @param lhs * @param lhsTarget * @param lhsTargetContext @@ -169,21 +151,18 @@ public Call getRHSCall() * @return * @throws PBXException */ - private boolean splitTwo() throws PBXException - { + private boolean splitTwo() throws PBXException { final AsteriskSettings profile = PBXFactory.getActiveProfile(); AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); - if (channel1 == channel2) - { + 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)) - { + 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."); @@ -206,13 +185,10 @@ private boolean splitTwo() throws PBXException // taking an undesired action // when the AgiChannelActivityBridge channel has it's acitvity // cancelled. - if (channel2.getCurrentActivityAction() instanceof AgiChannelActivityBridge) - { + if (channel2.getCurrentActivityAction() instanceof AgiChannelActivityBridge) { channel1.setCurrentActivityAction(agi1); channel2.setCurrentActivityAction(agi2); - } - else - { + } else { channel2.setCurrentActivityAction(agi2); channel1.setCurrentActivityAction(agi1); } @@ -232,22 +208,17 @@ private boolean splitTwo() throws PBXException boolean ret = false; { - try - { + try { renameEventReceived.set(new CountDownLatch(1)); // final ManagerResponse response = pbx.sendAction(redirect, 1000); - if (pbx.expectRenameEvents()) - { + if (pbx.expectRenameEvents()) { // wait for channels to unbridge - if (!renameEventReceived.get().await(2000, TimeUnit.MILLISECONDS)) - { + if (!renameEventReceived.get().await(2000, TimeUnit.MILLISECONDS)) { logger.error("There was no rename event"); - } - else - { + } else { logger.warn("Channels are renaming, now waiting for Quiescent"); } } @@ -256,32 +227,26 @@ private boolean splitTwo() throws PBXException channels.add(channel1); channels.add(channel2); - if (!pbx.waitForChannelsToQuiescent(channels, 3000)) - { + 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) - { + while ((!agi1.hasCallReachedAgi() || !agi2.hasCallReachedAgi()) && ctr < 10) { Thread.sleep(100); ctr += 100.0 / 1000.0; - if (!agi1.hasCallReachedAgi()) - { + if (!agi1.hasCallReachedAgi()) { logger.info("Waiting on (agi1) " + channel1); } - if (!agi2.hasCallReachedAgi()) - { + if (!agi2.hasCallReachedAgi()) { logger.info("Waiting on (agi2) " + channel2); } } ret = agi1.hasCallReachedAgi() && agi2.hasCallReachedAgi(); - } - catch (final Exception e) - { + } catch (final Exception e) { logger.error(e, e); } } diff --git a/src/main/java/org/asteriskjava/pbx/internal/asterisk/CallerIDImpl.java b/src/main/java/org/asteriskjava/pbx/internal/asterisk/CallerIDImpl.java index eac9d1df2..db7b773d2 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/asterisk/CallerIDImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/CallerIDImpl.java @@ -3,33 +3,29 @@ import org.asteriskjava.pbx.CallerID; import org.asteriskjava.pbx.PBXFactory; -public class CallerIDImpl implements CallerID -{ +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. + * @param name - if null then we store an empty string. */ - public CallerIDImpl(final String number, final String name) - { + 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() - { + public String getNumber() { return this.number; } @Override - public String getName() - { + public String getName() { return this.name; } @@ -37,24 +33,20 @@ public String getName() * 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. + * @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) - { + public static CallerID buildFromComponents(final String firstname, final String lastname, final String number) { String name = ""; //$NON-NLS-1$ - if (firstname != null) - { + if (firstname != null) { name += firstname.trim(); } - if (lastname != null) - { - if (name.length() > 0) - { + if (lastname != null) { + if (name.length() > 0) { name += " "; //$NON-NLS-1$ } name += lastname.trim(); @@ -67,20 +59,16 @@ public static CallerID buildFromComponents(final String firstname, final String * 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() - { + public String formatted() { String callerID = ""; //$NON-NLS-1$ - if (this.name != null) - { + if (this.name != null) { callerID += this.name; } - if (this.number != null) - { - if (callerID.length() > 1) - { + if (this.number != null) { + if (callerID.length() > 1) { callerID += " "; //$NON-NLS-1$ } callerID += "<" + this.number + ">"; //$NON-NLS-1$ //$NON-NLS-2$ @@ -89,27 +77,23 @@ public String formatted() } @Override - public void setHideCallerID(final boolean hide) - { + public void setHideCallerID(final boolean hide) { this.hideCallerID = hide; } @Override - public boolean isHideCallerID() - { + public boolean isHideCallerID() { return this.hideCallerID; } @Override - public String toString() - { + public String toString() { return this.formatted(); } @Override - public boolean isUnknown() - { + 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 index 0cd4e830b..64cb11102 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/asterisk/DurationRoomOwner.java +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/DurationRoomOwner.java @@ -2,25 +2,21 @@ import java.util.concurrent.TimeUnit; -public class DurationRoomOwner implements RoomOwner -{ +public class DurationRoomOwner implements RoomOwner { long end = System.currentTimeMillis(); - public DurationRoomOwner(long duration, TimeUnit units) - { + public DurationRoomOwner(long duration, TimeUnit units) { end = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(duration, units); } @Override - public boolean isRoomStillRequired() - { + public boolean isRoomStillRequired() { return System.currentTimeMillis() < end; } @Override - public void setRoom(MeetmeRoom meetmeRoom) - { + 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 index 722953b9b..f01856574 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoom.java +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoom.java @@ -1,19 +1,19 @@ package org.asteriskjava.pbx.internal.asterisk; -import java.util.Date; -import java.util.LinkedList; - +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 -{ +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 @@ -31,12 +31,11 @@ public class MeetmeRoom private boolean forceClose = false; - private Date lastUpdated = null; + private Long lastUpdated = null; private RoomOwner owner = null; - public MeetmeRoom(final int number) - { + public MeetmeRoom(final int number) { this.roomNumber = number; } @@ -44,116 +43,108 @@ public MeetmeRoom(final int 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 */ - synchronized public boolean addChannel(final Channel channel) - { - boolean newChannel = false; - if (!this.channels.contains(channel)) - { - this.channels.add(channel); - this.channelCount++; - newChannel = true; + 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; } - else - MeetmeRoom.logger.error("rejecting " + channel + " already in meetme."); //$NON-NLS-1$ //$NON-NLS-2$ - return newChannel; } - synchronized public int getChannelCount() - { - return this.channelCount; + public int getChannelCount() { + try (LockCloser closer = this.withLock()) { + return this.channelCount; + } } - synchronized public Channel[] getChannels() - { - final Channel list[] = new Channel[this.channels.size()]; + 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; + int cnt = 0; + for (final Channel channel : this.channels) { + list[cnt++] = channel; + } + return list; } - return list; } - public boolean getForceClose() - { + public boolean getForceClose() { return this.forceClose; } - public Date getLastUpdated() - { + public Long getLastUpdated() { return this.lastUpdated; } - public String getRoomNumber() - { + 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() - { + public boolean isActive() { return this.active; } - synchronized public void removeChannel(final Channel channel) - { - final boolean channelCountInSync = this.channelCount == this.channels.size(); - final boolean removed = this.channels.remove(channel); + 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 " + this.getRoomNumber()); //$NON-NLS-1$ //$NON-NLS-2$ - } + 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 (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 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$ + 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() - { + public void setActive() { this.active = true; } - public void setForceClose(final boolean canClose) - { + public void setForceClose(final boolean canClose) { this.forceClose = canClose; } - public void setInactive() - { + public void setInactive() { this.active = false; this.channels.clear(); this.forceClose = false; @@ -162,45 +153,38 @@ public void setInactive() } - public void setLastUpdated() - { - this.lastUpdated = new Date(); + 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) - { + public void resetChannelCount(final int resetChannelCount) { this.channelCount = resetChannelCount; } - public RoomOwner getOwner() - { + public RoomOwner getOwner() { return owner; } - public void setOwner(RoomOwner newOwner) - { + public void setOwner(RoomOwner newOwner) { owner = newOwner; owner.setRoom(this); setActive(); } - public void removeOwner(RoomOwner toRemove) - { - if (owner == toRemove) - { + 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"); + } 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 index b8610f026..a6d7970a4 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoomControl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/MeetmeRoomControl.java @@ -1,28 +1,12 @@ package org.asteriskjava.pbx.internal.asterisk; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.atomic.AtomicReference; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.live.ManagerCommunicationException; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +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.ConfbridgeListEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.MeetMeJoinEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.MeetMeLeaveEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.ResponseEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.ResponseEvents; +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; @@ -31,8 +15,13 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class MeetmeRoomControl extends EventListenerBaseClass implements CoherentManagerEventListener -{ +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 @@ -52,22 +41,16 @@ public class MeetmeRoomControl extends EventListenerBaseClass implements Coheren private final static AtomicReference self = new AtomicReference<>(); - synchronized public static void init(PBX pbx, final int roomCount) throws NoMeetmeException - { - if (MeetmeRoomControl.self.get() != null) - { + 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 - { + } else { MeetmeRoomControl.self.set(new MeetmeRoomControl(pbx, roomCount)); } } - public static MeetmeRoomControl getInstance() - { - if (MeetmeRoomControl.self.get() == null) - { + 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$ } @@ -76,8 +59,7 @@ public static MeetmeRoomControl getInstance() } - private MeetmeRoomControl(PBX pbx, final int roomCount) throws NoMeetmeException - { + private MeetmeRoomControl(PBX pbx, final int roomCount) throws NoMeetmeException { super("MeetmeRoomControl", pbx); //$NON-NLS-1$ this.roomCount = roomCount; final AsteriskSettings settings = PBXFactory.getActiveProfile(); @@ -89,9 +71,8 @@ private MeetmeRoomControl(PBX pbx, final int roomCount) throws NoMeetmeException } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(MeetMeJoinEvent.class); required.add(MeetMeLeaveEvent.class); @@ -103,159 +84,135 @@ private MeetmeRoomControl(PBX pbx, final int roomCount) throws NoMeetmeException * returns the next available meetme room, or null if no rooms are * available. */ - public synchronized MeetmeRoom findAvailableRoom(RoomOwner newOwner) - { - 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 Date lastUpdated = room.getLastUpdated(); - final long now = new Date().getTime(); - if (lastUpdated != null) - { - final long elapsedTime = now - lastUpdated.getTime(); - 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(); - } - } + 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); } - catch (final Exception e) - { + if (room.getOwner() == null || !room.getOwner().isRoomStillRequired()) { /* - * attempt to make this new change safe + * new code to attempt to recover uncleared meetme rooms + * safely */ - MeetmeRoomControl.logger.error(e, e); - } + 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.warn("Returning available room " + room.getRoomNumber()); - return room; - } + 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++; } - else - { - logger.warn("Meetme " + room.getRoomNumber() + " is still in use by " + room.getOwner()); - } - count++; + MeetmeRoomControl.logger.error("no more available rooms"); + return null; } - 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 */ - synchronized private MeetmeRoom findMeetmeRoom(final String roomNumber) - { - MeetmeRoom foundRoom = null; - for (final MeetmeRoom room : this.rooms) - { - if (room.getRoomNumber().compareToIgnoreCase(roomNumber) == 0) - { - foundRoom = room; - break; + 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; } - return foundRoom; + } - synchronized MeetmeRoom getRoom(final int room) - { - return this.rooms[room]; + MeetmeRoom getRoom(final int room) { + try (LockCloser closer = this.withLock()) { + return this.rooms[room]; + } } @Override - public void onManagerEvent(final ManagerEvent event) - { + public void onManagerEvent(final ManagerEvent event) { MeetmeRoom room; - if (event instanceof MeetMeJoinEvent) - { + 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)) - { + 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) - { + if (event instanceof MeetMeLeaveEvent) { final MeetMeLeaveEvent evt = (MeetMeLeaveEvent) event; room = this.findMeetmeRoom(evt.getMeetMe()); final Channel channel = evt.getChannel(); - if (room != null) - { + if (room != null) { // ignore local dummy channels// && // !channel.toUpperCase().startsWith("LOCAL/")) { - if (MeetmeRoomControl.logger.isDebugEnabled()) - { + 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()) - { + if (room.getChannelCount() < 2 && room.getForceClose()) { this.hangupChannels(room); room.setInactive(); } - if (room.getChannelCount() < 1) - { + if (room.getChannelCount() < 1) { room.setInactive(); } } } } - public void hangupChannels(final MeetmeRoom room) - { + public void hangupChannels(final MeetmeRoom room) { final Channel Channels[] = room.getChannels(); - if (room.isActive()) - { + if (room.isActive()) { PBX pbx = PBXFactory.getActivePBX(); - for (final Channel channel : Channels) - { + for (final Channel channel : Channels) { room.removeChannel(channel); - try - { + try { logger.warn("Hanging up"); pbx.hangup(channel); - } - catch (IllegalArgumentException | IllegalStateException | PBXException e) - { + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { logger.error(e, e); } @@ -263,122 +220,96 @@ public void hangupChannels(final MeetmeRoom room) } } - private void configure(AsteriskPBX pbx) throws NoMeetmeException - { + private void configure(AsteriskPBX pbx) throws NoMeetmeException { final int base = this.meetmeBaseAddress; - for (int r = 0; r < this.roomCount; r++) - { + for (int r = 0; r < this.roomCount; r++) { this.rooms[r] = new MeetmeRoom(r + base); } - try - { + try { String command; - if (pbx.getVersion().isAtLeast(AsteriskVersion.ASTERISK_13)) - { + 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()) - { + for (ResponseEvent event : response.getEvents()) { ConfbridgeListEvent e = (ConfbridgeListEvent) event; Integer current = roomChannelCount.get(e.getConference()); - if (current == null) - { + if (current == null) { roomChannelCount.put(e.getConference(), 1); - } - else - { + } else { roomChannelCount.put(e.getConference(), current + 1); } } - for (Entry entry : roomChannelCount.entrySet()) - { + 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)) - { + } else { + if (pbx.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) { command = "meetme list"; //$NON-NLS-1$ - } - else - { + } else { command = "meetme"; //$NON-NLS-1$ } final CommandAction commandAction = new CommandAction(command); final ManagerResponse response = pbx.sendAction(commandAction, 3000); - if (!(response instanceof CommandResponse)) - { + 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()) - { + for (final String line : commandResponse.getResult()) { this.parseMeetme(line); this.meetmeInstalled = true; MeetmeRoomControl.logger.debug(line); } } - } - catch (final NoMeetmeException e) - { + } catch (final NoMeetmeException e) { throw e; - } - catch (final Exception e) - { + } catch (final Exception e) { MeetmeRoomControl.logger.error(e, e); throw new NoMeetmeException(e.getLocalizedMessage()); } } - private synchronized void parseMeetme(final String line) throws NoMeetmeException - { - - 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$ - } + 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); + 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) - { + 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))) - { + if ((roomNo >= base) && (roomNo < (base + this.roomCount))) { final MeetmeRoom room = this.findMeetmeRoom(roomNumber); - if (room != null) - { - if (room.getChannelCount() != channelCount) - { + 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 @@ -400,20 +331,17 @@ private void setRoomCount(final String roomNumber, final int channelCount, final } } - public void stop() - { + public void stop() { this.close(); } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.NORMAL; } - public boolean isMeetmeInstalled() - { + 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 index eb666a2d5..7b83e8b20 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/asterisk/NoMeetmeException.java +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/NoMeetmeException.java @@ -1,12 +1,10 @@ package org.asteriskjava.pbx.internal.asterisk; -public class NoMeetmeException extends Exception -{ - private static final long serialVersionUID = 1L; +public class NoMeetmeException extends Exception { + private static final long serialVersionUID = 1L; - public NoMeetmeException(final String message) - { - super(message); - } + 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 index 3bb04c3de..f1f614edb 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/asterisk/RoomOwner.java +++ b/src/main/java/org/asteriskjava/pbx/internal/asterisk/RoomOwner.java @@ -1,12 +1,11 @@ package org.asteriskjava.pbx.internal.asterisk; -public interface RoomOwner -{ +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(); @@ -14,7 +13,7 @@ public interface RoomOwner /** * 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 index 1a4c44d22..639aa12bd 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/ActiveCallListener.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/ActiveCallListener.java @@ -5,13 +5,11 @@ /** * 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 -{ +public interface ActiveCallListener { - void callStatusChanged(Call call, boolean isHidden); + 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 index b610d5a12..9147f06e7 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/AsteriskPBX.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/AsteriskPBX.java @@ -1,68 +1,23 @@ package org.asteriskjava.pbx.internal.core; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - 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.Activity; -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.ActivityStatusEnum; -import org.asteriskjava.pbx.AgiChannelActivityAction; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.Call; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.Call.OperandChannel; -import org.asteriskjava.pbx.CallDirection; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ChannelHangupListener; -import org.asteriskjava.pbx.CompletionAdaptor; -import org.asteriskjava.pbx.DTMFTone; -import org.asteriskjava.pbx.DialPlanExtension; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.InvalidChannelName; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; -import org.asteriskjava.pbx.TechType; -import org.asteriskjava.pbx.Trunk; -import org.asteriskjava.pbx.activities.BlindTransferActivity; -import org.asteriskjava.pbx.activities.BridgeActivity; -import org.asteriskjava.pbx.activities.DialActivity; -import org.asteriskjava.pbx.activities.DialToAgiActivity; -import org.asteriskjava.pbx.activities.HoldActivity; -import org.asteriskjava.pbx.activities.JoinActivity; -import org.asteriskjava.pbx.activities.ParkActivity; -import org.asteriskjava.pbx.activities.RedirectToActivity; -import org.asteriskjava.pbx.activities.SplitActivity; +import org.asteriskjava.pbx.activities.*; import org.asteriskjava.pbx.agi.AgiChannelActivityHangup; import org.asteriskjava.pbx.agi.AgiChannelActivityHold; -import org.asteriskjava.pbx.asterisk.wrap.actions.CommandAction; -import org.asteriskjava.pbx.asterisk.wrap.actions.EventGeneratingAction; -import org.asteriskjava.pbx.asterisk.wrap.actions.HangupAction; -import org.asteriskjava.pbx.asterisk.wrap.actions.ManagerAction; -import org.asteriskjava.pbx.asterisk.wrap.actions.PlayDtmfAction; -import org.asteriskjava.pbx.asterisk.wrap.actions.RedirectAction; +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.BlindTransferActivityImpl; -import org.asteriskjava.pbx.internal.activity.BridgeActivityImpl; -import org.asteriskjava.pbx.internal.activity.DialActivityImpl; -import org.asteriskjava.pbx.internal.activity.DialToAgiActivityImpl; -import org.asteriskjava.pbx.internal.activity.HoldActivityImpl; -import org.asteriskjava.pbx.internal.activity.JoinActivityImpl; -import org.asteriskjava.pbx.internal.activity.ParkActivityImpl; -import org.asteriskjava.pbx.internal.activity.RedirectToActivityImpl; -import org.asteriskjava.pbx.internal.activity.SplitActivityImpl; +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; @@ -71,8 +26,13 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public enum AsteriskPBX implements PBX, ChannelHangupListener -{ +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; @@ -86,10 +46,8 @@ public enum AsteriskPBX implements PBX, ChannelHangupListener private LiveChannelManager liveChannels; - AsteriskPBX() - { - try - { + AsteriskPBX() { + try { CoherentManagerConnection.init(); this.muteSupported = CoherentManagerConnection.getInstance().isMuteAudioSupported(); @@ -98,16 +56,13 @@ public enum AsteriskPBX implements PBX, ChannelHangupListener liveChannels = new LiveChannelManager(); MeetmeRoomControl.init(this, AsteriskPBX.MAX_MEETME_ROOMS); - } - catch (Exception e) - { + } catch (Exception e) { throw new RuntimeException(e); } } @Override - public void performPostCreationTasks() - { + public void performPostCreationTasks() { liveChannels.performPostCreationTasks(); } @@ -116,22 +71,19 @@ public void performPostCreationTasks() * cleanup. */ @Override - public void shutdown() - { + public void shutdown() { MeetmeRoomControl.getInstance().stop(); CoherentManagerConnection.getInstance().shutDown(); } @Override - public boolean isBridgeSupported() - { + 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) - { + CallerID toCallerID, boolean autoAnswer, long timeout, String dialOptions) { final CompletionAdaptor completion = new CompletionAdaptor<>(); final BlindTransferActivityImpl transfer = new BlindTransferActivityImpl(call, channelToTransfer, transferTarget, @@ -145,17 +97,15 @@ public BlindTransferActivity blindTransfer(Call call, Call.OperandChannel channe @Override public void blindTransfer(Call call, Call.OperandChannel channelToTransfer, EndPoint transferTarget, CallerID toCallerID, - boolean autoAnswer, long timeout, ActivityCallback listener, String dialOptions) - { + 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 - { + boolean autoAnswer, int timeout, ActivityCallback iCallback, String dialOptions) + throws PBXException { return new BlindTransferActivityImpl(agentChannel, transferTarget, toCallerID, autoAnswer, timeout, iCallback, dialOptions); @@ -169,8 +119,7 @@ public BlindTransferActivity blindTransfer(Channel agentChannel, EndPoint transf * @param direction * @throws PBXException */ - public BridgeActivity bridge(final Channel lhsChannel, final Channel rhsChannel) 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); @@ -182,8 +131,7 @@ public BridgeActivity bridge(final Channel lhsChannel, final Channel rhsChannel) } @Override - public void split(final Call callToSplit) throws PBXException - { + public void split(final Call callToSplit) throws PBXException { final CompletionAdaptor completion = new CompletionAdaptor<>(); new SplitActivityImpl(callToSplit, completion); @@ -193,15 +141,13 @@ public void split(final Call callToSplit) throws PBXException } @Override - public SplitActivity split(final Call callToSplit, final ActivityCallback listener) - { + public SplitActivity split(final Call callToSplit, final ActivityCallback listener) { return new SplitActivityImpl(callToSplit, listener); } @Override - public RedirectToActivity redirectToActivity(final Channel channel, final ActivityCallback listener) - { + public RedirectToActivity redirectToActivity(final Channel channel, final ActivityCallback listener) { return new RedirectToActivityImpl(channel, listener); } @@ -213,8 +159,7 @@ public RedirectToActivity redirectToActivity(final Channel channel, final Activi */ @Override public JoinActivity join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel acceptingOperand, - CallDirection direction) - { + CallDirection direction) { final CompletionAdaptor completion = new CompletionAdaptor<>(); final JoinActivityImpl join = new JoinActivityImpl(lhs, originatingOperand, rhs, acceptingOperand, direction, @@ -233,31 +178,27 @@ public JoinActivity join(Call lhs, OperandChannel originatingOperand, Call rhs, */ @Override public void join(Call lhs, OperandChannel originatingOperand, Call rhs, OperandChannel acceptingOperand, - CallDirection direction, ActivityCallback listener) - { + 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) - { + 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) - { + 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) - { + String dialOptions) { final CompletionAdaptor completion = new CompletionAdaptor<>(); final DialActivityImpl dialer = new DialActivityImpl(from, to, toCallerID, false, completion, null, dialOptions); @@ -268,14 +209,12 @@ public DialActivity dial(final EndPoint from, final CallerID fromCallerID, final } public DialLocalToAgiActivity dialLocalToAgi(final EndPoint from, final CallerID fromCallerID, - ActivityCallback callback, Map channelVarsToSet) - { + 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 ActivityCallback callback, Map channelVarsToSet, String dialOptions) { final DialActivityImpl dialer = new DialActivityImpl(from, to, toCallerID, false, callback, channelVarsToSet, dialOptions); return dialer; @@ -283,8 +222,7 @@ public DialActivity dial(final EndPoint from, final CallerID fromCallerID, final @Override public void dial(final EndPoint from, final CallerID fromCallerID, final EndPoint to, final CallerID toCallerID, - final ActivityCallback callback, String dialOptions) - { + final ActivityCallback callback, String dialOptions) { new DialActivityImpl(from, to, toCallerID, false, callback, null, dialOptions); } @@ -293,16 +231,13 @@ public void dial(final EndPoint from, final CallerID fromCallerID, final EndPoin * Convenience method to hangup the call without having to extract the * channel yourself. */ - public void hangup(Call call) throws PBXException - { + public void hangup(Call call) throws PBXException { this.hangup(call.getOriginatingParty()); } @Override - public void hangup(final Channel channel) throws PBXException - { - if (channel.isLive()) - { + 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(); @@ -310,42 +245,33 @@ public void hangup(final Channel channel) throws PBXException throw new PBXException("Channel: " + channel + " cannot be retrieved as it is still in transition."); final HangupAction hangup = new HangupAction(channel); - try - { + try { channel.setCurrentActivityAction(new AgiChannelActivityHangup()); CoherentManagerConnection.sendAction(hangup, 1000); - } - catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) - { + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { logger.error(e, e); throw new PBXException(e); } - } - else + } 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) - { + 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) - { + public HoldActivity hold(final Channel channel) { final CompletionAdaptor completion = new CompletionAdaptor<>(); HoldActivity activity = null; - try - { + try { activity = new HoldActivityImpl(channel, completion); completion.waitForCompletion(10, TimeUnit.SECONDS); - } - catch (final Exception e) - { + } catch (final Exception e) { logger.error(e, e); } @@ -353,14 +279,12 @@ public HoldActivity hold(final Channel channel) } @Override - public boolean isMuteSupported() - { + public boolean isMuteSupported() { return this.muteSupported; } @Override - public ParkActivity park(final Call call, final Channel parkChannel) - { + public ParkActivity park(final Call call, final Channel parkChannel) { final CompletionAdaptor completion = new CompletionAdaptor<>(); final ParkActivity activity = new ParkActivityImpl(call, parkChannel, completion); @@ -371,70 +295,58 @@ public ParkActivity park(final Call call, final Channel parkChannel) } @Override - public void park(final Call call, final Channel parkChannel, final ActivityCallback callback) - { + 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 - { + 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) - { + } 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) - { + 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 - { + public void transferToMusicOnHold(final Channel channel) throws PBXException { final RedirectCall transfer = new RedirectCall(); transfer.redirect(channel, new AgiChannelActivityHold()); } - public String getManagementContext() - { + public String getManagementContext() { final AsteriskSettings settings = PBXFactory.getActiveProfile(); return settings.getManagementContext(); } @Override - public Channel getChannelByEndPoint(final EndPoint endPoint) - { + public Channel getChannelByEndPoint(final EndPoint endPoint) { return this.liveChannels.getChannelByEndPoint(endPoint); } @Override - public void channelHangup(Channel channel, Integer cause, String causeText) - { + public void channelHangup(Channel channel, Integer cause, String causeText) { this.liveChannels.remove((ChannelProxy) channel); } - public DialPlanExtension getExtensionPark() - { + public DialPlanExtension getExtensionPark() { final AsteriskSettings settings = PBXFactory.getActiveProfile(); return this.buildDialPlanExtension(settings.getExtensionPark()); } @Override - public EndPoint getExtensionAgi() - { + public EndPoint getExtensionAgi() { final AsteriskSettings settings = PBXFactory.getActiveProfile(); return this.buildDialPlanExtension(settings.getAgiExtension()); } @@ -446,15 +358,11 @@ public EndPoint getExtensionAgi() */ @Override - public EndPoint buildEndPoint(final String fullyQualifiedEndPoint) - { + public EndPoint buildEndPoint(final String fullyQualifiedEndPoint) { EndPoint endPoint = null; - try - { + try { endPoint = new EndPointImpl(fullyQualifiedEndPoint); - } - catch (final IllegalArgumentException e) - { + } catch (final IllegalArgumentException e) { logger.warn(e, e); } return endPoint; @@ -465,18 +373,14 @@ public EndPoint buildEndPoint(final String fullyQualifiedEndPoint) * have a tech specified then the defaultTech is used. */ @Override - public EndPoint buildEndPoint(final TechType defaultTech, final String endPointName) - { + public EndPoint buildEndPoint(final TechType defaultTech, final String endPointName) { EndPoint endPoint = null; - try - { + try { if (endPointName == null || endPointName.trim().length() == 0) endPoint = new EndPointImpl(); else endPoint = new EndPointImpl(defaultTech, endPointName); - } - catch (final IllegalArgumentException e) - { + } catch (final IllegalArgumentException e) { logger.error(e, e); } return endPoint; @@ -484,8 +388,7 @@ public EndPoint buildEndPoint(final TechType defaultTech, final String endPointN } @Override - public EndPoint buildEndPoint(final TechType defaultTech, final Trunk trunk, final String endPointName) - { + public EndPoint buildEndPoint(final TechType defaultTech, final Trunk trunk, final String endPointName) { return new EndPointImpl(defaultTech, trunk, endPointName); } @@ -494,15 +397,11 @@ public EndPoint buildEndPoint(final TechType defaultTech, final Trunk trunk, fin * 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) - { + public DialPlanExtension buildDialPlanExtension(final String extension) { DialPlanExtension dialPlan = null; - try - { + try { dialPlan = new DialPlanExtension(extension); - } - catch (final IllegalArgumentException e) - { + } catch (final IllegalArgumentException e) { logger.error(e, e); } return dialPlan; @@ -510,8 +409,7 @@ public DialPlanExtension buildDialPlanExtension(final String extension) } @Override - public CallerID buildCallerID(final String number, final String name) - { + public CallerID buildCallerID(final String number, final String name) { return new CallerIDImpl(number, name); } @@ -520,36 +418,28 @@ public CallerID buildCallerID(final String number, final String name) * * @param event */ - public CallerID buildCallerID(final AbstractChannelEvent 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 - { + public Channel registerChannel(final String channelName, final String uniqueIdParam) throws InvalidChannelName { String uniqueID = uniqueIdParam; - if (uniqueIdParam == null || uniqueIdParam.length() == 0) - { + if (uniqueIdParam == null || uniqueIdParam.length() == 0) { uniqueID = ChannelImpl.UNKNOWN_UNIQUE_ID; } - if (channelName == null || channelName.trim().length() == 0) - { + 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) - { + 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())) - { + } else { + if (uniqueID != null && !uniqueID.equals(proxy.getUniqueId())) { logger.info( "Found the channel(" + proxy.getUniqueId() + "), but with a different uniqueId (" + uniqueID + ")"); @@ -571,16 +461,13 @@ public Channel registerChannel(final String channelName, final String uniqueIdPa * @return * @throws InvalidChannelName */ - public Channel internalRegisterChannel(final String channelName, final String uniqueID) throws InvalidChannelName - { + public Channel internalRegisterChannel(final String channelName, final String uniqueID) throws InvalidChannelName { ChannelProxy proxy = null; - synchronized (this.liveChannels) - { + try (LockCloser closer = this.liveChannels.withLock()) { String localUniqueID = (uniqueID == null ? ChannelImpl.UNKNOWN_UNIQUE_ID : uniqueID); proxy = this.findChannel(cleanChannelName(channelName), localUniqueID); - if (proxy == null) - { + if (proxy == null) { proxy = new ChannelProxy(new ChannelImpl(channelName, localUniqueID)); logger.debug("Creating new Channel Proxy " + proxy); this.liveChannels.add(proxy); @@ -596,21 +483,17 @@ public Channel internalRegisterChannel(final String channelName, final String un * @param name * @return */ - private String cleanChannelName(final String name) - { + private String cleanChannelName(final String name) { String cleanedName = name.trim().toUpperCase(); return cleanedName; } - public Channel registerHangupChannel(String channel, String uniqueId) throws InvalidChannelName - { + public Channel registerHangupChannel(String channel, String uniqueId) throws InvalidChannelName { Channel newChannel = null; - synchronized (this.liveChannels) - { + try (LockCloser closer = this.liveChannels.withLock()) { newChannel = this.findChannel(channel, uniqueId); - if (newChannel == null) - { + 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. @@ -625,24 +508,20 @@ public Channel registerHangupChannel(String channel, String uniqueId) throws Inv return newChannel; } - public ChannelProxy findChannel(final String channelName, final String uniqueID) - { + public ChannelProxy findChannel(final String channelName, final String uniqueID) { return this.liveChannels.findChannel(channelName, uniqueID); } - public MeetmeRoom acquireMeetmeRoom(RoomOwner owner) - { + public MeetmeRoom acquireMeetmeRoom(RoomOwner owner) { return MeetmeRoomControl.getInstance().findAvailableRoom(owner); } - public void addListener(FilteredManagerListener listener) - { + public void addListener(FilteredManagerListener listener) { CoherentManagerConnection connection = CoherentManagerConnection.getInstance(); connection.addListener(listener); } - public void removeListener(FilteredManagerListener listener) - { + public void removeListener(FilteredManagerListener listener) { CoherentManagerConnection connection = CoherentManagerConnection.getInstance(); connection.removeListener(listener); } @@ -658,86 +537,70 @@ public void removeListener(FilteredManagerListener listener) * @throws TimeoutException */ public ManagerResponse sendAction(ManagerAction theAction) - throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException - { + throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { return CoherentManagerConnection.sendAction(theAction, 30000); } public ManagerResponse sendAction(ManagerAction theAction, int timeout) - throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException - { + throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { return CoherentManagerConnection.sendAction(theAction, timeout); } public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) - throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException - { + throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException { ResponseEvents events = CoherentManagerConnection.sendEventGeneratingAction(action); return events; } public ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, int timeout) - throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException - { + throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException { return CoherentManagerConnection.sendEventGeneratingAction(action, timeout); } - public void setVariable(Channel channel, String name, String value) throws PBXException - { + public void setVariable(Channel channel, String name, String value) throws PBXException { CoherentManagerConnection.getInstance().setVariable(channel, name, value); } - public void sendActionNoWait(final ManagerAction action) - { + public void sendActionNoWait(final ManagerAction action) { CoherentManagerConnection.sendActionNoWait(action); } - public String getVariable(Channel channel, String name) - { + public String getVariable(Channel channel, String name) { return CoherentManagerConnection.getInstance().getVariable(channel, name); } - public AsteriskVersion getVersion() - { + public AsteriskVersion getVersion() { return CoherentManagerConnection.getInstance().getVersion(); } - public boolean isConnected() - { + public boolean isConnected() { return ((CoherentManagerConnection.managerConnection != null) && (CoherentManagerConnection.managerConnection.getState() == ManagerConnectionState.CONNECTED)); } - public boolean isMeetmeInstalled() - { + public boolean isMeetmeInstalled() { return MeetmeRoomControl.getInstance().isMeetmeInstalled(); } @Override - public boolean isChannel(String channelName) - { + public boolean isChannel(String channelName) { boolean isChannel = false; - try - { + try { internalRegisterChannel(channelName, ChannelImpl.UNKNOWN_UNIQUE_ID); isChannel = true; - } - catch (InvalidChannelName e) - { + } 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) - { + static public String getSIPADDHeader(final boolean inherit, final boolean targetIsSIP) { String sipHeader = "SIPADDHEADER"; //$NON-NLS-1$ - if (!targetIsSIP || inherit) - { + if (!targetIsSIP || inherit) { sipHeader = "__" + sipHeader; //$NON-NLS-1$ } return sipHeader; @@ -749,35 +612,27 @@ static public String getSIPADDHeader(final boolean inherit, final boolean target * * @param channel * @param timeout the time to wait (in milliseconds) for the channel to - * become quiescent. + * become quiescent. */ @Override - public boolean waitForChannelsToQuiescent(List channels, long timeout) - { + public boolean waitForChannelsToQuiescent(List channels, long timeout) { long elapsed = 0; - while (elapsed < timeout && !channelsAreQuiesent(channels)) - { - try - { + while (elapsed < timeout && !channelsAreQuiesent(channels)) { + try { Thread.sleep(200); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { logger.error(e, e); } logger.info("Waiting for channesl to Quiescent"); elapsed += 200; } - if (elapsed > timeout / 2) - { + if (elapsed > timeout / 2) { logger.warn("Took " + elapsed + "ms for channels to Quiescent"); } - if (elapsed >= timeout) - { + if (elapsed >= timeout) { logger.error("Channels didn't Quiescent"); - for (Channel channel : channels) - { + for (Channel channel : channels) { logger.error(channel); } @@ -785,24 +640,20 @@ public boolean waitForChannelsToQuiescent(List channels, long timeout) return timeout > elapsed; } - private boolean channelsAreQuiesent(List channels) - { + private boolean channelsAreQuiesent(List channels) { boolean ret = true; - for (Channel channel : channels) - { + for (Channel channel : channels) { ret &= channel.isQuiescent(); } return ret; } - public boolean moveChannelToAgi(Channel channel) throws PBXException - { + 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) - { + if (!isInAgi) { final AsteriskSettings profile = PBXFactory.getActiveProfile(); channel.setCurrentActivityAction(new AgiChannelActivityHold()); @@ -811,26 +662,21 @@ public boolean moveChannelToAgi(Channel channel) throws PBXException logger.error("Issuing redirect on channel " + channel + " to move it to the agi"); - try - { + 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) - { + while (!channel.isInAgi() && limit-- > 0) { Thread.sleep(100); } isInAgi = channel.isInAgi(); - if (!isInAgi) - { + if (!isInAgi) { logger.error("Failed to move channel"); } } - } - catch (final Exception e) - { + } catch (final Exception e) { logger.error(e, e); } @@ -839,42 +685,35 @@ public boolean moveChannelToAgi(Channel channel) throws PBXException } - public void moveChannelTo(Channel channel, String context, String exten, int prio) - { + 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 - { + try { sendAction(redirect, 1000); - } - catch (final Exception e) - { + } catch (final Exception e) { logger.error(e, e); } } @Override - public boolean waitForChannelToQuiescent(Channel channel, int timeout) - { + public boolean waitForChannelToQuiescent(Channel channel, int timeout) { List channels = new LinkedList<>(); channels.add(channel); return waitForChannelsToQuiescent(channels, timeout); } - public ChannelProxy getProxyById(String id) - { + public ChannelProxy getProxyById(String id) { return liveChannels.findProxyById(id); } public DialToAgiActivityImpl dialToAgi(EndPoint endPoint, CallerID callerID, AgiChannelActivityAction action, - ActivityCallback iCallback, Map channelVarsToSet) - { + ActivityCallback iCallback, Map channelVarsToSet) { final CompletionAdaptor completion = new CompletionAdaptor<>(); @@ -887,12 +726,9 @@ public DialToAgiActivityImpl dialToAgi(EndPoint endPoint, CallerID callerID, Agi final ActivityStatusEnum status; - if (dialer.isSuccess()) - { + if (dialer.isSuccess()) { status = ActivityStatusEnum.SUCCESS; - } - else - { + } else { status = ActivityStatusEnum.FAILURE; } @@ -902,8 +738,7 @@ public DialToAgiActivityImpl dialToAgi(EndPoint endPoint, CallerID callerID, Agi } public DialToAgiActivityImpl dialToAgiWithAbort(EndPoint endPoint, CallerID callerID, int timeout, - AgiChannelActivityAction action, ActivityCallback iCallback) - { + AgiChannelActivityAction action, ActivityCallback iCallback) { return new DialToAgiActivityImpl(endPoint, callerID, timeout, false, iCallback, null, action); @@ -921,17 +756,13 @@ public DialToAgiActivityImpl dialToAgiWithAbort(EndPoint endPoint, CallerID call * @throws AuthenticationFailedException * @throws TimeoutException */ - public boolean createAgiEntryPoint() throws IOException, AuthenticationFailedException, TimeoutException - { + public boolean createAgiEntryPoint() throws IOException, AuthenticationFailedException, TimeoutException { - try - { + try { AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); AsteriskSettings profile = PBXFactory.getActiveProfile(); - if (!checkDialplanExists(profile)) - - { + if (!checkDialplanExists(profile)) { String host = profile.getAgiHost(); String agi = profile.getAgiExtension(); @@ -943,9 +774,7 @@ public boolean createAgiEntryPoint() throws IOException, AuthenticationFailedExc return checkDialplanExists(profile); } return true; - } - catch (Exception e) - { + } catch (Exception e) { logger.error(e); return false; @@ -953,17 +782,13 @@ public boolean createAgiEntryPoint() throws IOException, AuthenticationFailedExc } - public boolean checkDialplanExists(String dialPlan, String context) throws IOException, TimeoutException - { + public boolean checkDialplanExists(String dialPlan, String context) throws IOException, TimeoutException { String command; - if (getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) - { + if (getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6)) { // TODO: Use ShowDialplanAction instead of CommandAction? command = "dialplan show " + context; - } - else - { + } else { command = "show dialplan " + context; } @@ -974,15 +799,12 @@ public boolean checkDialplanExists(String dialPlan, String context) throws IOExc } public boolean checkDialplanExists(AsteriskSettings profile) - throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException - { + throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { return checkDialplanExists(ACTIVITY_AGI, profile.getManagementContext()); } - public String addAsteriskExtension(String extNumber, int priority, String command) throws Exception - - { + public String addAsteriskExtension(String extNumber, int priority, String command) throws Exception { String ext = "dialplan add extension " + extNumber + "," + priority + "," + command; CommandAction action = new CommandAction(ext); @@ -991,8 +813,7 @@ public String addAsteriskExtension(String extNumber, int priority, String comman List line = response.getResult(); String tmp = "Extension '" + extNumber + "," + priority + ","; - if (line.stream().anyMatch(answer -> answer.substring(0, tmp.length()).compareToIgnoreCase(tmp) == 0)) - { + if (line.stream().anyMatch(answer -> answer.substring(0, tmp.length()).compareToIgnoreCase(tmp) == 0)) { return "OK"; } @@ -1000,26 +821,21 @@ public String addAsteriskExtension(String extNumber, int priority, String comman } @Override - public Trunk buildTrunk(final String trunk) - { - return new Trunk() - { + public Trunk buildTrunk(final String trunk) { + return new Trunk() { @Override - public String getTrunkAsString() - { + public String getTrunkAsString() { return trunk; } }; } - public List getChannelList() - { + public List getChannelList() { return liveChannels.getChannelList(); } - public boolean expectRenameEvents() - { + 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 index fe42b1ce6..7dfb9271a 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/CallEndedListener.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CallEndedListener.java @@ -2,13 +2,11 @@ /** * Used to notify a listener that a Call (CallTracker) has ended. - * + *

    * This generally means the last channel has hungup. - * - * @author bsutton * + * @author bsutton */ -public interface CallEndedListener -{ - void callEnded(CallTracker listener); +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 index 4dc529478..458b612c7 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/CallTracker.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CallTracker.java @@ -1,15 +1,17 @@ package org.asteriskjava.pbx.internal.core; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - +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 @@ -18,17 +20,16 @@ * 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 -{ +public class CallTracker implements ChannelHangupListener { private static final Log logger = LogFactory.getLog(CallTracker.class); /** * The list of channels associated with this call. */ - ArrayList _associatedChannels = new ArrayList<>(); + LockableList _associatedChannels = new LockableList<>(new ArrayList<>()); /** * The state of this call. @@ -37,8 +38,7 @@ public class CallTracker implements ChannelHangupListener private CallEndedListener listener; - CallTracker(Peer peer, Channel initialChannel) - { + CallTracker(Peer peer, Channel initialChannel) { this._associatedChannels.add(initialChannel); initialChannel.addHangupListener(this); this.listener = peer; @@ -51,43 +51,35 @@ public class CallTracker implements ChannelHangupListener * 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) - { - synchronized (this._associatedChannels) - { + 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() - { + public PeerState getState() { return this._state; } /** * @param s */ - public void setState(final ChannelState channelState) - { + public void setState(final ChannelState channelState) { this._state = PeerState.valueByChannelState(channelState); } - public int findChannel(Channel newChannel) - { + public int findChannel(Channel newChannel) { int index = -1; - synchronized (this._associatedChannels) - { + try (LockCloser closer = this._associatedChannels.withLock()) { - for (int i = 0; i < this._associatedChannels.size(); i++) - { + for (int i = 0; i < this._associatedChannels.size(); i++) { Channel channel = this._associatedChannels.get(i); - if (channel.isSame(newChannel)) - { + if (channel.isSame(newChannel)) { index = i; break; } @@ -99,16 +91,13 @@ public int findChannel(Channel newChannel) /** * Remove a channel from the call. - * + * * @param channel */ - public void remove(Channel channel) - { - synchronized (this._associatedChannels) - { + public void remove(Channel channel) { + try (LockCloser closer = this._associatedChannels.withLock()) { int index = findChannel(channel); - if (index != -1) - { + if (index != -1) { if (logger.isDebugEnabled()) logger.debug( "CallTracker removing channel: " + this.toString() + " " + channel.getExtendedChannelName()); //$NON-NLS-1$ //$NON-NLS-2$ @@ -119,26 +108,19 @@ public void remove(Channel channel) } - public void startSweep() - { - synchronized (this._associatedChannels) - { - for (final Channel channel : this._associatedChannels) - { + public void startSweep() { + try (LockCloser closer = this._associatedChannels.withLock()) { + for (final Channel channel : this._associatedChannels) { ((ChannelProxy) channel).getRealChannel().startSweep(); } } } - public void endSweep() - { + public void endSweep() { final List toremove = new LinkedList<>(); - synchronized (this._associatedChannels) - { - for (final Channel channel : this._associatedChannels) - { - if (!((ChannelProxy) channel).getRealChannel().wasMarkedDuringSweep()) - { + 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$ } @@ -148,58 +130,46 @@ public void endSweep() } // Now tell each of the channels it has been hungup - for (final Channel channel : toremove) - { + for (final Channel channel : toremove) { ((ChannelProxy) channel).getRealChannel().notifyHangupListeners(-1, "Lingering channel probably due to missed hangup event"); } } - void dumpChannelList() - { - if (logger.isDebugEnabled()) - { + void dumpChannelList() { + if (logger.isDebugEnabled()) { logger.debug("CallTracker: dump channellist:" + this); //$NON-NLS-1$ - synchronized (this._associatedChannels) - { - for (final Channel channel : this._associatedChannels) - { + try (LockCloser closer = this._associatedChannels.withLock()) { + for (final Channel channel : this._associatedChannels) { logger.debug("--> " + channel.toString()); //$NON-NLS-1$ } } } } - public boolean hasEnded() - { - synchronized (this._associatedChannels) - { + public boolean hasEnded() { + try (LockCloser closer = this._associatedChannels.withLock()) { return this._associatedChannels.size() == 0; } } @Override - public void channelHangup(Channel channel, Integer cause, String causeText) - { + public void channelHangup(Channel channel, Integer cause, String causeText) { remove(channel); - synchronized (this._associatedChannels) - { - if (this._associatedChannels.size() == 0) - { + try (LockCloser closer = this._associatedChannels.withLock()) { + if (this._associatedChannels.size() == 0) { this._state = PeerState.NOTSET; notifyCallEndedListener(); } } } - private void notifyCallEndedListener() - { + private void notifyCallEndedListener() { this.listener.callEnded(this); } - public String toString() - { + 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 index 4ff574bd0..97a64a66b 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/ChannelImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/ChannelImpl.java @@ -1,22 +1,11 @@ package org.asteriskjava.pbx.internal.core; -import java.util.Date; -import java.util.concurrent.TimeUnit; - -import org.asteriskjava.pbx.AgiChannelActivityAction; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ChannelFactory; -import org.asteriskjava.pbx.ChannelHangupListener; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.InvalidChannelName; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXFactory; -import org.asteriskjava.pbx.TechType; +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.
    @@ -34,11 +23,10 @@ * 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 class ChannelImpl implements Channel { public static final String ZOMBIE = ""; //$NON-NLS-1$ public static final String MASQ = ""; //$NON-NLS-1$ @@ -164,20 +152,18 @@ public class ChannelImpl implements Channel * 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 - { + 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) - { + if (uniqueID.compareToIgnoreCase("-1") == 0) { logger.debug("uniqueID is -1"); } @@ -193,24 +179,20 @@ public class ChannelImpl implements Channel * 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) - { + 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()) - { + if (channel.hasCallerID()) { this._callerID = channel.getCallerID(); - } - else if (this._callerID != null && ((ChannelImpl) channel)._callerID != null) - { + } 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()); + if (this._callerID != null) { + ((ChannelImpl) channel)._callerID = pbx.buildCallerID(this._callerID.getNumber(), + this._callerID.getName()); } } @@ -226,8 +208,7 @@ else if (this._callerID != null && ((ChannelImpl) channel)._callerID != null) this._sweepStartTime = null; } - private void setChannelName(final String channelName) throws InvalidChannelName - { + 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); @@ -242,15 +223,11 @@ private void setChannelName(final String channelName) throws InvalidChannelName // 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) - { + 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) - { + } else if (ChannelImpl.logCounter == 0) { ChannelImpl.logger.warn("Further Invalid channel name warnings suppressed"); //$NON-NLS-1$ ChannelImpl.logCounter--; } @@ -260,52 +237,45 @@ else if (ChannelImpl.logCounter == 0) /** * 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)) - { + 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) - { + 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) - { + 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$ + 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) - { + 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) - { + 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$ } @@ -318,12 +288,11 @@ private void validateChannelName(final String channelName) throws InvalidChannel * 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) - { + private String cleanChannelName(final String name) { String cleanedName = name.trim().toUpperCase(); // If if the channel is the console @@ -336,19 +305,17 @@ private String cleanChannelName(final String name) // 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)) - { + 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); + 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 @@ -356,8 +323,7 @@ private String cleanChannelName(final String name) // as a // zombie. this._isZombie = false; - if (cleanedName.contains(ChannelImpl.ZOMBIE)) - { + if (cleanedName.contains(ChannelImpl.ZOMBIE)) { this._isZombie = true; cleanedName = cleanedName.substring(0, cleanedName.indexOf(ChannelImpl.ZOMBIE)); } @@ -369,8 +335,7 @@ private String cleanChannelName(final String name) // word // added as a suffix. this._isMasqueraded = false; - if (cleanedName.contains(ChannelImpl.MASQ)) - { + if (cleanedName.contains(ChannelImpl.MASQ)) { this._isMasqueraded = true; cleanedName = cleanedName.substring(0, cleanedName.indexOf(ChannelImpl.MASQ)); } @@ -379,15 +344,13 @@ private String cleanChannelName(final String name) } @Override - public void rename(final String newName, String uniqueId) throws InvalidChannelName - { + 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")) - { + if (_uniqueID.equalsIgnoreCase("-1")) { logger.info("Changing " + _uniqueID + " to " + uniqueId + " on " + oldChannelName + " " + _uniqueID); _uniqueID = uniqueId; } @@ -403,14 +366,12 @@ public void rename(final String newName, String uniqueId) throws InvalidChannelN } @Override - public String getChannelName() - { + public String getChannelName() { return this._channelName; } @Override - public EndPoint getEndPoint() - { + public EndPoint getEndPoint() { return this._endPoint; } @@ -422,12 +383,10 @@ public EndPoint getEndPoint() * form: DAHDI/i/[:]-0000000123 With the peer name * of the form: DAHDI/i/[:] */ - private final String extractPeerName(final String channelName) - { + private final String extractPeerName(final String channelName) { // Find the start of the sequence number int channelNameEndPoint = channelName.lastIndexOf("-"); //$NON-NLS-1$ - if (channelNameEndPoint == -1) - { + if (channelNameEndPoint == -1) { channelNameEndPoint = channelName.length(); } // return the peer name which is everything before the sequence number @@ -435,19 +394,17 @@ private final String extractPeerName(final String channelName) return channelName.substring(0, channelNameEndPoint); } - boolean wasMarkedDuringSweep() - { + boolean wasMarkedDuringSweep() { boolean ret = false; - if (this._sweepStartTime == null || this._marked) - { + if (this._sweepStartTime == null || this._marked) { this._sweepStartTime = null; ret = true; } return ret; } - public void setCallerId(final CallerID callerId) - { + @Override + public void setCallerId(final CallerID callerId) { this._callerID = callerId; } @@ -456,17 +413,15 @@ public void setCallerId(final CallerID callerId) * 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 = new Date().getTime(); + 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() - { + void markChannel() { this._marked = true; } @@ -479,66 +434,49 @@ void markChannel() * ************************** */ @Override - public boolean isSame(final Channel _rhs) - { + public boolean isSame(final Channel _rhs) { boolean equals = false; - if (_rhs == null) - { + if (_rhs == null) { logger.warn("isSame called with null"); return false; } ChannelImpl rhs; - if (_rhs instanceof ChannelImpl) - { + if (_rhs instanceof ChannelImpl) { rhs = (ChannelImpl) _rhs; - } - else - { + } 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) - { + && (rhs._uniqueID.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0)) { + if (this._uniqueID.compareToIgnoreCase(rhs._uniqueID) == 0) { equals = true; } - } - else - { + } else { boolean ok = (this._channelName != null) && (rhs._channelName != null); final boolean namesMatch = (ok && (this._channelName.compareToIgnoreCase(rhs._channelName) == 0)); - if (namesMatch) - { + if (namesMatch) { // check if the actions match - if (this._isInAction != rhs._isInAction) - { + if (this._isInAction != rhs._isInAction) { ok = false; - } - else if (this._isInAction) - { + } else if (this._isInAction) { ok = this._actionPrefix.compareTo(rhs._actionPrefix) == 0; } } - if (ok && namesMatch) - { + if (ok && namesMatch) { // check if the zombie match - if (this._isZombie != rhs._isZombie) - { + if (this._isZombie != rhs._isZombie) { ok = false; } } - if (ok && namesMatch) - { + if (ok && namesMatch) { // check if the masquerade match - if (this._isMasqueraded != rhs._isMasqueraded) - { + if (this._isMasqueraded != rhs._isMasqueraded) { ok = false; } } @@ -549,19 +487,14 @@ else if (this._isInAction) } @Override - public boolean isSame(final String extendedChannelName, final String uniqueID) - { + 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) - { + && (uniqueID.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0)) { + if (this._uniqueID.compareTo(uniqueID) == 0) { equals = true; } - } - else - { + } else { equals = this.sameExtenededChannelName(extendedChannelName); } @@ -569,8 +502,7 @@ public boolean isSame(final String extendedChannelName, final String uniqueID) } @Override - public boolean sameExtenededChannelName(final String extendedChannelName) - { + public boolean sameExtenededChannelName(final String extendedChannelName) { boolean ok = (this.getExtendedChannelName() != null) && (extendedChannelName != null); return ok && (this.getExtendedChannelName().compareToIgnoreCase(extendedChannelName) == 0); @@ -578,18 +510,15 @@ public boolean sameExtenededChannelName(final String extendedChannelName) /** * Try to match a channel based solely on its unique ID - * + * * @param uniqueID * @return */ - public boolean sameUniqueID(String uniqueID) - { + 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) - { + && (uniqueID.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0)) { + if (this._uniqueID.compareTo(uniqueID) == 0) { equals = true; } } @@ -598,33 +527,28 @@ public boolean sameUniqueID(String uniqueID) } @Override - public boolean sameEndPoint(final Channel rhs) - { + public boolean sameEndPoint(final Channel rhs) { return this.sameEndPoint(rhs.getEndPoint()); } @Override - public boolean sameEndPoint(final EndPoint rhs) - { + public boolean sameEndPoint(final EndPoint rhs) { boolean ok = (this._endPoint != null) && (rhs != null); return ok && this._endPoint.isSame(rhs); } @Override - public long getChannelId() - { + public long getChannelId() { return this._channelId; } @Override - public boolean isLive() - { + public boolean isLive() { return this._isLive; } @Override - public void addHangupListener(final ChannelHangupListener listener) - { + 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$ @@ -632,8 +556,7 @@ public void addHangupListener(final ChannelHangupListener listener) } @Override - public void removeListener(final ChannelHangupListener listener) - { + 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$ @@ -649,143 +572,144 @@ public void removeListener(final ChannelHangupListener listener) * has been hung up. */ @Override - public void notifyHangupListeners(Integer cause, String causeText) - { + public void notifyHangupListeners(Integer cause, String causeText) { this._isLive = false; - if (this.hangupListener != null) - { + if (this.hangupListener != null) { this.hangupListener.channelHangup(this, cause, causeText); - } - else - { + } else { logger.warn("Hangup listener is null"); } } @Override - public boolean isConnectedTo(final EndPoint endPoint) - { + public boolean isConnectedTo(final EndPoint endPoint) { return this._endPoint.isSame(endPoint); } @Override - public boolean isMute() - { + public boolean isMute() { return this._muted; } @Override - public void setMute(final boolean mutedState) - { + public void setMute(final boolean mutedState) { this._muted = mutedState; } @Override - public void setParked(final boolean parked) - { + public void setParked(final boolean parked) { this._parked = parked; } @Override - public boolean isParked() - { + public boolean isParked() { return this._parked; } @Override - public String toString() - { + 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() - { - final StringBuilder name = new StringBuilder(); + 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._isInAction) { + name.append(this._actionPrefix); + name.append("/"); //$NON-NLS-1$ + } + name.append(this._channelName); - if (this._isMasqueraded) - { - name.append(ChannelImpl.MASQ); - } + if (this._isMasqueraded) { + name.append(ChannelImpl.MASQ); + } + + if (this._isZombie) { + name.append(ChannelImpl.ZOMBIE); + } + lastState = state; + lastChannelName = _channelName; + cachedExtenedChannelName = name.toString(); - if (this._isZombie) - { - name.append(ChannelImpl.ZOMBIE); } + return cachedExtenedChannelName; - return name.toString(); + } + 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() - { + public boolean isLocal() { return this._endPoint.isLocal(); } @Override - public boolean isZombie() - { + public boolean isZombie() { return this._isZombie; } @Override - public boolean isConsole() - { + public boolean isConsole() { return this._isConsole; } - TechType getTech() - { + 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() - { + String getActionPrefix() { return this._isInAction ? this._actionPrefix : ""; //$NON-NLS-1$ } - boolean isInAction() - { + boolean isInAction() { return this._isInAction; } - boolean isMasqueraded() - { + boolean isMasqueraded() { return this._isMasqueraded; } @Override - public boolean hasCallerID() - { + public boolean hasCallerID() { return this._callerID != null && !this._callerID.isUnknown(); } @Override - public CallerID getCallerID() - { - if (this._callerID == null) - { + 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$ @@ -798,8 +722,7 @@ public CallerID getCallerID() } @Override - public String getUniqueId() - { + public String getUniqueId() { return this._uniqueID; } @@ -812,14 +735,12 @@ public String getUniqueId() * never hangup. */ @Override - public boolean canDetectHangup() - { + public boolean canDetectHangup() { boolean canDetectHangup = true; AsteriskSettings profile = PBXFactory.getActiveProfile(); final boolean detect = profile.getCanDetectHangup(); - if (!this.getEndPoint().isSIP() && !detect) - { + if (!this.getEndPoint().isSIP() && !detect) { canDetectHangup = false; } return canDetectHangup; @@ -829,42 +750,36 @@ public boolean 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() - { + public boolean isQuiescent() { return !(_isInAction || _isMasqueraded || _isZombie); } @Override - public AgiChannelActivityAction getCurrentActivityAction() - { + public AgiChannelActivityAction getCurrentActivityAction() { throw new RuntimeException("This method is only implemented in ChannelProxy"); } @Override - public void setCurrentActivityAction(AgiChannelActivityAction action) - { + public void setCurrentActivityAction(AgiChannelActivityAction action) { throw new RuntimeException("This method is only implemented in ChannelProxy"); } @Override - public void setIsInAgi(boolean b) - { + public void setIsInAgi(boolean b) { throw new RuntimeException("This method is only implemented in ChannelProxy"); } @Override - public boolean isInAgi() - { + public boolean isInAgi() { throw new RuntimeException("This method is only implemented in ChannelProxy"); } @Override - public boolean waitForChannelToReachAgi(long timeout, TimeUnit timeunit) throws InterruptedException - { + 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 index 4662d6932..40dd823b2 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/ChannelProxy.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/ChannelProxy.java @@ -1,5 +1,10 @@ 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; @@ -7,16 +12,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import org.asteriskjava.pbx.AgiChannelActivityAction; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ChannelHangupListener; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.InvalidChannelName; -import org.asteriskjava.pbx.agi.AgiChannelActivityHold; -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; - /** * 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 @@ -24,11 +19,10 @@ * 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 -{ +public class ChannelProxy implements Channel, ChannelHangupListener { private static final Log logger = LogFactory.getLog(ChannelProxy.class); @@ -43,8 +37,7 @@ public class ChannelProxy implements Channel, ChannelHangupListener private final List listeners = new CopyOnWriteArrayList<>(); - public ChannelProxy(ChannelImpl channel) - { + public ChannelProxy(ChannelImpl channel) { this._channel = channel; currentActivityAction.set(new AgiChannelActivityHold()); @@ -54,161 +47,136 @@ public ChannelProxy(ChannelImpl channel) /** * returns the current channel - * + * * @return */ - public Channel getChannel() - { + public Channel getChannel() { return this._channel; } @Override - public boolean isSame(Channel rhs) - { + public boolean isSame(Channel rhs) { return this._channel.isSame(rhs); } @Override - public boolean isSame(String extendedChannelName, String uniqueID) - { + public boolean isSame(String extendedChannelName, String uniqueID) { return this._channel.isSame(extendedChannelName, uniqueID); } - public boolean sameUniqueID(String uniqueID) - { + public boolean sameUniqueID(String uniqueID) { return this._channel.sameUniqueID(uniqueID); } @Override - public boolean sameEndPoint(Channel rhs) - { + public boolean sameEndPoint(Channel rhs) { return this._channel.sameEndPoint(rhs); } @Override - public boolean sameEndPoint(EndPoint extensionRoaming) - { + public boolean sameEndPoint(EndPoint extensionRoaming) { return this._channel.sameEndPoint(extensionRoaming); } @Override - public boolean sameExtenededChannelName(String channelName) - { + public boolean sameExtenededChannelName(String channelName) { return this._channel.sameExtenededChannelName(channelName); } @Override - public void setParked(boolean parked) - { + public void setParked(boolean parked) { this._channel.setParked(parked); } @Override - public void setMute(boolean muteState) - { + public void setMute(boolean muteState) { this._channel.setMute(muteState); } @Override - public long getChannelId() - { + public long getChannelId() { return this._channel.getChannelId(); } @Override - public boolean isLive() - { + public boolean isLive() { return this._channel.isLive(); } @Override - public void addHangupListener(ChannelHangupListener listener) - { - if (!listeners.contains(listener)) - { + public void addHangupListener(ChannelHangupListener listener) { + if (!listeners.contains(listener)) { this.listeners.add(listener); } } @Override - public void removeListener(ChannelHangupListener listener) - { + public void removeListener(ChannelHangupListener listener) { this.listeners.remove(listener); } @Override - public boolean isConnectedTo(EndPoint endPoint) - { + public boolean isConnectedTo(EndPoint endPoint) { return this._channel.isConnectedTo(endPoint); } @Override - public String getChannelName() - { + public String getChannelName() { return this._channel.getChannelName(); } @Override - public EndPoint getEndPoint() - { + public EndPoint getEndPoint() { return this._channel.getEndPoint(); } @Override - public boolean isMute() - { + public boolean isMute() { return this._channel.isMute(); } @Override - public boolean isLocal() - { + public boolean isLocal() { return this._channel.isLocal(); } @Override - public boolean isZombie() - { + public boolean isZombie() { return this._channel.isZombie(); } @Override - public boolean isConsole() - { + public boolean isConsole() { return this._channel.isConsole(); } @Override - public CallerID getCallerID() - { + public CallerID getCallerID() { return this._channel.getCallerID(); } @Override - public void rename(String newName, String uniqueId) throws InvalidChannelName - { + public void rename(String newName, String uniqueId) throws InvalidChannelName { this._channel.rename(newName, uniqueId); } @Override - public boolean isParked() - { + 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 - { + public void masquerade(ChannelProxy cloneProxy) throws InvalidChannelName { ChannelImpl originalChannel = this._channel; ChannelImpl cloneChannel = cloneProxy._channel; @@ -229,29 +197,24 @@ public void masquerade(ChannelProxy cloneProxy) throws InvalidChannelName logger.debug(originalChannel + " Channel proxy now points to " + this._channel); } - public ChannelImpl getRealChannel() - { + public ChannelImpl getRealChannel() { return this._channel; } @Override - public String getExtendedChannelName() - { + 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) - { + public void notifyHangupListeners(Integer cause, String causeText) { + for (ChannelHangupListener listener : this.listeners) { listener.channelHangup(this, cause, causeText); } - if (hangupCalled) - { + if (hangupCalled) { logger.error("Hangup was already called and the listeners removed - OH NO"); } // we will blow up if notify listeners is called again @@ -261,14 +224,12 @@ public void notifyHangupListeners(Integer cause, String causeText) } @Override - public String toString() - { + 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) - { + 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) @@ -277,20 +238,17 @@ public void channelHangup(Channel channel, Integer cause, String causeText) } @Override - public boolean canDetectHangup() - { + public boolean canDetectHangup() { return this._channel.canDetectHangup(); } @Override - public boolean isQuiescent() - { + public boolean isQuiescent() { return this._channel.isQuiescent(); } @Override - public boolean hasCallerID() - { + public boolean hasCallerID() { return this._channel.hasCallerID(); } @@ -299,8 +257,7 @@ public boolean hasCallerID() * @see java.lang.Object#hashCode() */ @Override - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _identity; @@ -312,23 +269,18 @@ public int hashCode() * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(Object obj) - { - if (this == obj) - { + public boolean equals(Object obj) { + if (this == obj) { return true; } - if (obj == null) - { + if (obj == null) { return false; } - if (!(obj instanceof ChannelProxy)) - { + if (!(obj instanceof ChannelProxy)) { return false; } ChannelProxy other = (ChannelProxy) obj; - if (_identity != other._identity) - { + if (_identity != other._identity) { return false; } return true; @@ -338,14 +290,12 @@ public boolean equals(Object obj) volatile private boolean isInAgi; @Override - public AgiChannelActivityAction getCurrentActivityAction() - { + public AgiChannelActivityAction getCurrentActivityAction() { return currentActivityAction.get(); } @Override - public void setCurrentActivityAction(AgiChannelActivityAction action) - { + public void setCurrentActivityAction(AgiChannelActivityAction action) { AgiChannelActivityAction previousAction = currentActivityAction.get(); logger.debug("Setting action to " + action.getClass().getSimpleName() + " for " + this); @@ -355,53 +305,48 @@ public void setCurrentActivityAction(AgiChannelActivityAction action) // logger.warn(e, e); currentActivityAction.set(action); - if (previousAction != null) - { + 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) - { + public void setIsInAgi(boolean b) { + if (b) { hasReachedAgi.countDown(); } isInAgi = b; - logger.debug("Setting is in agi to " + b + " for channel " + this); + logger.info("Setting is in agi to " + b + " for channel " + this); } @Override - public boolean isInAgi() - { + public boolean isInAgi() { return isInAgi; } final CountDownLatch hasReachedAgi = new CountDownLatch(1); @Override - public boolean waitForChannelToReachAgi(long timeout, TimeUnit timeunit) throws InterruptedException - { - return hasReachedAgi.await(timeout, timeunit); + 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() - { + public String getUniqueId() { return _channel.getUniqueId(); } - public int getIdentity() - { + public int getIdentity() { return _identity; } @Override - public void setCallerId(CallerID callerId) - { + 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 index c90c6c39f..454a2ff9d 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/CoherentEventFactory.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentEventFactory.java @@ -1,11 +1,5 @@ package org.asteriskjava.pbx.internal.core; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; -import java.util.Hashtable; -import java.util.Set; - import org.asteriskjava.pbx.asterisk.wrap.actions.ManagerAction; import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; import org.asteriskjava.pbx.asterisk.wrap.events.ResponseEvent; @@ -16,6 +10,12 @@ 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. @@ -23,72 +23,53 @@ * @author bsutton */ @SuppressWarnings({"unchecked"}) -public class CoherentEventFactory -{ +public class CoherentEventFactory { private static final Log logger = LogFactory.getLog(CoherentEventFactory.class); // Events static Hashtable, Class> mapEvents = new Hashtable<>(); // Response - static Hashtable, Class< ? extends ResponseEvent>> mapResponses = new Hashtable<>(); + static Hashtable, Class> mapResponses = new Hashtable<>(); // static initialiser - static - { + static { - Set> knownClasses = ReflectionUtil.loadClasses("org.asteriskjava.pbx.asterisk.wrap.events", + 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 - { + 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)) - { + 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 - { + } else { CoherentEventFactory.mapEvents.put((Class) clazz, (Class) known); logger.info("Manager Event Added " + clazz + " --> " + known); } - } - else - { + } else { logger.warn("Skipping class " + clazz + " it doesn't have a public constructor with one arg of type " + known); } - } - else - { + } else { logger.info("Skipping abstract class " + clazz); } - } - catch (ClassNotFoundException e) - { + } catch (ClassNotFoundException e) { logger.error(e, e); throw new RuntimeException(e); - } - catch (NoSuchMethodException e) - { + } catch (NoSuchMethodException e) { logger.error(clazz.getCanonicalName() + " doesn't have an appropriate event constructor"); - } - catch (SecurityException e) - { + } catch (SecurityException e) { logger.error(e, e); } } @@ -97,12 +78,10 @@ public class CoherentEventFactory } - public static Class< ? extends ManagerEvent> getShadowEvent(org.asteriskjava.manager.event.ManagerEvent event) - { - Class< ? extends ManagerEvent> result = CoherentEventFactory.mapEvents.get(event.getClass()); - if (result == null) - { - Class< ? extends ResponseEvent> response = CoherentEventFactory.mapResponses.get(event.getClass()); + 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; } @@ -110,31 +89,24 @@ public class CoherentEventFactory } - public static ManagerEvent build(final org.asteriskjava.manager.event.ManagerEvent event) - { + public static ManagerEvent build(final org.asteriskjava.manager.event.ManagerEvent event) { ManagerEvent iEvent = null; - Class< ? extends ManagerEvent> target = 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) - { + if (target == null) { logger.warn("The given event " + event.getClass().getName() + " is not supported "); //$NON-NLS-1$ //$NON-NLS-2$ - } - else - { + } else { - try - { + try { iEvent = target.getDeclaredConstructor(event.getClass()).newInstance(event); - } - catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) - { + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { CoherentEventFactory.logger.error(e, e); } @@ -142,28 +114,21 @@ public static ManagerEvent build(final org.asteriskjava.manager.event.ManagerEve return iEvent; } - public static ResponseEvent build(org.asteriskjava.manager.event.ResponseEvent event) - { + public static ResponseEvent build(org.asteriskjava.manager.event.ResponseEvent event) { ResponseEvent response = null; - final Class< ? extends ResponseEvent> target = CoherentEventFactory.mapResponses.get(event.getClass()); + final Class target = CoherentEventFactory.mapResponses.get(event.getClass()); - if (target == null) - { + if (target == null) { logger.warn("The given event " + event.getClass().getName() + " is not supported "); //$NON-NLS-1$ //$NON-NLS-2$ - } - else - { + } else { - try - { - final Constructor< ? extends ResponseEvent> declaredConstructor = target + try { + final Constructor declaredConstructor = target .getDeclaredConstructor(event.getClass()); response = declaredConstructor.newInstance(event); - } - catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) - { + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { CoherentEventFactory.logger.error(e, e); } @@ -171,27 +136,20 @@ public static ResponseEvent build(org.asteriskjava.manager.event.ResponseEvent e return response; } - public static ManagerResponse build(org.asteriskjava.manager.response.ManagerResponse response) - { + public static ManagerResponse build(org.asteriskjava.manager.response.ManagerResponse response) { ManagerResponse result; - if (response instanceof org.asteriskjava.manager.response.CommandResponse) - { + if (response instanceof org.asteriskjava.manager.response.CommandResponse) { result = new CommandResponse(response); - } - else if (response instanceof org.asteriskjava.manager.response.ManagerError) - { + } else if (response instanceof org.asteriskjava.manager.response.ManagerError) { result = new ManagerError(response); - } - else - { + } else { result = new ManagerResponse(response); } return result; } - public static org.asteriskjava.manager.action.ManagerAction build(ManagerAction action) - { + public static org.asteriskjava.manager.action.ManagerAction build(ManagerAction action) { org.asteriskjava.manager.action.ManagerAction result = null; // final Class diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java index 1a6393363..fd73f2fd8 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerConnection.java @@ -1,31 +1,9 @@ package org.asteriskjava.pbx.internal.core; -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; - -import javax.naming.OperationNotSupportedException; - import org.asteriskjava.AsteriskVersion; -import org.asteriskjava.manager.AuthenticationFailedException; -import org.asteriskjava.manager.EventTimeoutException; -import org.asteriskjava.manager.ManagerConnection; -import org.asteriskjava.manager.ManagerConnectionState; -import org.asteriskjava.manager.TimeoutException; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; -import org.asteriskjava.pbx.asterisk.wrap.actions.EventGeneratingAction; -import org.asteriskjava.pbx.asterisk.wrap.actions.GetVarAction; -import org.asteriskjava.pbx.asterisk.wrap.actions.ListCommandsAction; -import org.asteriskjava.pbx.asterisk.wrap.actions.ManagerAction; -import org.asteriskjava.pbx.asterisk.wrap.actions.SetVarAction; +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; @@ -35,6 +13,14 @@ 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.
    *
    @@ -64,12 +50,11 @@ * 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! + * events for any action are distributed to all listeners! */ -class CoherentManagerConnection implements FilteredManagerListener -{ +class CoherentManagerConnection implements FilteredManagerListener { static private Log logger = LogFactory.getLog(CoherentManagerConnection.class); @@ -116,32 +101,23 @@ class CoherentManagerConnection implements FilteredManagerListener private boolean expectRenameEvents = true; public static synchronized void init() - throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException, InterruptedException - { + throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException, InterruptedException { if (self != null) - logger.warn("The CoherentManagerConnection has already been initialised"); //$NON-NLS-1$ - else - { + logger.warn("The CoherentManagerConnection has already been initialised"); + else { self = new CoherentManagerConnection(); boolean done = false; - while (!done) - { - try - { + while (!done) { + try { self.checkConnection(); self.checkFeatures(); done = true; - } - catch (Exception e) - { + } catch (Exception e) { logger.error(e, e); - try - { + try { TimeUnit.MILLISECONDS.sleep(500); - } - catch (InterruptedException e1) - { + } catch (InterruptedException e1) { throw e1; } } @@ -151,15 +127,13 @@ public static synchronized void init() self.checkConnection(); } - public static void reset() - { + public static void reset() { self = null; } - public static synchronized CoherentManagerConnection getInstance() - { + public static synchronized CoherentManagerConnection getInstance() { if (self == null) - throw new IllegalStateException("The CoherentManagerConnection has not been initialised"); //$NON-NLS-1$ + throw new IllegalStateException("The CoherentManagerConnection has not been initialised"); self.checkConnection(); @@ -167,22 +141,18 @@ public static synchronized CoherentManagerConnection getInstance() } private CoherentManagerConnection() - throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException - { + throws IllegalStateException, IOException, AuthenticationFailedException, TimeoutException { super(); connector = new Connector(); this.configureConnection(); } - public AsteriskVersion getVersion() throws IllegalStateException - { + public AsteriskVersion getVersion() throws IllegalStateException { return CoherentManagerConnection.managerConnection.getVersion(); } - public void setVariable(final Channel channel, final String variableName, final String value) throws PBXException - { - try - { + 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. @@ -195,21 +165,16 @@ public void setVariable(final Channel channel, final String variableName, final 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$ - { + if ((response != null) && (response.getResponse().compareToIgnoreCase("success") == 0)) { // $NON-NLS-1$ - CoherentManagerConnection.logger.debug("set variable " + variableName + " to " + value //$NON-NLS-1$ //$NON-NLS-2$ - + " on " + channel); //$NON-NLS-1$ - } - else - { - throw new PBXException("failed to set variable '" + variableName + "' on channel " + channel + " to '" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - + value + "'" + (response != null ? " Error:" + response.getMessage() : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + 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) - { + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { logger.error(e, e); throw new PBXException(e); @@ -220,35 +185,30 @@ public void setVariable(final Channel channel, final String variableName, final /** * 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) - { + public String getVariable(final Channel channel, final String variableName) { String value = ""; final GetVarAction var = new GetVarAction(channel, variableName); - try - { + 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"); //$NON-NLS-1$ + if (convertedResponse != null) { + value = convertedResponse.getAttribute("value"); if (value == null) value = ""; - CoherentManagerConnection.logger.debug("getVarAction returned name:" + variableName + " value:" + value); //$NON-NLS-1$ //$NON-NLS-2$ + CoherentManagerConnection.logger.debug("getVarAction returned name:" + variableName + " value:" + value); //$NON-NLS-2$ } - } - catch (final Exception e) - { + } catch (final Exception e) { CoherentManagerConnection.logger.debug(e, e); - CoherentManagerConnection.logger.error("getVariable: " + e); //$NON-NLS-1$ + CoherentManagerConnection.logger.error("getVariable: " + e); } return value; } @@ -257,40 +217,32 @@ public String getVariable(final Channel channel, final String variableName) * 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() - { + public static void sendActionNoWait(final ManagerAction action) { + final Thread background = new Thread() { @Override - public void run() - { - try - { + public void run() { + try { CoherentManagerConnection.sendAction(action, 5000); - } - catch (final Exception e) - { + } catch (final Exception e) { CoherentManagerConnection.logger.error(e, e); } } }; - background.setName("sendActionNoWait"); //$NON-NLS-1$ + background.setName("sendActionNoWait"); background.setDaemon(true); background.start(); } public static ResponseEvents sendEventGeneratingAction(EventGeneratingAction action) - throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException - { + 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()) - { + for (org.asteriskjava.manager.event.ResponseEvent event : events.getEvents()) { convertedEvents.add(CoherentEventFactory.build(event)); } return convertedEvents; @@ -298,14 +250,12 @@ public static ResponseEvents sendEventGeneratingAction(EventGeneratingAction act } public static ResponseEvents sendEventGeneratingAction(EventGeneratingAction action, int timeout) - throws EventTimeoutException, IllegalArgumentException, IllegalStateException, IOException - { + 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()) - { + for (org.asteriskjava.manager.event.ResponseEvent event : events.getEvents()) { convertedEvents.add(CoherentEventFactory.build(event)); } return convertedEvents; @@ -314,7 +264,7 @@ public static ResponseEvents sendEventGeneratingAction(EventGeneratingAction act /** * Sends an Asterisk action and waits for a ManagerRespose. - * + * * @param action * @param timeout timeout in milliseconds * @return @@ -325,15 +275,13 @@ public static ResponseEvents sendEventGeneratingAction(EventGeneratingAction act * @throws OperationNotSupportedException */ public static ManagerResponse sendAction(final ManagerAction action, final int timeout) - throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException - { + throws IllegalArgumentException, IllegalStateException, IOException, TimeoutException { if (logger.isDebugEnabled()) - CoherentManagerConnection.logger.debug("Sending Action: " + action.toString()); //$NON-NLS-1$ + CoherentManagerConnection.logger.debug("Sending Action: " + action.toString()); CoherentManagerConnection.getInstance(); if ((CoherentManagerConnection.managerConnection != null) - && (CoherentManagerConnection.managerConnection.getState() == ManagerConnectionState.CONNECTED)) - { + && (CoherentManagerConnection.managerConnection.getState() == ManagerConnectionState.CONNECTED)) { final org.asteriskjava.manager.action.ManagerAction ajAction = action.getAJAction(); org.asteriskjava.manager.response.ManagerResponse response = CoherentManagerConnection.managerConnection @@ -344,50 +292,41 @@ public static ManagerResponse sendAction(final ManagerAction action, final int t if (response != null) convertedResponse = CoherentEventFactory.build(response); - if ((convertedResponse != null) && (convertedResponse.getResponse().compareToIgnoreCase("Error") == 0))//$NON-NLS-1$ - { - CoherentManagerConnection.logger.warn("Action '" + ajAction + "' failed, Response: " //$NON-NLS-1$ //$NON-NLS-2$ - + convertedResponse.getResponse() + " Message: " + convertedResponse.getMessage()); //$NON-NLS-1$ + 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."); //$NON-NLS-1$ + throw new IllegalStateException("not connected."); } - private void checkConnection() - { + 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"); //$NON-NLS-1$ + || (CoherentManagerConnection.managerConnection.getState() != ManagerConnectionState.CONNECTED))) { + if (trys == 3) { + CoherentManagerConnection.logger.warn("Awaiting Manager connection"); } - try - { + try { this._reconnectLatch.await(300, TimeUnit.MILLISECONDS); - } - catch (final InterruptedException e) - { + } catch (final InterruptedException e) { CoherentManagerConnection.logger.error(e, e); } trys--; } } - public ManagerConnectionState getState() - { + public ManagerConnectionState getState() { return CoherentManagerConnection.managerConnection.getState(); } private void configureConnection() - throws IOException, AuthenticationFailedException, TimeoutException, IllegalStateException - { + throws IOException, AuthenticationFailedException, TimeoutException, IllegalStateException { final AsteriskSettings profile = PBXFactory.getActiveProfile(); CoherentManagerConnection.managerConnection = CoherentManagerConnection.connector.connect(profile); @@ -398,27 +337,24 @@ private void configureConnection() // that it hasn't already) // and should have no duplicate events. Once drained the queue will be // garbage collected. - CoherentManagerEventQueue newRealtime = new CoherentManagerEventQueue("Realtime", //$NON-NLS-1$ + CoherentManagerEventQueue newRealtime = new CoherentManagerEventQueue("Realtime", CoherentManagerConnection.managerConnection); - if (this.realtimeEventQueue != null) - { + if (this.realtimeEventQueue != null) { this.realtimeEventQueue.stop(); newRealtime.transferListeners(this.realtimeEventQueue); } this.realtimeEventQueue = newRealtime; - CoherentManagerEventQueue newStandard = new CoherentManagerEventQueue("Standard", //$NON-NLS-1$ + CoherentManagerEventQueue newStandard = new CoherentManagerEventQueue("Standard", CoherentManagerConnection.managerConnection); - if (this.eventQueue != null) - { + if (this.eventQueue != null) { this.eventQueue.stop(); newStandard.transferListeners(this.eventQueue); } this.eventQueue = newStandard; } - private void checkFeatures() throws IOException, TimeoutException - { + private void checkFeatures() throws IOException, TimeoutException { final AsteriskSettings profile = PBXFactory.getActiveProfile(); // Determine if the Bridge and Mute events are available. @@ -426,60 +362,46 @@ private void checkFeatures() throws IOException, TimeoutException ManagerResponse convertedResponse = sendAction(lca, 500); boolean bridgeFound = false; boolean muteAudioFound = false; - for (final String command : convertedResponse.getAttributes().keySet()) - { - if (command.toLowerCase().contains("bridge")) //$NON-NLS-1$ - { + for (final String command : convertedResponse.getAttributes().keySet()) { + if (command.toLowerCase().contains("bridge")) { bridgeFound = true; } - if (command.toLowerCase().contains("muteaudio")) //$NON-NLS-1$ - { + if (command.toLowerCase().contains("muteaudio")) { muteAudioFound = true; } } - if (CoherentManagerConnection.managerConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_13)) - { + 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()) - { + if (profile.getDisableBridge()) { this.canBridge = false; - } - else - { + } else { this.canBridge = bridgeFound; } } - public void shutDown() - { + public void shutDown() { CoherentManagerConnection.managerConnection.removeEventListener(this.eventQueue); this.eventQueue.stop(); - try - { + try { CoherentManagerConnection.managerConnection.logoff(); - } - catch (final Exception e) - { - CoherentManagerConnection.logger.debug("Manager logging off"); //$NON-NLS-1$ + } catch (final Exception e) { + CoherentManagerConnection.logger.debug("Manager logging off"); CoherentManagerConnection.logger.debug(e, e); } } - public boolean isBridgeSupported() - { + public boolean isBridgeSupported() { return this.canBridge; } - public boolean isMuteAudioSupported() - { + public boolean isMuteAudioSupported() { return this.canMuteAudio; } - public void removeListener(FilteredManagerListener listener) - { + public void removeListener(FilteredManagerListener listener) { if (listener.getPriority() == ListenerPriority.REALTIME) this.realtimeEventQueue.removeListener(listener); else @@ -487,8 +409,7 @@ public void removeListener(FilteredManagerListener listener) } - public void addListener(FilteredManagerListener listener) - { + public void addListener(FilteredManagerListener listener) { if (listener.getPriority() == ListenerPriority.REALTIME) this.realtimeEventQueue.addListener(listener); else @@ -497,42 +418,35 @@ public void addListener(FilteredManagerListener listener) } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(ConnectEvent.class); required.add(DisconnectEvent.class); return required; } @Override - public String getName() - { - return "CoherentManagerConnection"; //$NON-NLS-1$ + public String getName() { + return "CoherentManagerConnection"; } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.REALTIME; } @Override - public void onManagerEvent(ManagerEvent event) - { + 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 **************************"); //$NON-NLS-1$ + if (event instanceof ConnectEvent) { + logger.warn("****************** Asterisk manager connection acquired **************************"); this._reconnectLatch.countDown(); - } - else if (event instanceof DisconnectEvent) - { - logger.warn("****************** Asterisk manager connection lost **************************"); //$NON-NLS-1$ + } else if (event instanceof DisconnectEvent) { + logger.warn("****************** Asterisk manager connection lost **************************"); // new Thread(new Runnable() // { // public void run() @@ -544,8 +458,7 @@ else if (event instanceof DisconnectEvent) } - public boolean expectRenameEvents() - { + 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 index c5aa4799d..62776b976 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventListener.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventListener.java @@ -1,16 +1,14 @@ package org.asteriskjava.pbx.internal.core; -import java.util.EventListener; - import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; -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); +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 index 84fb33e2b..213520fe6 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventQueue.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/CoherentManagerEventQueue.java @@ -1,16 +1,7 @@ package org.asteriskjava.pbx.internal.core; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - +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; @@ -22,6 +13,12 @@ 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 @@ -30,36 +27,32 @@ * follows: manager.addEventListener(new * CoherentManagerEventQueue(originalListener)); This affectively daisy changes * the originalListener via our queue. - * + * * @author bsutton */ -class CoherentManagerEventQueue implements ManagerEventListener, Runnable -{ +class CoherentManagerEventQueue implements ManagerEventListener, Runnable { private static final Log logger = LogFactory.getLog(CoherentManagerEventQueue.class); private final ListenerManager listeners = new ListenerManager(); - private boolean _stop = false; - private final Thread _th; - private final BlockingQueue> _eventQueue = new LinkedBlockingQueue<>(); + private volatile boolean _stop = false; - private int _queueMaxSize; + private static final int QUEUE_SIZE = 1000; + private final BlockingQueue> _eventQueue = new LinkedBlockingQueue<>( + QUEUE_SIZE); - private long _queueSum; + long suppressQueueSizeErrorUntil = 0; - private long _queueCount; + private LockableSet> globalEvents = new LockableSet<>(new HashSet<>()); - private HashSet> globalEvents = new HashSet<>(); - - public CoherentManagerEventQueue(String name, ManagerConnection connection) - { + public CoherentManagerEventQueue(String name, ManagerConnection connection) { connection.addEventListener(this); - this._th = new Thread(this); - this._th.setName("EventQueue: " + name);//$NON-NLS-1$ - this._th.setDaemon(true); - this._th.start(); + Thread _th = new Thread(this); + _th.setName("EventQueue: " + name);//$NON-NLS-1$ + _th.setDaemon(true); + _th.start(); } /** @@ -68,8 +61,7 @@ public CoherentManagerEventQueue(String name, ManagerConnection connection) * subsequently passed on to the original listener. */ @Override - public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event) - { + public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event) { // logger.error(event); boolean wanted = false; @@ -78,107 +70,85 @@ public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent eve * processing overhead of these events. */ // Only enqueue the events that are of interest to one of our listeners. - synchronized (this.globalEvents) - { - Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event); - if (this.globalEvents.contains(shadowEvent)) - { + try (LockCloser closer = this.globalEvents.withLock()) { + Class shadowEvent = CoherentEventFactory.getShadowEvent(event); + if (this.globalEvents.contains(shadowEvent)) { wanted = true; } } - if (wanted) - { - + if (wanted) { // We don't support all events. this._eventQueue.add(new EventLifeMonitor<>(event)); - final int queueSize = this._eventQueue.size(); - if (this._queueMaxSize < queueSize) - { - this._queueMaxSize = queueSize; - } - this._queueSum += queueSize; - this._queueCount++; - - if (CoherentManagerEventQueue.logger.isDebugEnabled()) - { - if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2)) - { - CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$ - + this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$ - } + if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10 + && suppressQueueSizeErrorUntil < System.currentTimeMillis()) { + suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000; + logger.error("EventQueue more than 90% full"); } + } } @Override - public void run() - { - - 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) - break; - - final ManagerEvent iEvent = CoherentEventFactory.build(elm.getEvent()); - if (iEvent != null) - { - dispatchEvent(iEvent); - elm.assessAge(); + 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); } } - } - 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 - { + class PoisonQueueEvent extends org.asteriskjava.manager.event.ManagerEvent { private static final long serialVersionUID = 1L; - public PoisonQueueEvent() - { + public PoisonQueueEvent() { super("PoisonQueueEvent"); //$NON-NLS-1$ } } - public void stop() - { + public void stop() { this._stop = true; - try - { + try { this._eventQueue.put(new EventLifeMonitor(new PoisonQueueEvent())); - } - catch (InterruptedException e) - { + } catch (InterruptedException e) { logger.error(e, e); } } - // TODO: make this multi threaded - private final ExecutorService executors = Executors.newFixedThreadPool(1); + // + private final ExecutorService executors = Executors.newCachedThreadPool(); /** * Events are sent here from the CoherentManagerEventQueue after being @@ -186,10 +156,8 @@ public void stop() * from a dedicated thread attached to the event queue which it uses for * dispatching events. */ - public void dispatchEvent(final ManagerEvent event) - { - if (logger.isDebugEnabled()) - { + public void dispatchEvent(final ManagerEvent event) { + if (logger.isDebugEnabled()) { logger.debug("dispatch=" + event.toString()); //$NON-NLS-1$ } @@ -197,69 +165,53 @@ public void dispatchEvent(final ManagerEvent event) // iterate over them // The iteration may call some long running processes. final List listenerCopy; - synchronized (this.listeners) - { + try (LockCloser closer = this.listeners.withLock()) { listenerCopy = this.listeners.getCopyAsList(); } - try - { + try { final LogTime totalTime = new LogTime(); CountDownLatch latch = new CountDownLatch(listenerCopy.size()); - for (final FilteredManagerListenerWrapper filter : listenerCopy) - { - if (filter.requiredEvents.contains(event.getClass())) - { + for (final FilteredManagerListenerWrapper filter : listenerCopy) { + if (filter.requiredEvents.contains(event.getClass())) { dispatchEventOnThread(event, filter, latch); - } - else - { + } else { // this listener didn't want the event, so just decrease the // countdown latch.countDown(); } } - latch.await(); + if (!latch.await(2, TimeUnit.SECONDS)) { + logger.error("Timeout waiting for event to be processed " + event); + } - if (totalTime.timeTaken() > 500) - { + 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) - { + } catch (InterruptedException e) { Thread.interrupted(); } } private void dispatchEventOnThread(final ManagerEvent event, final FilteredManagerListenerWrapper filter, - final CountDownLatch latch) - { - Runnable runner = new Runnable() - { + final CountDownLatch latch) { + Runnable runner = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { final LogTime time = new LogTime(); filter._listener.onManagerEvent(event); - if (time.timeTaken() > 500) - { + 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) - { + } catch (Exception e) { logger.error(e, e); - } - finally - { + } finally { latch.countDown(); } } @@ -275,17 +227,14 @@ public void run() * 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) - { - synchronized (this.listeners) - { + public void addListener(final FilteredManagerListener listener) { + try (LockCloser closer = this.listeners.withLock()) { this.listeners.addListener(listener); - synchronized (this.globalEvents) - { - Collection> expandEvents = expandEvents(listener.requiredEvents()); + try (LockCloser closer2 = this.globalEvents.withLock()) { + Collection> expandEvents = expandEvents(listener.requiredEvents()); this.globalEvents.addAll(expandEvents); } } @@ -296,18 +245,15 @@ public void addListener(final FilteredManagerListener 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< ? extends ManagerEvent> event : events) - { + Collection> expandEvents(Collection> events) { + Collection> requiredEvents = new HashSet<>(); + for (Class event : events) { requiredEvents.add(event); - if (event.equals(BridgeEvent.class)) - { + if (event.equals(BridgeEvent.class)) { requiredEvents.add(UnlinkEvent.class); requiredEvents.add(LinkEvent.class); } @@ -316,23 +262,18 @@ public void addListener(final FilteredManagerListener listener) return requiredEvents; } - public void removeListener(final FilteredManagerListener melf) - { - if (melf != null) - { - synchronized (this.listeners) - { + 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. - synchronized (this.globalEvents) - { + try (LockCloser closer2 = this.globalEvents.withLock()) { this.globalEvents.clear(); Iterator itr = this.listeners.iterator(); - while (itr.hasNext()) - { + while (itr.hasNext()) { FilteredManagerListenerWrapper readdContainer = itr.next(); this.globalEvents.addAll(expandEvents(readdContainer._listener.requiredEvents())); } @@ -346,18 +287,14 @@ public void removeListener(final FilteredManagerListener melf) /** * transfers the listeners from one queue to another. - * + * * @param eventQueue */ - public void transferListeners(CoherentManagerEventQueue eventQueue) - { - synchronized (this.listeners) - { - synchronized (eventQueue.listeners) - { + 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()) - { + while (itr.hasNext()) { FilteredManagerListenerWrapper listener = itr.next(); this.addListener(listener._listener); diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/DialLocalToAgiActivity.java b/src/main/java/org/asteriskjava/pbx/internal/core/DialLocalToAgiActivity.java index bec7f02bd..b399d795b 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/DialLocalToAgiActivity.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/DialLocalToAgiActivity.java @@ -1,22 +1,6 @@ package org.asteriskjava.pbx.internal.core; -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; - -import org.asteriskjava.pbx.Activity; -import org.asteriskjava.pbx.ActivityCallback; -import org.asteriskjava.pbx.ActivityStatusEnum; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.agi.ActivityAgi; import org.asteriskjava.pbx.agi.ActivityArrivalListener; import org.asteriskjava.pbx.asterisk.wrap.actions.OriginateAction; @@ -24,8 +8,14 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class DialLocalToAgiActivity implements Runnable, Activity -{ +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; @@ -38,8 +28,7 @@ public class DialLocalToAgiActivity implements Runnable, Activity private Map channelVarsToSet; public DialLocalToAgiActivity(EndPoint from, CallerID fromCallerID, ActivityCallback callback, - Map channelVarsToSet) - { + Map channelVarsToSet) { this.from = from; this.fromCallerID = fromCallerID; this.callback = callback; @@ -51,8 +40,7 @@ public DialLocalToAgiActivity(EndPoint from, CallerID fromCallerID, ActivityCall // Logger logger = LogManager.getLogger(); @Override - public void run() - { + public void run() { logger.debug("*******************************************************************************"); logger.info("*********** begin dial local to AGI ****************"); logger.debug("*********** ****************"); @@ -71,48 +59,35 @@ public void run() Map myVars = new HashMap<>(); - if (channelVarsToSet != null) - { + if (channelVarsToSet != null) { myVars.putAll(channelVarsToSet); } originate.setVariables(myVars); - ActivityArrivalListener listener = new ActivityArrivalListener() - { + ActivityArrivalListener listener = new ActivityArrivalListener() { @Override - public void channelArrived(Channel channel) - { + public void channelArrived(Channel channel) { channels.add(channel); - if (isSuccess()) - { + if (isSuccess()) { latch.countDown(); } } }; - try (AutoCloseable closeable = ActivityAgi.addArrivalListener(originate, listener);) - { + try (AutoCloseable closeable = ActivityAgi.addArrivalListener(originate, listener);) { ManagerResponse response = pbx.sendAction(originate, 5000); - if (response.getResponse().compareToIgnoreCase("Success") != 0) - { + if (response.getResponse().compareToIgnoreCase("Success") != 0) { callback.progress(this, ActivityStatusEnum.FAILURE, ActivityStatusEnum.FAILURE.getDefaultMessage()); - } - else - { - if (latch.await(5, TimeUnit.SECONDS)) - { + } else { + if (latch.await(5, TimeUnit.SECONDS)) { callback.progress(this, ActivityStatusEnum.SUCCESS, ActivityStatusEnum.SUCCESS.getDefaultMessage()); - } - else - { + } else { callback.progress(this, ActivityStatusEnum.FAILURE, ActivityStatusEnum.FAILURE.getDefaultMessage()); } } - } - catch (Exception e) - { + } catch (Exception e) { logger.error(e, e); callback.progress(this, ActivityStatusEnum.FAILURE, ActivityStatusEnum.FAILURE.getDefaultMessage()); @@ -120,19 +95,14 @@ public void channelArrived(Channel channel) } - public void abort(final String reason) - { + public void abort(final String reason) { logger.warn("Aborting originate "); - for (Channel channel : channels) - { + for (Channel channel : channels) { PBX pbx = PBXFactory.getActivePBX(); - try - { + try { pbx.hangup(channel); - } - catch (IllegalArgumentException | IllegalStateException | PBXException e) - { + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { logger.error(e, e); } @@ -142,25 +112,21 @@ public void abort(final String reason) } @Override - public Throwable getLastException() - { + public Throwable getLastException() { return null; } @Override - public boolean isSuccess() - { + public boolean isSuccess() { return channels.size() == 2; } - public Channel getChannel1() - { + public Channel getChannel1() { return channels.get(0); } - public Channel getChannel2() - { + 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 index b8914123d..c8f09dece 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/EndPointImpl.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/EndPointImpl.java @@ -4,8 +4,7 @@ import org.asteriskjava.pbx.TechType; import org.asteriskjava.pbx.Trunk; -public class EndPointImpl implements EndPoint -{ +public class EndPointImpl implements EndPoint { private static final String DELIMITER = "/"; //$NON-NLS-1$ final private TechType _tech; @@ -23,13 +22,11 @@ public class EndPointImpl implements EndPoint * 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) - { + public EndPointImpl(final String fullyQualifiedEndPoint) { + if (fullyQualifiedEndPoint == null) { throw new IllegalArgumentException("The fullyQualifiedEndPoint may not be null"); //$NON-NLS-1$ } @@ -37,12 +34,9 @@ public EndPointImpl(final String fullyQualifiedEndPoint) this._tech = TechType.getTech(cleaned); this._endPointName = cleaned.substring(this._tech.name().length() + 1); - if (this._tech == TechType.DIALPLAN) - { + if (this._tech == TechType.DIALPLAN) { this._fullyQualifiedName = this._endPointName; - } - else - { + } else { this._fullyQualifiedName = this._tech.name() + EndPointImpl.DELIMITER + this._endPointName; } this._empty = false; @@ -51,8 +45,7 @@ public EndPointImpl(final String fullyQualifiedEndPoint) /** * Creates a empty end point. */ - public EndPointImpl() - { + public EndPointImpl() { this._empty = true; this._tech = TechType.UNKNOWN; this._endPointName = ""; @@ -61,7 +54,7 @@ public EndPointImpl() /** * Creates an EndPoint from from a simple endpoint name and a tech. - * + * * @param _tech * @param peerName */ @@ -80,64 +73,50 @@ public EndPointImpl() // this.tech = Tech.valueOf(tech.toUpperCase()); // this.endPointName = cleaned; // } - - public EndPointImpl(final TechType defaultTech, final String endPointName) - { - if (endPointName == null) - { + 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) - { + 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)) - { + if (TechType.hasTech(cleaned)) { this._tech = TechType.getTech(cleaned); this._endPointName = cleaned.substring(this._tech.name().length() + 1); - } - else - { + } else { this._tech = defaultTech; this._endPointName = cleaned; } - if (this._tech == TechType.DIALPLAN) - { + if (this._tech == TechType.DIALPLAN) { this._fullyQualifiedName = this._endPointName; - } - else - { + } else { this._fullyQualifiedName = this._tech.name() + EndPointImpl.DELIMITER + this._endPointName; } this._empty = false; } - public EndPointImpl(TechType defaultTech, Trunk trunk, String endPointName) - { - if (endPointName == null) - { + 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) - { + 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)) - { + if (TechType.hasTech(cleaned)) { throw new IllegalArgumentException("endPointName may not contain a Tech"); } @@ -146,8 +125,7 @@ public EndPointImpl(TechType defaultTech, Trunk trunk, String endPointName) this._endPointName = cleaned; this._trunk = trunk; - if (this._tech == TechType.DIALPLAN || this._tech == TechType.CONSOLE || this._tech == TechType.LOCAL) - { + if (this._tech == TechType.DIALPLAN || this._tech == TechType.CONSOLE || this._tech == TechType.LOCAL) { throw new IllegalArgumentException("defaultTech may not be DIALPLAN, LOCAL or CONSOLE"); } @@ -162,31 +140,26 @@ public EndPointImpl(TechType defaultTech, Trunk trunk, String endPointName) * Returns the fully qualified endPoint. */ @Override - public String getFullyQualifiedName() - { + public String getFullyQualifiedName() { return this._fullyQualifiedName; } - public Trunk getTrunk() - { + public Trunk getTrunk() { return _trunk; } @Override - public boolean isSame(final EndPoint rhs) - { + public boolean isSame(final EndPoint rhs) { return this.compareTo(rhs) == 0; } @Override - public int compareTo(EndPoint rhs) - { + public int compareTo(EndPoint rhs) { return this.getFullyQualifiedName().compareTo(rhs.getFullyQualifiedName()); } @Override - public boolean isLocal() - { + public boolean isLocal() { return this._tech == TechType.LOCAL; } @@ -194,44 +167,38 @@ public boolean isLocal() * For the purposes of asterisk IAX and SIP are both considered SIP. */ @Override - public boolean isSIP() - { + public boolean isSIP() { return this._tech == TechType.SIP || this._tech == TechType.IAX || this._tech == TechType.IAX2; } - public boolean isDAHDI() - { + public boolean isDAHDI() { return this._tech == TechType.DAHDI; } @Override - public String getSimpleName() - { + public String getSimpleName() { return this._endPointName; } @Override - public boolean isUnknown() - { + 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) - { + 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) - { + while (tmp != -1) { localTo = localTo.substring(0, tmp) + localTo.substring(tmp + 1, localTo.length()); tmp = localTo.indexOf(" "); //$NON-NLS-1$ } @@ -239,20 +206,17 @@ private String clean(final String _endPointName) } @Override - public TechType getTech() - { + public TechType getTech() { return this._tech; } @Override - public String toString() - { + public String toString() { return this.getFullyQualifiedName(); } @Override - public String getSIPSimpleName() - { + public String getSIPSimpleName() { String name; if (isSIP()) @@ -262,8 +226,7 @@ public String getSIPSimpleName() return name; } - public boolean isEmpty() - { + 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 index ebf7afbbb..103ca0e61 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListener.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListener.java @@ -1,46 +1,44 @@ package org.asteriskjava.pbx.internal.core; -import java.util.Set; - 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(); +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 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); + /** + * 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(); + /** + * 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 index ae73a9f22..eba0c8178 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListenerWrapper.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/FilteredManagerListenerWrapper.java @@ -1,39 +1,34 @@ package org.asteriskjava.pbx.internal.core; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; - 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; -public class FilteredManagerListenerWrapper -{ +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +public class FilteredManagerListenerWrapper { FilteredManagerListener _listener; - Set> requiredEvents; + Set> requiredEvents; private final static AtomicInteger seed = new AtomicInteger(); Integer equalityBuster = seed.incrementAndGet(); - public FilteredManagerListenerWrapper(FilteredManagerListener listener) - { + public FilteredManagerListenerWrapper(FilteredManagerListener listener) { this._listener = listener; this.requiredEvents = listener.requiredEvents(); - if (requiredEvents.contains(BridgeEvent.class)) - { + 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< ? extends ManagerEvent> event : requiredEvents) - { + for (Class event : requiredEvents) { if (!CoherentEventFactory.mapEvents.values().contains(event) - && !CoherentEventFactory.mapResponses.values().contains(event)) - { + && !CoherentEventFactory.mapResponses.values().contains(event)) { throw new RuntimeException( "The requested event type of " + event + "+isn't known by " + CoherentEventFactory.class); } @@ -41,8 +36,7 @@ public FilteredManagerListenerWrapper(FilteredManagerListener list } @Override - public String toString() - { + 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 index 0bec0d1c0..fb922097f 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/ListenerManager.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/ListenerManager.java @@ -1,26 +1,20 @@ package org.asteriskjava.pbx.internal.core; -import java.util.Comparator; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.TreeSet; - +import org.asteriskjava.lock.Lockable; import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class ListenerManager -{ +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 - { + final class ListenerPriorityComparator implements Comparator { @Override - public int compare(FilteredManagerListenerWrapper lhs, FilteredManagerListenerWrapper rhs) - { + public int compare(FilteredManagerListenerWrapper lhs, FilteredManagerListenerWrapper rhs) { int result = lhs._listener.getPriority().compare(rhs._listener.getPriority()); @@ -31,47 +25,38 @@ public int compare(FilteredManagerListenerWrapper lhs, FilteredManagerListenerWr } } - public void clear() - { + public void clear() { listeners.clear(); } - public int size() - { + public int size() { return listeners.size(); } - public Iterator iterator() - { + public Iterator iterator() { return listeners.iterator(); } - public void addListener(FilteredManagerListener listener) - { + public void addListener(FilteredManagerListener listener) { listeners.add(new FilteredManagerListenerWrapper(listener)); } - List getCopyAsList() - { + List getCopyAsList() { List list = new LinkedList<>(); - for (FilteredManagerListenerWrapper listener : listeners) - { + for (FilteredManagerListenerWrapper listener : listeners) { list.add(listener); } return list; } - boolean removeListener(FilteredManagerListener toRemove) - { + boolean removeListener(FilteredManagerListener toRemove) { boolean removed = false; Iterator itr = listeners.iterator(); - while (itr.hasNext()) - { + while (itr.hasNext()) { FilteredManagerListenerWrapper container = itr.next(); // logger.error("Checking " + container._listener + " " + toRemove); - if (container._listener == toRemove) - { + if (container._listener == toRemove) { logger.debug("Removing listener " + toRemove); itr.remove(); removed = true; diff --git a/src/main/java/org/asteriskjava/pbx/internal/core/LiveChannelManager.java b/src/main/java/org/asteriskjava/pbx/internal/core/LiveChannelManager.java index 85d1fe98f..46a1778bd 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/LiveChannelManager.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/LiveChannelManager.java @@ -1,29 +1,25 @@ package org.asteriskjava.pbx.internal.core; -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; - +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.HangupEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.MasqueradeEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.NewChannelEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.RenameEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.ResponseEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.ResponseEvents; -import org.asteriskjava.pbx.asterisk.wrap.events.StatusEvent; +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 @@ -54,11 +50,10 @@ * 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 implements FilteredManagerListener -{ +public class LiveChannelManager extends Lockable implements FilteredManagerListener { private static final Log logger = LogFactory.getLog(LiveChannelManager.class); /** @@ -66,10 +61,9 @@ public class LiveChannelManager implements FilteredManagerListener * channels and remove them as they hangup. The hash is keyed by the * channel's name. e.g. SIP/100-000000100 */ - private final List _liveChannels = new CopyOnWriteArrayList<>(); + private final LockableList _liveChannels = new LockableList<>(new CopyOnWriteArrayList<>()); - public LiveChannelManager() - { + public LiveChannelManager() { CoherentManagerConnection.getInstance().addListener(this); } @@ -80,36 +74,27 @@ public LiveChannelManager() * AsteriskPBX which isn't finished constructing until after the Constructor * returns. */ - void performPostCreationTasks() - { + void performPostCreationTasks() { StatusAction statusAction = new StatusAction(); - try - { + try { ResponseEvents events = CoherentManagerConnection.sendEventGeneratingAction(statusAction, 1000); - for (ResponseEvent event : events.getEvents()) - { - if (event instanceof StatusEvent) - { + 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) - { + } catch (IllegalArgumentException | IllegalStateException | IOException | TimeoutException e) { logger.error(e, e); } } - public ChannelProxy getChannelByEndPoint(EndPoint endPoint) - { + public ChannelProxy getChannelByEndPoint(EndPoint endPoint) { ChannelProxy connectedChannel = null; - for (final ChannelProxy channel : _liveChannels) - { - if (channel.isConnectedTo(endPoint)) - { + for (final ChannelProxy channel : _liveChannels) { + if (channel.isConnectedTo(endPoint)) { connectedChannel = channel; break; } @@ -118,10 +103,8 @@ public ChannelProxy getChannelByEndPoint(EndPoint endPoint) return connectedChannel; } - public void add(ChannelProxy proxy) - { - synchronized (this._liveChannels) - { + public void add(ChannelProxy proxy) { + try (LockCloser closer = _liveChannels.withLock()) { ChannelProxy index = findProxy(proxy); if (index == null) this._liveChannels.add(proxy); @@ -133,24 +116,19 @@ public void add(ChannelProxy proxy) } - private void dumpProxies(ChannelProxy proxy, String cause) - { - if (logger.isDebugEnabled()) - { + 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) - { + for (ChannelProxy aProxy : _liveChannels) { logger.debug("ChannelProxy: " + aProxy); } } } - public void remove(ChannelProxy proxy) - { + public void remove(ChannelProxy proxy) { ChannelProxy index = findProxy(proxy); - if (index != null) - { + if (index != null) { logger.info("Removing liveChannel " + proxy); this._liveChannels.remove(index); } @@ -158,8 +136,7 @@ public void remove(ChannelProxy proxy) } - public ChannelProxy findChannel(String extendedChannelName, String uniqueID) - { + public ChannelProxy findChannel(String extendedChannelName, String uniqueID) { ChannelProxy proxy = null; logger.debug("Trying to find channel " + extendedChannelName + " " + uniqueID); @@ -171,13 +148,10 @@ public ChannelProxy findChannel(String extendedChannelName, String uniqueID) // Sometimes we can have two channels with the same name but // different - if (localUniqueId.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0) - { + if (localUniqueId.compareTo(ChannelImpl.UNKNOWN_UNIQUE_ID) != 0) { - for (ChannelProxy aChannel : _liveChannels) - { - if (aChannel.sameUniqueID(localUniqueId)) - { + for (ChannelProxy aChannel : _liveChannels) { + if (aChannel.sameUniqueID(localUniqueId)) { proxy = aChannel; break; } @@ -187,24 +161,19 @@ public ChannelProxy findChannel(String extendedChannelName, String uniqueID) // 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 (proxy == null) { + for (ChannelProxy aChannel : _liveChannels) { - if (aChannel.isSame(extendedChannelName, localUniqueId)) - { + if (aChannel.isSame(extendedChannelName, localUniqueId)) { proxy = aChannel; break; } } } - if (proxy == null) - { + if (proxy == null) { logger.debug("Failed to match channel to any of..."); - for (ChannelProxy aChannel : _liveChannels) - { + for (ChannelProxy aChannel : _liveChannels) { logger.debug(aChannel); } @@ -213,12 +182,9 @@ public ChannelProxy findChannel(String extendedChannelName, String uniqueID) return proxy; } - private ChannelProxy findProxy(Channel original) - { - for (ChannelProxy aChannel : _liveChannels) - { - if (aChannel.isSame(original)) - { + private ChannelProxy findProxy(Channel original) { + for (ChannelProxy aChannel : _liveChannels) { + if (aChannel.isSame(original)) { return aChannel; } } @@ -226,9 +192,8 @@ private ChannelProxy findProxy(Channel original) } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(MasqueradeEvent.class); required.add(RenameEvent.class); @@ -241,12 +206,9 @@ private ChannelProxy findProxy(Channel original) return required; } - ChannelProxy findProxyById(String id) - { - for (ChannelProxy aChannel : _liveChannels) - { - if (("" + aChannel.getIdentity()).equals(id)) - { + ChannelProxy findProxyById(String id) { + for (ChannelProxy aChannel : _liveChannels) { + if (("" + aChannel.getIdentity()).equals(id)) { return aChannel; } } @@ -254,19 +216,15 @@ ChannelProxy findProxyById(String id) } @Override - public void onManagerEvent(ManagerEvent event) - { - if (event instanceof MasqueradeEvent) - { + 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) - { + if (originalIndex != null && cloneIndex != null) { ChannelProxy originalProxy = (ChannelProxy) masq.getOriginal(); ChannelProxy cloneProxy = (ChannelProxy) masq.getClone(); - try - { + try { // After the masquerade the two underlying channels will // have been switched // between the two proxies. @@ -294,47 +252,35 @@ public void onManagerEvent(ManagerEvent event) originalProxy.masquerade(cloneProxy); dumpProxies(cloneProxy, "Masquerade"); sanityCheck(); - } - catch (InvalidChannelName e) - { + } catch (InvalidChannelName e) { logger.error(e, e); } - } - else + } else logger.error("Either the clone or original channelProxy was missing during a masquerade: cloneIndex=" + cloneIndex + " originalIndex=" + originalIndex); } - if (event instanceof RenameEvent) - { + if (event instanceof RenameEvent) { RenameEvent rename = (RenameEvent) event; ChannelProxy oldChannel = findProxy(rename.getChannel()); - if (oldChannel != null) - { - try - { + if (oldChannel != null) { + try { oldChannel.rename(rename.getNewName(), rename.getUniqueId()); dumpProxies(oldChannel, "RenameEvent"); sanityCheck(); - } - catch (InvalidChannelName e) - { + } catch (InvalidChannelName e) { logger.error(e, e); } - } - else - { + } else { String message = "Unable to rename channel -> Failed to find channel " + rename.getChannel(); logger.warn(message); dumpProxies(null, message); } - } - else if (event instanceof HangupEvent) - { + } 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 @@ -346,12 +292,10 @@ else if (event instanceof HangupEvent) // Yes I've seen a hangup where the channel was null, who knows // why? - if (hangup.getChannel() != null) - { + if (hangup.getChannel() != null) { ChannelProxy proxy = findProxy(hangup.getChannel()); - if (proxy != null) - { + if (proxy != null) { logger.debug("Removing proxy " + proxy); this._liveChannels.remove(proxy); @@ -360,44 +304,34 @@ else if (event instanceof HangupEvent) dumpProxies(proxy, "HangupEvent"); } - } - else - { + } else { logger.error("Didn't remove hungup channel"); } } } @Override - public String getName() - { + public String getName() { return "LiveChannelManager"; } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.CRITICAL; } - public void sanityCheck() - { + public void sanityCheck() { - if (logger.isDebugEnabled()) - { + if (logger.isDebugEnabled()) { logger.error("Performing Sanity Check"); Set channels = new HashSet<>(); - for (ChannelProxy channel : _liveChannels) - { - if (!channels.add(channel.getChannel().getExtendedChannelName())) - { + 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) - { + for (ChannelProxy channel2 : _liveChannels) { if (channel2.getChannel().getExtendedChannelName() - .equals(channel.getChannel().getExtendedChannelName())) - { + .equals(channel.getChannel().getExtendedChannelName())) { logger.error(channel2); } } @@ -409,8 +343,7 @@ public void sanityCheck() } } - public List getChannelList() - { + 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 index 0718943bf..f06e87020 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/Peer.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/Peer.java @@ -1,7 +1,7 @@ package org.asteriskjava.pbx.internal.core; -import java.util.LinkedList; - +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; @@ -11,16 +11,17 @@ 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 + * + * Peers are created by the PeerMonitor which also sends asterisk events to * the peer. - * + * */ -public class Peer implements CallEndedListener -{ +public class Peer implements CallEndedListener { private static final Log logger = LogFactory.getLog(Peer.class); private final EndPoint peerEndPoint; @@ -30,38 +31,31 @@ public class Peer implements CallEndedListener * 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 LinkedList callList = new LinkedList<>(); + private final LockableList callList = new LockableList<>(new LinkedList<>()); private PeerState _state = PeerState.NOTSET; private boolean dnd = false; - public Peer(final EndPoint endPoint) - { + public Peer(final EndPoint endPoint) { this.peerEndPoint = endPoint; } - public boolean isSame(final Peer rhs) - { + public boolean isSame(final Peer rhs) { return this.peerEndPoint.isSame(rhs.getEndPoint()); } - private CallTracker registerChannel(final Channel newChannel) - { + private CallTracker registerChannel(final Channel newChannel) { CallTracker associatedCall = null; boolean found = false; - synchronized (this.callList) - { - for (final CallTracker call : this.callList) - { - if (call.findChannel(newChannel) != -1) - { + 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 (!found) { if (logger.isDebugEnabled()) logger.debug("Peer adding Call: " + this.toString() + " " + newChannel.getExtendedChannelName()); //$NON-NLS-1$ //$NON-NLS-2$ associatedCall = createCallTracker(newChannel); @@ -71,26 +65,23 @@ private CallTracker registerChannel(final Channel newChannel) return associatedCall; } - private CallTracker createCallTracker(final Channel newChannel) - { + private CallTracker createCallTracker(final Channel newChannel) { CallTracker newCall; - synchronized (this.callList) - { + try (LockCloser closer = this.callList.withLock()) { newCall = new CallTracker(this, newChannel); this.callList.add(newCall); } return newCall; } - public boolean getDND() - { + public boolean getDND() { return this.dnd; } // public String getFullChannelName() // { // String channelName = null; - // synchronized (this.callList) + // try (LockCloser closer = Locker2.lock(this.callList) // { // if (this.callList.size() > 0) // { @@ -101,19 +92,17 @@ public boolean getDND() // return channelName; // } - public PeerState getState() - { + 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) - { + private boolean isConnectedToSelf(final Channel channel) { return this.getEndPoint().isSame(channel.getEndPoint()); } @@ -122,25 +111,21 @@ private boolean isConnectedToSelf(final Channel channel) * 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())) - { + 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) - { + if (original != null && clone != null) { clone.mergeCalls(original); clone.setState(b.getCloneState()); this.evaluateState(); - } - else + } 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$ } @@ -149,71 +134,57 @@ public void handleEvent(final MasqueradeEvent b) /** * 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) - { + 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())) - { + if ((b.getChannel() == null) || (b.getChannel().isConsole())) { return; } - if (this.isConnectedToSelf(b.getChannel())) - { + if (this.isConnectedToSelf(b.getChannel())) { CallTracker call = this.registerChannel(b.getChannel()); - if (call != null) - { + if (call != null) { call.setState(b.getChannelState()); this.evaluateState(); } } } - public void handleEvent(final NewStateEvent b) - { - if (this.isConnectedToSelf(b.getChannel())) - { + public void handleEvent(final NewStateEvent b) { + if (this.isConnectedToSelf(b.getChannel())) { CallTracker call = this.registerChannel(b.getChannel()); - if (call != null) - { + if (call != null) { call.setState(b.getChannelState()); this.evaluateState(); } } } - public void handleEvent(final StatusEvent b) - { + public void handleEvent(final StatusEvent b) { final Channel channel = b.getChannel(); - if (this.isConnectedToSelf(channel)) - { + if (this.isConnectedToSelf(channel)) { ((ChannelProxy) channel).getRealChannel().markChannel(); CallTracker call = findCall(channel); - if (call != null) - { + if (call != null) { call.setState(b.getState()); this.evaluateState(); } } } - private CallTracker findCall(Channel channel) - { + private CallTracker findCall(Channel channel) { CallTracker result = null; - synchronized (this.callList) - { - for (CallTracker call : this.callList) - { - if (call.findChannel(channel) != -1) - { + try (LockCloser closer = this.callList.withLock()) { + for (CallTracker call : this.callList) { + if (call.findChannel(channel) != -1) { result = call; break; } @@ -223,30 +194,23 @@ private CallTracker findCall(Channel channel) return result; } - public void setDND(final boolean on) - { + public void setDND(final boolean on) { this.dnd = on; } - public void startSweep() - { + public void startSweep() { Peer.logger.debug("Starting sweep for " + this.peerEndPoint.getFullyQualifiedName());//$NON-NLS-1$ - synchronized (this.callList) - { - for (final CallTracker call : this.callList) - { + try (LockCloser closer = this.callList.withLock()) { + for (final CallTracker call : this.callList) { call.startSweep(); } } } - public void endSweep() - { + public void endSweep() { Peer.logger.debug("Ending sweep for " + this.peerEndPoint.getFullyQualifiedName());//$NON-NLS-1$ - synchronized (this.callList) - { - for (final CallTracker call : this.callList) - { + try (LockCloser closer = this.callList.withLock()) { + for (final CallTracker call : this.callList) { call.endSweep(); } } @@ -257,14 +221,11 @@ public void endSweep() * Called each time the state of a call changes to determine the Peers * overall state. */ - private void evaluateState() - { - synchronized (this.callList) - { + 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) - { + for (CallTracker call : this.callList) { if (call.getState().getPriority() > newState.getPriority()) newState = call.getState(); } @@ -273,39 +234,30 @@ private void evaluateState() } } - public EndPoint getEndPoint() - { + public EndPoint getEndPoint() { return this.peerEndPoint; } @Override - public String toString() - { + public String toString() { return this.getEndPoint().toString(); } - private void dumpCallList() - { - if (logger.isDebugEnabled()) - { + private void dumpCallList() { + if (logger.isDebugEnabled()) { Peer.logger.debug("Peer: dump CallList:" + this); //$NON-NLS-1$ - for (final CallTracker call : this.callList) - { + for (final CallTracker call : this.callList) { call.dumpChannelList(); } } } @Override - public void callEnded(CallTracker call) - { + public void callEnded(CallTracker call) { boolean found = false; - synchronized (this.callList) - { - for (final CallTracker aCall : this.callList) - { - if (call == aCall) - { + 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$ @@ -315,8 +267,7 @@ public void callEnded(CallTracker call) break; } } - if (!found) - { + 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 index 387b1b3ee..05d9c1a25 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/PeerMonitor.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/PeerMonitor.java @@ -1,40 +1,28 @@ package org.asteriskjava.pbx.internal.core; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.NewExtensionListener; -import org.asteriskjava.pbx.PBXFactory; +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.DndStateEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; -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.PeerEntryEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.PeerStatusEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.PeerlistCompleteEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.StatusCompleteEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.StatusEvent; +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 -{ +public class PeerMonitor extends EventListenerBaseClass implements Runnable { private static final Log logger = LogFactory.getLog(PeerMonitor.class); - LinkedList peerList = new LinkedList<>(); + LockableList peerList = new LockableList<>(new LinkedList<>()); boolean initSip = false; @@ -46,51 +34,38 @@ public class PeerMonitor extends EventListenerBaseClass implements Runnable /** * needs to notify PhoneBookDisplayController.getInstance().addExtensions(); - * + * * @param _listener */ - public synchronized static void init(final NewExtensionListener _listener) - { + public synchronized static void init(final NewExtensionListener _listener) { PeerMonitor.listener = _listener; - if (PeerMonitor.self == null) - { + if (PeerMonitor.self == null) { PeerMonitor.self = new PeerMonitor(); - } - else if (_listener != null) - { + } 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) - { + 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() - { + private PeerMonitor() { super("PeerMonitor", PBXFactory.getActivePBX()); //$NON-NLS-1$ - this.peerList = new LinkedList<>(); + this.peerList = new LockableList<>(new LinkedList<>()); this.startListener(); this.addSipsToMonitor(); - try - { - if (PeerMonitor.listener != null) - { + try { + if (PeerMonitor.listener != null) { PeerMonitor.listener.newExtension(); - } - else - { + } else { logger.warn("Peer monitor listener is null"); } - } - catch (final Exception e) - { + } catch (final Exception e) { PeerMonitor.logger.error(e, e); } @@ -101,8 +76,7 @@ private PeerMonitor() } - public void addSipsToMonitor() - { + public void addSipsToMonitor() { /* * request asterisk to send a list of sip peers. The monitor will * dynamically add the peers to its list @@ -111,70 +85,62 @@ public void addSipsToMonitor() final StatusAction sa = new StatusAction(); final SipPeersAction t = new SipPeersAction(); - try - { + try { AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); pbx.sendAction(t, 5000); pbx.sendAction(sa, 5000); - } - catch (final Exception e) - { + } catch (final Exception e) { PeerMonitor.logger.error(e, e); } } - synchronized public Peer registerPeer(final Channel newChannel) - { + public Peer registerPeer(final Channel newChannel) { final Peer peer = this.registerPeer(newChannel.getEndPoint()); return peer; } - synchronized public Peer registerPeer(final EndPoint endPoint) - { - if (endPoint.isLocal()) - { + public Peer registerPeer(final EndPoint endPoint) { + if (endPoint.isLocal()) { return null; } - Peer peer = this.findPeer(endPoint); - if (peer == null) - { - peer = new Peer(endPoint); - this.peerList.add(peer); + try (LockCloser closer = peerList.withLock()) { + Peer peer = this.findPeer(endPoint); + if (peer == null) { + peer = new Peer(endPoint); + this.peerList.add(peer); + } + return peer; } - return peer; } - synchronized public Peer findPeer(final EndPoint peerEndPoint) - { + public Peer findPeer(final EndPoint peerEndPoint) { Peer found = null; - for (final Peer peer : this.peerList) - { - if (peer.getEndPoint().isSame(peerEndPoint)) - { - found = peer; - break; + try (LockCloser closer = peerList.withLock()) { + for (final Peer peer : this.peerList) { + if (peer.getEndPoint().isSame(peerEndPoint)) { + found = peer; + break; + } } } return found; } - @SuppressWarnings("unchecked") - public Iterator getIterator() - { - final List clone = (LinkedList) this.peerList.clone(); - final List tmpList = clone; - return tmpList.iterator(); + 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<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(NewChannelEvent.class); required.add(PeerStatusEvent.class); @@ -189,95 +155,76 @@ public Iterator getIterator() } @Override - synchronized public void onManagerEvent(final ManagerEvent event) - { + 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) - { + if (event instanceof PeerStatusEvent) { this.handleEvent((PeerStatusEvent) event); - } - else if (event instanceof PeerlistCompleteEvent) - { + } else if (event instanceof PeerlistCompleteEvent) { this.handleEvent((PeerlistCompleteEvent) event); - } - else if (event instanceof PeerEntryEvent) - { + } else if (event instanceof PeerEntryEvent) { this.handleEvent((PeerEntryEvent) event); - } - else if (event instanceof NewChannelEvent) - { + } else if (event instanceof NewChannelEvent) { this.handleEvent((NewChannelEvent) event); - } - else if (event instanceof MasqueradeEvent) - { + } else if (event instanceof MasqueradeEvent) { this.handleEvent((MasqueradeEvent) event); - } - else if (event instanceof StatusEvent) - { + } else if (event instanceof StatusEvent) { this.handleEvent((StatusEvent) event); - } - else if (event instanceof StatusCompleteEvent) - { + } else if (event instanceof StatusCompleteEvent) { this.handleEvent((StatusCompleteEvent) event); - } - else if (event instanceof NewStateEvent) - { + } else if (event instanceof NewStateEvent) { this.handleEvent((NewStateEvent) event); } } - private void handleEvent(NewStateEvent event) - { - for (Peer peer : this.peerList) - { - peer.handleEvent(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) - { - 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) - { - 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) - { - 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) - { + private void handleEvent(final PeerEntryEvent event) { final EndPoint endPoint = event.getPeer(); this.registerPeer(endPoint); } - private void handleEvent(final PeerlistCompleteEvent b) - { + private void handleEvent(final PeerlistCompleteEvent b) { this.initSip = true; } /** * @param event */ - private void handleEvent(final PeerStatusEvent event) - { + private void handleEvent(final PeerStatusEvent event) { this.registerPeer(event.getPeer()); } @@ -285,26 +232,23 @@ private void handleEvent(final PeerStatusEvent event) * 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 synchronized void handleEvent(final StatusCompleteEvent event) - { - - for (final Peer peer : this.peerList) - { - peer.endSweep(); + 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() - { + boolean isInitialized() { return this.initSip; } - public void stop() - { + public void stop() { this.close(); } @@ -319,17 +263,12 @@ public void stop() * missed the hangup event. */ @Override - public void run() - { - while (true) - { - try - { + public void run() { + while (true) { + try { Thread.sleep(120000); PeerMonitor.getInstance().startSweep(); - } - catch (final InterruptedException e) - { + } catch (final InterruptedException e) { PeerMonitor.logger.error(e, e); } @@ -345,15 +284,12 @@ public void run() * the end of the process any channels which haven't been marked are then * discarded. */ - public void startSweep() - { + public void startSweep() { PeerMonitor.logger.debug("Starting channel mark and sweep"); //$NON-NLS-1$ // Mark every channel as 'clearing' - synchronized (PeerMonitor.class) - { - for (final Peer peer : this.peerList) - { + try (LockCloser closer = peerList.withLock()) { + for (final Peer peer : this.peerList) { peer.startSweep(); } } @@ -362,21 +298,17 @@ public void startSweep() * Request Asterisk to send us a status update for every channel. */ final StatusAction sa = new StatusAction(); - try - { + try { AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); pbx.sendAction(sa, 5000); - } - catch (final Exception e) - { + } catch (final Exception e) { PeerMonitor.logger.error(e, e); } } @Override - public ListenerPriority getPriority() - { + 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 index 06a3ab2e9..b7405a0df 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/core/PeerState.java +++ b/src/main/java/org/asteriskjava/pbx/internal/core/PeerState.java @@ -4,8 +4,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public enum PeerState -{ +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$ @@ -40,15 +39,12 @@ public enum PeerState */ private int _priority; - public static PeerState valueByName(final String value) - { + public static PeerState valueByName(final String value) { PeerState status = NOTSET; - for (PeerState aState : PeerState.values()) - { + for (PeerState aState : PeerState.values()) { - if (aState.getAsteriskStateName().compareToIgnoreCase(value) == 0) - { + if (aState.getAsteriskStateName().compareToIgnoreCase(value) == 0) { status = aState; break; } @@ -56,20 +52,16 @@ public static PeerState valueByName(final String value) return status; } - private String getAsteriskStateName() - { + private String getAsteriskStateName() { return this._asteriskStateName; } - public static PeerState valueByChannelState(final ChannelState state) - { + public static PeerState valueByChannelState(final ChannelState state) { PeerState status = NOTSET; - for (PeerState aState : PeerState.values()) - { + for (PeerState aState : PeerState.values()) { - if (aState.getAsteriskStateName().compareToIgnoreCase(state.name()) == 0) - { + if (aState.getAsteriskStateName().compareToIgnoreCase(state.name()) == 0) { status = aState; break; } @@ -80,32 +72,27 @@ public static PeerState valueByChannelState(final ChannelState state) return status; } - PeerState(int priority, final String asteriskStateName, final String label, boolean visible) - { + 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() - { + public String getLabel() { return this.label; } @Override - public String toString() - { + public String toString() { return this.label; } - public boolean isVisible() - { + public boolean isVisible() { return this._visible; } - public int getPriority() - { + 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 index 1d7e5ba5f..b2d62d59c 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/eventQueue/EventLifeMonitor.java +++ b/src/main/java/org/asteriskjava/pbx/internal/eventQueue/EventLifeMonitor.java @@ -4,8 +4,7 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class EventLifeMonitor -{ +public class EventLifeMonitor { private static final Log logger = LogFactory.getLog(EventLifeMonitor.class); /* @@ -17,23 +16,19 @@ public class EventLifeMonitor private final LogTime age; - public EventLifeMonitor(final T event) - { + public EventLifeMonitor(final T event) { this.theEvent = event; this.age = new LogTime(); } - public void assessAge() - { - if (this.age.timeTaken() > 2000) - { + public void assessAge() { + if (this.age.timeTaken() > 2000) { EventLifeMonitor.logger.warn("event age : " + this.age.timeTaken()); //$NON-NLS-1$ } } - public T getEvent() - { + 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 index a8c47406e..80435bccd 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Connector.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Connector.java @@ -1,10 +1,5 @@ package org.asteriskjava.pbx.internal.managerAPI; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; - import org.asteriskjava.manager.AuthenticationFailedException; import org.asteriskjava.manager.ManagerConnection; import org.asteriskjava.manager.ManagerConnectionFactory; @@ -13,18 +8,22 @@ 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 -{ +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 @@ -33,8 +32,7 @@ public class Connector * @throws IllegalStateException */ public ManagerConnection connect(final AsteriskSettings asteriskSettings) - throws IOException, AuthenticationFailedException, TimeoutException, IllegalStateException - { + throws IOException, AuthenticationFailedException, TimeoutException, IllegalStateException { checkIfAsteriskRunning(asteriskSettings); this.makeConnection(asteriskSettings); return this.managerConnection; @@ -48,15 +46,13 @@ public ManagerConnection connect(final AsteriskSettings asteriskSettings) * 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()) - { + private void checkIfAsteriskRunning(AsteriskSettings asteriskSettings) throws UnknownHostException, IOException { + try (Socket socket = new Socket()) { socket.setSoTimeout(2000); InetSocketAddress asteriskHost = new InetSocketAddress(asteriskSettings.getAsteriskIP(), @@ -75,17 +71,13 @@ private void checkIfAsteriskRunning(AsteriskSettings asteriskSettings) throws Un * @throws IllegalStateException */ private void makeConnection(final AsteriskSettings asteriskSettings) - throws IOException, AuthenticationFailedException, TimeoutException, IllegalStateException - { + throws IOException, AuthenticationFailedException, TimeoutException, IllegalStateException { ManagerConnectionFactory factory = null; - if (asteriskSettings.getManagerPortNo() == -1) - { + if (asteriskSettings.getManagerPortNo() == -1) { Connector.logger.debug("Using default port 5038."); //$NON-NLS-1$ factory = new ManagerConnectionFactory(asteriskSettings.getAsteriskIP(), asteriskSettings.getManagerUsername(), asteriskSettings.getManagerPassword()); - } - else - { + } else { factory = new ManagerConnectionFactory(asteriskSettings.getAsteriskIP(), asteriskSettings.getManagerPortNo(), asteriskSettings.getManagerUsername(), asteriskSettings.getManagerPassword()); diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Dial.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Dial.java index d4d4c1e84..bf0f98162 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Dial.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/Dial.java @@ -1,38 +1,25 @@ package org.asteriskjava.pbx.internal.managerAPI; -import java.util.HashSet; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.NewChannelListener; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +import org.asteriskjava.pbx.*; import org.asteriskjava.pbx.agi.AgiChannelActivityDial; -import org.asteriskjava.pbx.asterisk.wrap.events.BridgeEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.HangupEvent; -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.asterisk.wrap.events.*; import org.asteriskjava.pbx.internal.core.AsteriskPBX; import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class Dial extends EventListenerBaseClass -{ +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) - { + public Dial(final String descriptiveName) { super(descriptiveName, PBXFactory.getActivePBX()); } @@ -41,26 +28,24 @@ public Dial(final String descriptiveName) * 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 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. + * @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 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)) - { + try (final OriginateToExtension originate = new OriginateToExtension(listener)) { this.startListener(); @@ -71,26 +56,18 @@ public OriginateResult[] dial(final NewChannelListener listener, final EndPoint ((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)) - { + 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 - { + } else { // call never reached agi System.out.println("Call never reached agi"); } - } - else - { + } else { // The call is now up, so connect it to // the @@ -100,28 +77,25 @@ public OriginateResult[] dial(final NewChannelListener listener, final EndPoint trcResult.getChannel().setCurrentActivityAction( new AgiChannelActivityDial(targetEndPoint.getFullyQualifiedName(), dialOptions)); - this._latch.await(30, TimeUnit.SECONDS); + if (!this._latch.await(30, TimeUnit.SECONDS)) { + logger.warn("Timeout waiting for channel. " + trcResult.getChannel()); + } } - } - catch (final InterruptedException e) - { + } catch (final InterruptedException e) { // noop } } return this.result; - } - finally - { + } finally { this.close(); } } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(BridgeEvent.class); // bridge event is a subclass of linkevent, so we need link & unlink in @@ -134,15 +108,12 @@ public OriginateResult[] dial(final NewChannelListener listener, final EndPoint } @Override - public void onManagerEvent(final ManagerEvent event) - { - if (event instanceof BridgeEvent) - { + 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())) - { + && 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(); @@ -150,22 +121,17 @@ public void onManagerEvent(final ManagerEvent event) this.result[1].setChannelData(link.getChannel2()); this._latch.countDown(); } - } - else if (event instanceof HangupEvent) - { + } else if (event instanceof HangupEvent) { final HangupEvent hangup = (HangupEvent) event; final Channel hangupChannel = hangup.getChannel(); - if (Dial.logger.isDebugEnabled()) - { + 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) - { + if ((this.result[0] != null) && this.result[0].isSuccess() && hangupChannel.isSame(this.result[0].getChannel())) { + if (this._latch != null) { this._latch.countDown(); } } @@ -173,8 +139,7 @@ else if (event instanceof HangupEvent) } @Override - public ListenerPriority getPriority() - { + 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 index ce437a63c..51bf9a03e 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/DialToAgi.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/DialToAgi.java @@ -1,26 +1,17 @@ package org.asteriskjava.pbx.internal.managerAPI; -import java.util.HashSet; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.asteriskjava.pbx.AgiChannelActivityAction; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.NewChannelListener; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +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; -public class DialToAgi extends EventListenerBaseClass -{ +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]; @@ -29,8 +20,7 @@ public class DialToAgi extends EventListenerBaseClass private OriginateToExtension originator; - public DialToAgi(final String descriptiveName) - { + public DialToAgi(final String descriptiveName) { super(descriptiveName, PBXFactory.getActivePBX()); } @@ -39,26 +29,24 @@ public DialToAgi(final String descriptiveName) * 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 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. + * @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 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)) - { + try (final OriginateToExtension originate = new OriginateToExtension(listener)) { this.startListener(); originator = originate; @@ -69,78 +57,64 @@ public OriginateResult[] dial(final NewChannelListener listener, final EndPoint ((AsteriskPBX) pbx).getManagementContext(), callerID, timeout, hideCallerId, channelVarsToSet); this.result[0] = trcResult; - if (trcResult.isSuccess()) - { - if (trcResult.getChannel() != null) - { + if (trcResult.isSuccess()) { + if (trcResult.getChannel() != null) { trcResult.getChannel().setCurrentActivityAction(action); - if (trcResult.getChannel().waitForChannelToReachAgi(30, TimeUnit.SECONDS)) - { + if (trcResult.getChannel().waitForChannelToReachAgi(30, TimeUnit.SECONDS)) { logger.info("Call reached AGI"); - } - else - { + } else { logger.error("Call never reached agi"); } - } - else - { + } else { logger.error("Call never reached agi"); } - } - else - { + } else { logger.warn("Originate failed: " + trcResult.getAbortReason()); } logger.info("Hangup status is " + hangupDetected); return this.result; - } - finally - { + } finally { this.close(); } } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(HangupEvent.class); return required; } @Override - public void onManagerEvent(final ManagerEvent event) - { - if (event instanceof HangupEvent) - { + public void onManagerEvent(final ManagerEvent event) { + if (event instanceof HangupEvent) { final HangupEvent hangup = (HangupEvent) event; final Channel hangupChannel = hangup.getChannel(); - if (DialToAgi.logger.isDebugEnabled()) - { + 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())) - { + if ((this.result[0] != null) && this.result[0].isSuccess() && hangupChannel.isSame(this.result[0].getChannel())) { hangupDetected = true; } } } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.NORMAL; } - public void abort() - { - originator.abort("user abort"); + 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 index d294e9cf7..2e2e0e8e4 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/EventListenerBaseClass.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/EventListenerBaseClass.java @@ -1,5 +1,6 @@ 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; @@ -9,21 +10,18 @@ * This is the basic abstract event listener class. It implements a thread * and queue. */ -public abstract class EventListenerBaseClass implements FilteredManagerListener, AutoCloseable -{ +public abstract class EventListenerBaseClass extends Lockable implements FilteredManagerListener, AutoCloseable { private final String name; private final PBX pbx; - protected EventListenerBaseClass(final String descriptiveName, PBX iPBX) - { + protected EventListenerBaseClass(final String descriptiveName, PBX iPBX) { this.name = descriptiveName; this.pbx = iPBX; } @Override - public String getName() - { + public String getName() { return this.name; } @@ -33,8 +31,7 @@ public String getName() * the pbx at that point event though it is initialised. */ - public void startListener() - { + public void startListener() { ((AsteriskPBX) pbx).addListener(this); } @@ -43,8 +40,7 @@ public void startListener() * Stops the listener. */ @Override - public void close() - { + public void close() { ((AsteriskPBX) pbx).removeListener(this); } @@ -53,35 +49,29 @@ public void close() * 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 - { + public class AutoClose implements java.lang.AutoCloseable { EventListenerBaseClass listener; - public AutoClose(final EventListenerBaseClass listener) - { + public AutoClose(final EventListenerBaseClass listener) { this(listener, true); } - public AutoClose(final EventListenerBaseClass listener, final boolean sendEvents) - { - if (listener == null) - { + 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) - { + if (sendEvents) { listener.startListener(); } } @Override - public void close() - { + 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 index 1483da224..5a29a3a36 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/HoldAtAgi.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/HoldAtAgi.java @@ -3,67 +3,56 @@ import org.asteriskjava.pbx.EndPoint; import org.asteriskjava.pbx.TechType; -public class HoldAtAgi implements EndPoint -{ +public class HoldAtAgi implements EndPoint { @Override - public int compareTo(EndPoint arg0) - { + public int compareTo(EndPoint arg0) { // TODO Auto-generated method stub return 0; } @Override - public boolean isSame(EndPoint rhs) - { + public boolean isSame(EndPoint rhs) { return rhs instanceof HoldAtAgi; } @Override - public boolean isLocal() - { + public boolean isLocal() { return false; } @Override - public boolean isSIP() - { - return false; + public boolean isSIP() { + return false; } @Override - public String getFullyQualifiedName() - { + public String getFullyQualifiedName() { return ""; } @Override - public String getSimpleName() - { + public String getSimpleName() { return ""; } @Override - public String getSIPSimpleName() - { + public String getSIPSimpleName() { return ""; } @Override - public boolean isUnknown() - { + public boolean isUnknown() { return false; } @Override - public TechType getTech() - { + public TechType getTech() { return null; } @Override - public boolean isEmpty() - { + 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 index 278fee9ca..af751a4fd 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/MonitorCall.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/MonitorCall.java @@ -1,7 +1,5 @@ package org.asteriskjava.pbx.internal.managerAPI; -import java.util.concurrent.atomic.AtomicLong; - import org.asteriskjava.pbx.Call; import org.asteriskjava.pbx.PBXFactory; import org.asteriskjava.pbx.asterisk.wrap.actions.MonitorAction; @@ -9,20 +7,19 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class MonitorCall -{ +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) - { + public MonitorCall(final Call call) { super(); - try - { + try { this.setFile(); final MonitorAction monitorAction = new MonitorAction(call.getRemoteParty(), this.file, "gsm", true); @@ -30,20 +27,16 @@ public MonitorCall(final Call call) pbx.sendAction(monitorAction, 1000); - } - catch (final Exception e) - { + } catch (final Exception e) { MonitorCall.logger.error(e, e); } } - public String getFilename() - { + public String getFilename() { return this.file + ".gsm"; } - private void setFile() - { + private void setFile() { long no = System.currentTimeMillis(); no = no / 1000; final String unq = Long.toHexString(no); diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateBaseClass.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateBaseClass.java index a93d66d0d..0ba6c5eaa 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateBaseClass.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateBaseClass.java @@ -1,37 +1,23 @@ package org.asteriskjava.pbx.internal.managerAPI; -import java.util.HashMap; -import java.util.HashSet; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - import org.asteriskjava.live.ManagerCommunicationException; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.NewChannelListener; -import org.asteriskjava.pbx.PBX; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +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.BridgeEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.DialBeginEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.DialEndEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.HangupEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.LinkEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.NewChannelEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.OriginateResponseEvent; -import org.asteriskjava.pbx.asterisk.wrap.events.UnlinkEvent; +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; -public abstract class OriginateBaseClass extends EventListenerBaseClass -{ +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 @@ -77,8 +63,9 @@ public abstract class OriginateBaseClass extends EventListenerBaseClass private String channelId; - protected OriginateBaseClass(final NewChannelListener listener, final Channel monitor, final Channel monitor2) - { + 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; @@ -94,26 +81,24 @@ protected OriginateBaseClass(final NewChannelListener listener, final Channel mo * @param local * @param target * @param myVars - * @param callerId the caller id to set when initiating this call. + * @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.debug("originate called"); + 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) - { + if (this.hungup) { // the monitored channel already hungup so just return false and // shutdown return null; } - OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$ + OriginateBaseClass.logger.info("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$ + " vars " + myVars); ManagerResponse response = null; @@ -127,15 +112,11 @@ OriginateResult originate(final EndPoint local, final EndPoint target, final Has Integer localTimeout = timeout; - if (timeout == null) - { + if (timeout == null) { localTimeout = 30000; - try - { + try { localTimeout = settings.getDialTimeout() * 1000; - } - catch (final Exception e) - { + } catch (final Exception e) { OriginateBaseClass.logger.error("Invalid dial timeout value"); } } @@ -147,13 +128,10 @@ OriginateResult originate(final EndPoint local, final EndPoint target, final Has // a channel as the doco talks about 'dialing the channel'. I suspect // this // may be part of asterisk's sloppy terminology. - if (local.isLocal()) - { + if (local.isLocal()) { originate.setEndPoint(local); originate.setOption("/n"); - } - else - { + } else { originate.setEndPoint(local); } @@ -162,13 +140,10 @@ OriginateResult originate(final EndPoint local, final EndPoint target, final Has originate.setPriority(1); // Set the caller id. - if (hideCallerId) - { + if (hideCallerId) { // hide callerID originate.setCallingPres(32); - } - else - { + } else { originate.setCallerId(callerID); } @@ -176,15 +151,13 @@ OriginateResult originate(final EndPoint local, final EndPoint target, final Has originate.setAsync(true); originate.setTimeout(localTimeout); - try - { + try { // Just add us as an asterisk event listener. this.startListener(); response = pbx.sendAction(originate, localTimeout); - OriginateBaseClass.logger.debug("Originate.sendAction completed"); - if (response.getResponse().compareToIgnoreCase("Success") != 0) - { + 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); @@ -192,66 +165,51 @@ OriginateResult originate(final EndPoint local, final EndPoint target, final Has // wait the set timeout +1 second to allow for // asterisk to start the originate - originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS); - } - catch (final InterruptedException e) - { + 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) - { + } catch (final Exception e) { OriginateBaseClass.logger.error(e, e); - } - finally - { + } finally { this.close(); } - if (this.originateSuccess) - { + if (this.originateSuccess) { this.result.setSuccess(true); this.result.setChannelData(this.newChannel); - OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel); - } - else - { + 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.info("Hanging up"); + if (this.newChannel != null) { + try { + logger.warn("Hanging up"); pbx.hangup(this.newChannel); - } - catch (IllegalArgumentException | IllegalStateException | PBXException e) - { + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { logger.error(e, e); } } } + return this.result; } - void abort(final String reason) - { - OriginateBaseClass.logger.debug("Aborting originate "); + void abort(final String reason) { + OriginateBaseClass.logger.warn("Aborting originate "); this.originateSuccess = false; this.result.setAbortReason(reason); this.hungup = true; - if (this.newChannel != null) - { + if (this.newChannel != null) { OriginateBaseClass.logger.warn("Aborted, Hangup up on the way out"); this.result.setChannelHungup(true); PBX pbx = PBXFactory.getActivePBX(); - try - { + try { pbx.hangup(this.newChannel); - } - catch (IllegalArgumentException | IllegalStateException | PBXException e) - { + } catch (IllegalArgumentException | IllegalStateException | PBXException e) { logger.error(e, e); } @@ -261,9 +219,8 @@ void abort(final String reason) } @Override - public HashSet> requiredEvents() - { - HashSet> required = new HashSet<>(); + public HashSet> requiredEvents() { + HashSet> required = new HashSet<>(); required.add(OriginateResponseEvent.class); required.add(BridgeEvent.class); @@ -285,182 +242,152 @@ void abort(final String reason) * time. */ @Override - synchronized public void onManagerEvent(final ManagerEvent event) - { - - 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.debug("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); + 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(); } - OriginateBaseClass.logger.debug("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.debug("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); + 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(); } - OriginateBaseClass.logger.debug("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.debug("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"); + } + 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"); } } - 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(); + if (event instanceof NewChannelEvent) { + final NewChannelEvent newState = (NewChannelEvent) event; + if (channelId.equalsIgnoreCase(newState.getChannel().getUniqueId())) { + final Channel channel = newState.getChannel(); - OriginateBaseClass.logger.debug("new channel event :" + channel + " context = " + newState.getContext() //$NON-NLS-2$ - + " state =" + newState.getChannelStateDesc() + " state =" + newState.getChannelState()); //$NON-NLS-2$ + OriginateBaseClass.logger.info("new channel event :" + channel + " context = " + newState.getContext() //$NON-NLS-2$ + + " state =" + newState.getChannelStateDesc() + " state =" + newState.getChannelState()); //$NON-NLS-2$ - handleId(channel); + 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())) - { + 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 - .debug("new bridge event :" + channel + " channel1 = " + bridgeEvent.getChannel1() //$NON-NLS-2$ - + " channel2 =" + bridgeEvent.getChannel2()); + OriginateBaseClass.logger + .info("new bridge event :" + channel + " channel1 = " + bridgeEvent.getChannel1() //$NON-NLS-2$ + + " channel2 =" + bridgeEvent.getChannel2()); - handleId(channel); + handleId(channel); + } } - } - } + } - if (event instanceof DialEndEvent) - { - if (channelId.equalsIgnoreCase(((DialEndEvent) event).getDestChannel().getUniqueId())) - { - String forward = ((DialEndEvent) event).getForward(); - if (forward != null && forward.length() > 0) - { - originateLatch.countDown(); + 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) - { + private void handleId(Channel channel) { - if ((this.newChannel == null) && !channel.isLocal()) - { + if ((this.newChannel == null) && !channel.isLocal()) { this.newChannel = channel; this.channelSeen = true; OriginateBaseClass.logger.info("new channel name " + channel); - if (this.listener != null) - { + if (this.listener != null) { /* * Update the phone channel to allow the call to be cancelled * before it's answered. @@ -468,9 +395,8 @@ private void handleId(Channel channel) this.listener.channelUpdate(channel); } - if (this.originateSeen) - { - OriginateBaseClass.logger.debug("notifying success 362"); + 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 index 9b3ef4e81..c2e544357 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateResult.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateResult.java @@ -2,8 +2,7 @@ import org.asteriskjava.pbx.Channel; -public class OriginateResult -{ +public class OriginateResult { private boolean channelHungup = false; @@ -13,50 +12,41 @@ public class OriginateResult private String abortReason; - OriginateResult() - { + OriginateResult() { // not used } - public String getAbortReason() - { + public String getAbortReason() { return this.abortReason; } - void setAbortReason(final String reason) - { + void setAbortReason(final String reason) { this.abortReason = reason; } - public void setChannelData(final Channel channel) - { + public void setChannelData(final Channel channel) { this.newChannel = channel; } - public Channel getChannel() - { + public Channel getChannel() { return this.newChannel; } - public boolean isSuccess() - { + public boolean isSuccess() { return this.success; } - public void setSuccess(boolean success) - { + public void setSuccess(boolean success) { this.success = success; } - public boolean isChannelHungup() - { + public boolean isChannelHungup() { return this.channelHungup; } - public void setChannelHungup(boolean channel1Hungup) - { + 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 index 038276faf..f82cd8841 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateToExtension.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/OriginateToExtension.java @@ -1,32 +1,24 @@ package org.asteriskjava.pbx.internal.managerAPI; +import org.asteriskjava.pbx.*; + import java.util.HashMap; import java.util.Map; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.CallerID; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.ListenerPriority; -import org.asteriskjava.pbx.NewChannelListener; -import org.asteriskjava.pbx.PBXFactory; - -public class OriginateToExtension extends OriginateBaseClass -{ +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) - { + 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) - { + final CallerID callerID, final String context) { /* * A new call is originated on the nominated channel to the specified * extension. @@ -36,8 +28,7 @@ public OriginateResult originate(final EndPoint localHandset, final EndPoint tar final AsteriskSettings profile = PBXFactory.getActiveProfile(); final HashMap myVars = new HashMap<>(1); - if (autoAnswer) - { + if (autoAnswer) { RedirectCall.setAutoAnswer(myVars, profile); } @@ -45,9 +36,8 @@ public OriginateResult originate(final EndPoint localHandset, final EndPoint tar } 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) - { + 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. @@ -57,12 +47,10 @@ public OriginateResult originate(final EndPoint localHandset, final EndPoint tar final AsteriskSettings profile = PBXFactory.getActiveProfile(); final HashMap myVars = new HashMap<>(1); - if (autoAnswer) - { + if (autoAnswer) { RedirectCall.setAutoAnswer(myVars, profile); } - if (channelVarsToSet != null) - { + if (channelVarsToSet != null) { myVars.putAll(channelVarsToSet); } @@ -70,8 +58,7 @@ public OriginateResult originate(final EndPoint localHandset, final EndPoint tar } @Override - public ListenerPriority getPriority() - { + 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 index f10db39c5..522191485 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectCall.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectCall.java @@ -1,43 +1,34 @@ package org.asteriskjava.pbx.internal.managerAPI; -import java.util.HashMap; - -import org.asteriskjava.pbx.AgiChannelActivityAction; -import org.asteriskjava.pbx.AsteriskSettings; -import org.asteriskjava.pbx.Channel; -import org.asteriskjava.pbx.EndPoint; -import org.asteriskjava.pbx.PBXException; -import org.asteriskjava.pbx.PBXFactory; +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; -public class RedirectCall -{ +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) - { + 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 - { + 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) - { + if (autoAnswer) { sipHeader = PBXFactory.getActiveProfile().getAutoAnswer(); } @@ -51,19 +42,16 @@ public boolean redirect(final Channel channel, final EndPoint targetEndPoint, fi return true; } - public boolean redirectToVoicemail(final Channel channel, final EndPoint mailbox) throws PBXException - { + 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 - { + public void redirect(Channel channel, AgiChannelActivityAction channelActivityHold) throws PBXException { final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); - if (!pbx.moveChannelToAgi(channel)) - { + if (!pbx.moveChannelToAgi(channel)) { throw new PBXException("Channel: " + channel + " couldn't be moved to agi"); } if (!pbx.waitForChannelToQuiescent(channel, 3000)) diff --git a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectToMeetMe.java b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectToMeetMe.java index 4a8df6d69..548938ed1 100644 --- a/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectToMeetMe.java +++ b/src/main/java/org/asteriskjava/pbx/internal/managerAPI/RedirectToMeetMe.java @@ -8,18 +8,15 @@ import org.asteriskjava.util.Log; import org.asteriskjava.util.LogFactory; -public class RedirectToMeetMe -{ +public class RedirectToMeetMe { private static final Log logger = LogFactory.getLog(RedirectToMeetMe.class); - public RedirectToMeetMe() - { + public RedirectToMeetMe() { super(); } public boolean redirectToMeetme(final Channel channel, final String room, String bridgeProfile, String userProfile) - throws PBXException - { + throws PBXException { final AsteriskPBX pbx = (AsteriskPBX) PBXFactory.getActivePBX(); /* * this procedure rediects the specified channel to the specified meetme @@ -31,8 +28,7 @@ public boolean redirectToMeetme(final Channel channel, final String room, String RedirectToMeetMe.logger.info("redirect to Meetme channel " + channel + " room " + room); - if (!pbx.moveChannelToAgi(channel)) - { + if (!pbx.moveChannelToAgi(channel)) { throw new PBXException("Channel: " + channel + " couldn't be moved to agi"); } channel.setCurrentActivityAction(new AgiChannelActivityMeetme(room, bridgeProfile, userProfile)); diff --git a/src/main/java/org/asteriskjava/pbx/util/LogTime.java b/src/main/java/org/asteriskjava/pbx/util/LogTime.java index fd2261e4c..2db86c5a1 100644 --- a/src/main/java/org/asteriskjava/pbx/util/LogTime.java +++ b/src/main/java/org/asteriskjava/pbx/util/LogTime.java @@ -7,16 +7,13 @@ /** * @author work shop */ -public class LogTime -{ - public Long dStartTime = System.currentTimeMillis(); - - public long timeTaken() - { - // returns the time taken from construction til now in milliseconds - // Date dStartTime = new Date(); +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/.gitignore b/src/main/java/org/asteriskjava/tools/.gitignore deleted file mode 100644 index 03106de55..000000000 --- a/src/main/java/org/asteriskjava/tools/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/HtmlEventTracer$1.class -/HtmlEventTracer.class diff --git a/src/main/java/org/asteriskjava/tools/HtmlEventTracer.java b/src/main/java/org/asteriskjava/tools/HtmlEventTracer.java index 660ddc3d6..b60b0b0f9 100644 --- a/src/main/java/org/asteriskjava/tools/HtmlEventTracer.java +++ b/src/main/java/org/asteriskjava/tools/HtmlEventTracer.java @@ -1,5 +1,9 @@ package org.asteriskjava.tools; +import org.asteriskjava.live.DefaultAsteriskServer; +import org.asteriskjava.manager.ManagerEventListener; +import org.asteriskjava.manager.event.*; + import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; @@ -13,22 +17,6 @@ import java.util.List; import java.util.Map; -import org.asteriskjava.live.DefaultAsteriskServer; -import org.asteriskjava.manager.ManagerEventListener; -import org.asteriskjava.manager.event.AbstractParkedCallEvent; -import org.asteriskjava.manager.event.AntennaLevelEvent; -import org.asteriskjava.manager.event.BridgeEvent; -import org.asteriskjava.manager.event.DialEvent; -import org.asteriskjava.manager.event.HangupEvent; -import org.asteriskjava.manager.event.HoldEvent; -import org.asteriskjava.manager.event.ManagerEvent; -import org.asteriskjava.manager.event.NewChannelEvent; -import org.asteriskjava.manager.event.NewExtenEvent; -import org.asteriskjava.manager.event.NewStateEvent; -import org.asteriskjava.manager.event.PausedEvent; -import org.asteriskjava.manager.event.RenameEvent; -import org.asteriskjava.manager.event.UnpausedEvent; - /** * A diagnostic tool that creates an HTML file showing the state changing events * received from Asterisk on the Manager API. @@ -46,16 +34,14 @@ * * @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; + private final Map, String> colors; - public HtmlEventTracer() - { + public HtmlEventTracer() { uniqueIds = new ArrayList<>(); events = new ArrayList<>(); colors = new HashMap<>(); @@ -68,20 +54,15 @@ public HtmlEventTracer() colors.put(BridgeEvent.class, "#fff8ae"); // light yellow colors.put(HangupEvent.class, "#ff6c17"); // orange - try - { + try { writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8)); - } - catch (IOException e) - { + } 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); } @@ -96,43 +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(); @@ -152,24 +124,19 @@ public void write() line.append("
    "); line.append(event.getDateReceived()); 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()); } } @@ -178,36 +145,27 @@ public void write() System.err.println("Trace file successfully written to " + filename + "."); } - private String getColor(Class< ? extends ManagerEvent> 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; } 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; } @@ -215,108 +173,74 @@ protected String getProperty(Object obj, String property) return null; } - 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) - { + } else if (event instanceof AntennaLevelEvent) { format = "%s"; properties = new String[]{"signal"}; - } - else if (event instanceof PausedEvent) - { + } else if (event instanceof PausedEvent) { format = "(%s) %s"; properties = new String[]{"header", "extension"}; - } - else if (event instanceof UnpausedEvent) - { + } 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 && properties != 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/.gitignore b/src/main/java/org/asteriskjava/util/.gitignore deleted file mode 100644 index 844729c85..000000000 --- a/src/main/java/org/asteriskjava/util/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -/AstState.class -/AstUtil.class -/Base64.class -/DaemonThreadFactory.class -/DateUtil.class -/Log.class -/LogFactory.class -/MixMonitorDirection.class -/ReflectionUtil.class -/ServerSocketFacade.class -/SocketConnectionFacade.class diff --git a/src/main/java/org/asteriskjava/util/AstState.java b/src/main/java/org/asteriskjava/util/AstState.java index 6cdd3b2e3..afe67770d 100644 --- a/src/main/java/org/asteriskjava/util/AstState.java +++ b/src/main/java/org/asteriskjava/util/AstState.java @@ -11,8 +11,7 @@ * * @since 1.0.0 */ -public class AstState -{ +public class AstState { /* from include/asterisk/channel.h */ /** @@ -67,8 +66,7 @@ public class AstState private static final Map inverseStateMap; - static - { + static { final Map tmpInverseStateMap = new HashMap<>(); tmpInverseStateMap.put("Down", AST_STATE_DOWN); @@ -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 1aa348dc7..98640c110 100644 --- a/src/main/java/org/asteriskjava/util/AstUtil.java +++ b/src/main/java/org/asteriskjava/util/AstUtil.java @@ -12,13 +12,11 @@ * @author srt * @version $Id$ */ -public class AstUtil -{ +public class AstUtil { private static final Set TRUE_LITERALS; private static final Set NULL_LITERALS; - static - { + static { TRUE_LITERALS = new HashSet<>(20); TRUE_LITERALS.add("yes"); TRUE_LITERALS.add("true"); @@ -43,8 +41,7 @@ public class AstUtil NULL_LITERALS.add("(null)"); // appData in ListDialplanEvent } - private AstUtil() - { + private AstUtil() { // hide constructor } @@ -52,7 +49,7 @@ private AstUtil() * Checks if a String represents true or false * according to Asterisk's logic.
    * The original implementation is util.c is as follows:
    - * + * *
          *     int ast_true(const char *s)
          *     {
    @@ -70,7 +67,7 @@ private AstUtil()
          *         return 0;
          *     }
          * 
    - * + * *
    * To support the dnd property of * {@link org.asteriskjava.manager.event.ZapShowChannelsEvent} this method @@ -78,31 +75,27 @@ private AstUtil() * * @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; } - return TRUE_LITERALS.contains(o.toString().toLowerCase(Locale.US)); + return TRUE_LITERALS.contains(o.toString().toLowerCase(Locale.ENGLISH)); } /** * @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 + * {@code false} otherwise */ - public static boolean isEqual(Object a, Object b) - { + public static boolean isEqual(Object a, Object b) { return a == b || a != null && a.equals(b); } @@ -116,16 +109,14 @@ public static boolean isEqual(Object a, Object b) * @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; } @@ -133,29 +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; } number = s.substring(lbPosition + 1, rbPosition).trim(); - if (number.length() == 0) - { + 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; } @@ -171,32 +157,58 @@ public static String[] parseCallerId(String s) * "<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. + * 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 3f053f778..c327d7665 100644 --- a/src/main/java/org/asteriskjava/util/Base64.java +++ b/src/main/java/org/asteriskjava/util/Base64.java @@ -12,14 +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[]). @@ -40,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); + 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]); } @@ -68,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('='); } } @@ -84,11 +87,11 @@ private static String byteArrayToBase64(byte[] a, boolean alternate) { * 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', '+', '/' + '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', '+', '/' }; /** @@ -99,11 +102,11 @@ private static String byteArrayToBase64(byte[] a, boolean alternate) { * 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', '+', '?' + '!', '"', '#', '$', '%', '&', '\'', '(', ')', ',', '-', '.', ':', + ';', '<', '>', '@', '[', ']', '^', '`', '_', '{', '|', '}', '~', + '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', '+', '?' }; /** @@ -111,7 +114,7 @@ private static String byteArrayToBase64(byte[] a, boolean alternate) { * into a byte array. * * @throws IllegalArgumentException if s is not a valid Base64 - * string. + * string. */ public static byte[] base64ToByteArray(String s) { return base64ToByteArray(s, false); @@ -122,35 +125,35 @@ public static byte[] base64ToByteArray(String s) { * into a byte array. * * @throws IllegalArgumentException or ArrayOutOfBoundsException - * if s is not a valid alternate representation - * Base64 string. + * 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(); } return currentDate; @@ -72,46 +67,39 @@ public static Date getDate() /** * 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. + * 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 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. + * zone. * @return the corresponding Java date object or null if it is - * not parsable. + * 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 8084e60c0..dc2992ca7 100644 --- a/src/main/java/org/asteriskjava/util/Log.java +++ b/src/main/java/org/asteriskjava/util/Log.java @@ -21,12 +21,11 @@ *

    * 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); diff --git a/src/main/java/org/asteriskjava/util/LogFactory.java b/src/main/java/org/asteriskjava/util/LogFactory.java index 356b8787e..b8d23004e 100644 --- a/src/main/java/org/asteriskjava/util/LogFactory.java +++ b/src/main/java/org/asteriskjava/util/LogFactory.java @@ -26,25 +26,24 @@ *

    * 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. * * @author srt * @version $Id$ */ -public final class LogFactory -{ +public final class LogFactory { private static Boolean slf4jLoggingAvailable = null; /** @@ -60,13 +59,12 @@ public final class LogFactory private static Boolean javaLoggingAvailable = null; private static ClassLoader classLoader = LogFactory.class.getClassLoader(); - + private LogFactory() { - + } - public static void setClassLoader(ClassLoader classLoader) - { + public static void setClassLoader(ClassLoader classLoader) { LogFactory.classLoader = classLoader; } @@ -76,65 +74,46 @@ public static void setClassLoader(ClassLoader classLoader) * @param clazz the class to create the logger for. * @return the created logger. */ - public synchronized 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); } return new NullLog(); diff --git a/src/main/java/org/asteriskjava/util/MixMonitorDirection.java b/src/main/java/org/asteriskjava/util/MixMonitorDirection.java index 58a520155..93866ea93 100644 --- a/src/main/java/org/asteriskjava/util/MixMonitorDirection.java +++ b/src/main/java/org/asteriskjava/util/MixMonitorDirection.java @@ -3,28 +3,24 @@ /** * 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 -{ +public enum MixMonitorDirection { FROM_CHANNEL("read"), TO_CHANNEL("write"), BOTH("both"); String stateName; - MixMonitorDirection(String name) - { + MixMonitorDirection(String name) { this.stateName = name; } - public String getStateName() - { + public String getStateName() { return stateName; } - public void setStateName(String 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 ca9d4f5f9..86a32e252 100644 --- a/src/main/java/org/asteriskjava/util/ReflectionUtil.java +++ b/src/main/java/org/asteriskjava/util/ReflectionUtil.java @@ -16,6 +16,8 @@ */ package org.asteriskjava.util; +import org.reflections.Reflections; + import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; @@ -26,15 +28,13 @@ import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Set; +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 @@ -44,10 +44,8 @@ * * @author srt */ -public class ReflectionUtil -{ - private ReflectionUtil() - { +public class ReflectionUtil { + private ReflectionUtil() { // hide constructor } @@ -62,33 +60,26 @@ 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) - { + public static Map getGetters(final Class clazz) { final Map accessors = new HashMap<>(); final Method[] methods = clazz.getMethods(); - for (Method method : methods) - { + for (Method method : methods) { String name = null; String methodName = method.getName(); - if (methodName.startsWith("get")) - { + if (methodName.startsWith("get")) { name = methodName.substring(3); - } - else if (methodName.startsWith("is")) - { + } else if (methodName.startsWith("is")) { name = methodName.substring(2); } - if (name == null || name.length() == 0) - { + if (name == null || name.length() == 0) { continue; } // skip methods with != 0 parameters - if (method.getParameterTypes().length != 0) - { + if (method.getParameterTypes().length != 0) { continue; } @@ -98,6 +89,26 @@ else if (methodName.startsWith("is")) return accessors; } + private final static ConcurrentHashMap, Map> setterMap = new ConcurrentHashMap<>(); + + /** + * 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. *

    @@ -109,93 +120,63 @@ else if (methodName.startsWith("is")) * @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) - { + 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') + * 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; - StringBuilder 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 StringBuilder(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(""); } /** @@ -204,19 +185,15 @@ else if (c >= 'a' && c <= 'z') * * @param s fully qualified name of the class to check. * @return true if the class is available, false - * otherwise. + * 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; } } @@ -229,35 +206,23 @@ public static boolean isClassAvailable(String s) * @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 - { - Class< ? > clazz = classLoader.loadClass(s); - Constructor< ? > constructor = clazz.getConstructor(); + 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; } @@ -266,44 +231,24 @@ public static Object newInstance(String s) private static final Log logger = LogFactory.getLog(ReflectionUtil.class); /** - * find and all non abstract classes that implement/extend - * baseClassOrInterface in the package packageName + * Find all non-abstract classes in the given package that + * implement/extend the provided type. * - * @param packageName - * @param baseClassOrInterface - * @return + * @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 */ - @SuppressWarnings("unchecked") - public static Set> loadClasses(String packageName, Class baseClassOrInterface) - { - Set> result = new HashSet<>(); - - try - { - Set classNames = getClassNamesFromPackage(packageName); - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - for (String className : classNames) - { - try - { - Class< ? > clazz = classLoader.loadClass(packageName + "." + className); - if (!Modifier.isAbstract(clazz.getModifiers()) && baseClassOrInterface.isAssignableFrom(clazz)) - { - result.add((Class) clazz); - } - } - catch (Throwable e) - { - logger.error(e, e); - } - - } - logger.info("Loaded " + result.size()); - } - catch (Exception e) - { - logger.error(e, e); - } + 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; } @@ -311,14 +256,13 @@ public static Set> loadClasses(String packageName, Class baseCla /** * 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 - { + private static Set getClassNamesFromPackage(String packageName) throws IOException, URISyntaxException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration packageURLs; Set names = new HashSet(); @@ -326,11 +270,9 @@ private static Set getClassNamesFromPackage(String packageName) throws I packageName = packageName.replace(".", "/"); packageURLs = classLoader.getResources(packageName); - while (packageURLs.hasMoreElements()) - { + while (packageURLs.hasMoreElements()) { URL packageURL = packageURLs.nextElement(); - if (packageURL.getProtocol().equals("jar")) - { + if (packageURL.getProtocol().equals("jar")) { String jarFileName; Enumeration jarEntries; @@ -340,14 +282,11 @@ private static Set getClassNamesFromPackage(String packageName) throws I jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8"); jarFileName = jarFileName.substring(5, jarFileName.indexOf("!")); logger.info(">" + jarFileName); - try (JarFile jf = new JarFile(jarFileName);) - { + try (JarFile jf = new JarFile(jarFileName);) { jarEntries = jf.entries(); - while (jarEntries.hasMoreElements()) - { + while (jarEntries.hasMoreElements()) { entryName = jarEntries.nextElement().getName(); - if (entryName.startsWith(packageName) && entryName.endsWith(".class")) - { + if (entryName.startsWith(packageName) && entryName.endsWith(".class")) { entryName = entryName.substring(packageName.length() + 1, entryName.lastIndexOf('.')); names.add(entryName); } @@ -355,18 +294,14 @@ private static Set getClassNamesFromPackage(String packageName) throws I } // loop through files in classpath - } - else - { + } 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) - { + if (files != null) { + for (File actual : files) { String entryName = actual.getName(); entryName = entryName.substring(0, entryName.lastIndexOf('.')); names.add(entryName); @@ -377,11 +312,9 @@ private static Set getClassNamesFromPackage(String packageName) throws I // clean up Iterator itr = names.iterator(); - while (itr.hasNext()) - { + while (itr.hasNext()) { String name = itr.next(); - if (name.equals("package") || name.endsWith(".") || name.length() == 0) - { + if (name.equals("package") || name.endsWith(".") || name.length() == 0) { itr.remove(); } } diff --git a/src/main/java/org/asteriskjava/util/ServerSocketFacade.java b/src/main/java/org/asteriskjava/util/ServerSocketFacade.java index c0fc5020b..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,7 +38,7 @@ public interface ServerSocketFacade /** * Unbinds and closes the server socket. - * + * * @throws IOException if the server socket cannot be closed. */ void close() throws IOException; @@ -48,7 +47,7 @@ public interface ServerSocketFacade * Connection is dropped if it stales on read longer than the timeout. * * @param socketReadTimeout the read timeout value to be used in - * milliseconds. + * milliseconds. * @see java.net.Socket#setSoTimeout(int) * @since 3.0.0 */ 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/.gitignore b/src/main/java/org/asteriskjava/util/internal/.gitignore deleted file mode 100644 index 7c5754050..000000000 --- a/src/main/java/org/asteriskjava/util/internal/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -/FileTrace.class -/JavaLoggingLog.class -/Log4JLogger.class -/NullLog.class -/ServerSocketFacadeImpl.class -/Slf4JLogger.class -/SocketConnectionFacadeImpl.class -/Trace.class diff --git a/src/main/java/org/asteriskjava/util/internal/FileTrace.java b/src/main/java/org/asteriskjava/util/internal/FileTrace.java index bed1fa36a..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,9 @@ package org.asteriskjava.util.internal; +import org.asteriskjava.util.DateUtil; +import org.asteriskjava.util.Log; +import org.asteriskjava.util.LogFactory; + import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; @@ -11,16 +15,11 @@ import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.Date; - -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; /** * 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"; @@ -34,15 +33,13 @@ public class FileTrace implements Trace private boolean exceptionLogged = false; private RandomAccessFile randomAccessFile; - public FileTrace(Socket socket) throws IOException - { + 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()); @@ -59,8 +56,7 @@ private String getHeader(Socket socket) 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); @@ -68,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("_"); @@ -85,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(" "); @@ -139,36 +121,28 @@ 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 - { + public void close() { + try { randomAccessFile.close(); - } - catch (IOException e) - { + } 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 61b1f3448..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. *

    * 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,104 +39,77 @@ 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() - { + private StackTraceElement getInvokerSTE() { StackTraceElement[] stack = (new Throwable()).getStackTrace(); - if (stack.length > 2) - { + if (stack.length > 2) { return stack[2]; } @@ -145,22 +117,17 @@ private StackTraceElement getInvokerSTE() } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return log.isLoggable(Level.FINE); } @Override - public void debug(Object e, Throwable e2) - { + public void debug(Object e, Throwable e2) { StackTraceElement ste = getInvokerSTE(); - if (ste != null) - { + if (ste != null) { log.logp(Level.FINE, ste.getClassName(), ste.getMethodName(), e.toString(), e2); - } - else - { + } 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 index 33a7c03cf..3bd3df9b7 100644 --- a/src/main/java/org/asteriskjava/util/internal/LocationAwareWrapper.java +++ b/src/main/java/org/asteriskjava/util/internal/LocationAwareWrapper.java @@ -4,430 +4,367 @@ import org.slf4j.Marker; import org.slf4j.spi.LocationAwareLogger; -public class LocationAwareWrapper implements Logger -{ +public class LocationAwareWrapper implements Logger { private String FQCN; private LocationAwareLogger logger; - public LocationAwareWrapper(String FQCN, LocationAwareLogger logger) - { + public LocationAwareWrapper(String FQCN, LocationAwareLogger logger) { this.FQCN = FQCN; this.logger = logger; } @Override - public String getName() - { + public String getName() { return logger.getName(); } @Override - public boolean isTraceEnabled() - { + public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override - public void trace(String msg) - { + public void trace(String msg) { logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, null); } @Override - public void trace(String format, Object arg) - { + public void trace(String format, Object arg) { logger.trace(format, arg); } @Override - public void trace(String format, Object arg1, Object arg2) - { + public void trace(String format, Object arg1, Object arg2) { logger.trace(format, arg1, arg2); } @Override - public void trace(String format, Object... arguments) - { + public void trace(String format, Object... arguments) { logger.trace(format, arguments); } @Override - public void trace(String msg, Throwable t) - { + public void trace(String msg, Throwable t) { logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, msg, null, t); } @Override - public boolean isTraceEnabled(Marker marker) - { + public boolean isTraceEnabled(Marker marker) { return logger.isTraceEnabled(marker); } @Override - public void trace(Marker marker, String msg) - { + 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) - { + 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) - { + 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) - { + public void trace(Marker marker, String format, Object... arguments) { logger.trace(marker, format, arguments); } @Override - public void trace(Marker marker, String msg, Throwable t) - { + public void trace(Marker marker, String msg, Throwable t) { logger.log(marker, FQCN, LocationAwareLogger.TRACE_INT, msg, null, t); } @Override - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override - public void debug(String msg) - { + public void debug(String msg) { logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, null); } @Override - public void debug(String format, Object arg) - { + public void debug(String format, Object arg) { logger.debug(format, arg); } @Override - public void debug(String format, Object arg1, Object arg2) - { + public void debug(String format, Object arg1, Object arg2) { logger.debug(format, arg1, arg2); } @Override - public void debug(String format, Object... arguments) - { + public void debug(String format, Object... arguments) { logger.debug(format, arguments); } @Override - public void debug(String msg, Throwable t) - { + public void debug(String msg, Throwable t) { logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, t); } @Override - public boolean isDebugEnabled(Marker marker) - { + public boolean isDebugEnabled(Marker marker) { return logger.isDebugEnabled(marker); } @Override - public void debug(Marker marker, String msg) - { + 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) - { + 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) - { + 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) - { + public void debug(Marker marker, String format, Object... arguments) { logger.debug(marker, format, arguments); } @Override - public void debug(Marker marker, String msg, Throwable t) - { + public void debug(Marker marker, String msg, Throwable t) { logger.log(marker, FQCN, LocationAwareLogger.DEBUG_INT, msg, null, t); } @Override - public boolean isInfoEnabled() - { + public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override - public void info(String msg) - { + public void info(String msg) { logger.log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, null); } @Override - public void info(String format, Object arg) - { + public void info(String format, Object arg) { logger.info(format, arg); } @Override - public void info(String format, Object arg1, Object arg2) - { + public void info(String format, Object arg1, Object arg2) { logger.info(format, arg1, arg2); } @Override - public void info(String format, Object... arguments) - { + public void info(String format, Object... arguments) { logger.info(format, arguments); } @Override - public void info(String msg, Throwable t) - { + public void info(String msg, Throwable t) { logger.log(null, FQCN, LocationAwareLogger.INFO_INT, msg, null, t); } @Override - public boolean isInfoEnabled(Marker marker) - { + public boolean isInfoEnabled(Marker marker) { return logger.isInfoEnabled(marker); } @Override - public void info(Marker marker, String msg) - { + 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) - { + 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) - { + 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) - { + public void info(Marker marker, String format, Object... arguments) { logger.info(marker, format, arguments); } @Override - public void info(Marker marker, String msg, Throwable t) - { + public void info(Marker marker, String msg, Throwable t) { logger.log(marker, FQCN, LocationAwareLogger.INFO_INT, msg, null, t); } @Override - public boolean isWarnEnabled() - { + public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override - public void warn(String msg) - { + public void warn(String msg) { logger.log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, null); } @Override - public void warn(String format, Object arg) - { + public void warn(String format, Object arg) { logger.warn(format, arg); } @Override - public void warn(String format, Object arg1, Object arg2) - { + public void warn(String format, Object arg1, Object arg2) { logger.warn(format, arg1, arg2); } @Override - public void warn(String format, Object... arguments) - { + public void warn(String format, Object... arguments) { logger.warn(format, arguments); } @Override - public void warn(String msg, Throwable t) - { + public void warn(String msg, Throwable t) { logger.log(null, FQCN, LocationAwareLogger.WARN_INT, msg, null, t); } @Override - public boolean isWarnEnabled(Marker marker) - { + public boolean isWarnEnabled(Marker marker) { return logger.isWarnEnabled(marker); } @Override - public void warn(Marker marker, String msg) - { + 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) - { + 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) - { + 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) - { + public void warn(Marker marker, String format, Object... arguments) { logger.warn(marker, format, arguments); } @Override - public void warn(Marker marker, String msg, Throwable t) - { + public void warn(Marker marker, String msg, Throwable t) { logger.log(marker, FQCN, LocationAwareLogger.WARN_INT, msg, null, t); } @Override - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return logger.isErrorEnabled(); } @Override - public void error(String msg) - { + public void error(String msg) { logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, null); } @Override - public void error(String format, Object arg) - { + public void error(String format, Object arg) { logger.error(format, arg); } @Override - public void error(String format, Object arg1, Object arg2) - { + public void error(String format, Object arg1, Object arg2) { logger.error(format, arg1, arg2); } @Override - public void error(String format, Object... arguments) - { + public void error(String format, Object... arguments) { logger.error(format, arguments); } @Override - public void error(String msg, Throwable t) - { + public void error(String msg, Throwable t) { logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, msg, null, t); } @Override - public boolean isErrorEnabled(Marker marker) - { + public boolean isErrorEnabled(Marker marker) { return logger.isErrorEnabled(marker); } @Override - public void error(Marker marker, String msg) - { + 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) - { + 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) - { + 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) - { + public void error(Marker marker, String format, Object... arguments) { logger.error(marker, format, arguments); } @Override - public void error(Marker marker, String msg, Throwable t) - { + public void error(Marker marker, String msg, Throwable t) { logger.log(marker, FQCN, LocationAwareLogger.ERROR_INT, msg, null, t); } diff --git a/src/main/java/org/asteriskjava/util/internal/Log4JLogger.java b/src/main/java/org/asteriskjava/util/internal/Log4JLogger.java index 96c05fb0b..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,13 +16,14 @@ package org.asteriskjava.util.internal; -import java.io.Serializable; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; -import org.apache.log4j.Priority; +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. @@ -31,14 +32,13 @@ * 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 @@ -47,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 @@ -79,238 +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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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(Level.ERROR); - } - 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(Level.FATAL); - } - 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(); } /** @@ -318,21 +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(Level.WARN); - } - 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 ca6e1bff5..445080be5 100644 --- a/src/main/java/org/asteriskjava/util/internal/NullLog.java +++ b/src/main/java/org/asteriskjava/util/internal/NullLog.java @@ -23,52 +23,42 @@ *

    * 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() - { + public boolean isDebugEnabled() { return false; } @Override - public void debug(Object e, Throwable e2) - { + public void debug(Object e, Throwable e2) { } } diff --git a/src/main/java/org/asteriskjava/util/internal/ServerSocketFacadeImpl.java b/src/main/java/org/asteriskjava/util/internal/ServerSocketFacadeImpl.java index 5d9bbc64f..ccef0449c 100644 --- a/src/main/java/org/asteriskjava/util/internal/ServerSocketFacadeImpl.java +++ b/src/main/java/org/asteriskjava/util/internal/ServerSocketFacadeImpl.java @@ -16,14 +16,14 @@ */ 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 @@ -32,20 +32,17 @@ * @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(); @@ -53,13 +50,11 @@ public SocketConnectionFacade accept() throws IOException return new SocketConnectionFacadeImpl(socket, socketReadTimeout); } - public void close() throws IOException - { + public void close() throws IOException { serverSocket.close(); } - public void setSocketReadTimeout(int socketReadTimeout) - { + 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 3374debb9..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. @@ -16,13 +16,13 @@ package org.asteriskjava.util.internal; -import java.io.Serializable; - 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. @@ -30,30 +30,31 @@ * * @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; static String FQCN = Slf4JLogger.class.getName(); - /** Logger name */ - private Class< ? > clazz = null; + /** + * 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(); } @@ -62,80 +63,70 @@ 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); } @@ -144,8 +135,7 @@ public void error(Object message, Throwable t) *

    * Currently uses the ERROR priority in SLF4J. */ - public void fatal(Object message) - { + public void fatal(Object message) { getLogger().error(message.toString()); } @@ -154,22 +144,18 @@ public void fatal(Object message) *

    * 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); } - if (logger instanceof LocationAwareLogger) - { + if (logger instanceof LocationAwareLogger) { return new LocationAwareWrapper(FQCN, (LocationAwareLogger) logger); } return this.logger; @@ -179,8 +165,7 @@ public final Logger getLogger() * Check whether the SLF4J Logger used is enabled for DEBUG * priority. */ - public boolean isDebugEnabled() - { + public boolean isDebugEnabled() { return getLogger().isDebugEnabled(); } @@ -188,8 +173,7 @@ public boolean isDebugEnabled() * Check whether the SLF4J Logger used is enabled for ERROR * priority. */ - public boolean isErrorEnabled() - { + public boolean isErrorEnabled() { return getLogger().isErrorEnabled(); } @@ -198,8 +182,7 @@ public boolean isErrorEnabled() * priority. For SLF4J, this returns the value of * isErrorEnabled() */ - public boolean isFatalEnabled() - { + public boolean isFatalEnabled() { return isErrorEnabled(); } @@ -207,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(); } @@ -216,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(); } @@ -225,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(); } } diff --git a/src/main/java/org/asteriskjava/util/internal/SocketConnectionFacadeImpl.java b/src/main/java/org/asteriskjava/util/internal/SocketConnectionFacadeImpl.java index 9ef606a43..e50c6f0be 100644 --- a/src/main/java/org/asteriskjava/util/internal/SocketConnectionFacadeImpl.java +++ b/src/main/java/org/asteriskjava/util/internal/SocketConnectionFacadeImpl.java @@ -16,12 +16,13 @@ */ package org.asteriskjava.util.internal; -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; @@ -30,21 +31,13 @@ import java.util.NoSuchElementException; import java.util.regex.Pattern; -import javax.net.SocketFactory; -import javax.net.ssl.SSLSocketFactory; - -import org.asteriskjava.util.SocketConnectionFacade; -import org.asteriskjava.util.internal.streamreader.FastScanner; -import org.asteriskjava.util.internal.streamreader.FastScannerFactory; - /** * 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; @@ -53,39 +46,35 @@ public class SocketConnectionFacadeImpl implements SocketConnectionFacade private Trace trace; /** - * <<<<<<< HEAD Creates a new instance for use with the Manager API that - * uses UTF-8 as encoding and CRNL ("\r\n") as line delimiter. ======= - * Creates a new instance for use with the Manager API that uses CRNL - * ("\r\n") as line delimiter. >>>>>>> refs/heads/release-1.1 + * 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. - * @param ssl true to use SSL, false otherwise. - * @param timeout 0 incidcates default + * @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)} * @throws IOException if the connection cannot be established. */ - public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeout, int readTimeout) throws IOException - { + 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 - * encoding and CRNL ("\r\n") as line delimiter. + * 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 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 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 - { + throws IOException { this(host, port, ssl, timeout, readTimeout, encoding, CRNL_PATTERN); } @@ -93,18 +82,17 @@ public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeou * 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 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 + * 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 - { + Pattern lineDelimiter) throws IOException { this(host, port, ssl, timeout, readTimeout, StandardCharsets.UTF_8, lineDelimiter); } @@ -112,36 +100,31 @@ public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeou * 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 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 + * for the socket * @throws IOException if the connection cannot be established. */ public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeout, int readTimeout, Charset encoding, - Pattern lineDelimiter) throws IOException - { + 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, encoding, lineDelimiter); - if (System.getProperty(Trace.TRACE_PROPERTY, "false").equalsIgnoreCase("true")) - { + if (System.getProperty(Trace.TRACE_PROPERTY, "false").equalsIgnoreCase("true")) { trace = new FileTrace(socket); } } @@ -153,22 +136,19 @@ public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeou * @param socket the underlying socket. * @throws IOException if the connection cannot be initialized. */ - SocketConnectionFacadeImpl(Socket socket) throws IOException - { + 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 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) - { + SocketConnectionFacadeImpl(Socket socket, int timeout) throws IOException { + if (timeout == -1) { timeout = 0; } else if (timeout == 0) { timeout = MAX_SOCKET_READ_TIMEOUT_MILLIS; @@ -177,11 +157,12 @@ public SocketConnectionFacadeImpl(String host, int port, boolean ssl, int timeou initialize(socket, StandardCharsets.UTF_8, NL_PATTERN); } - /** 3 hrs = 3 * 3660 * 1000 */ + /** + * 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 - { + private void initialize(Socket socket, Charset encoding, Pattern pattern) throws IOException { this.socket = socket; InputStream inputStream = socket.getInputStream(); @@ -194,79 +175,62 @@ private void initialize(Socket socket, Charset encoding, Pattern pattern) throws } @Override - public String readLine() throws IOException - { + public String readLine() throws IOException { String line = null; - try - { + try { line = scanner.next(); - } - catch (IllegalStateException e) - { + } catch (IllegalStateException e) { // throw new IOException("No more lines available", e); // JDK6 throw new IOException("No more lines available: " + e.getMessage()); - } - catch (NoSuchElementException e) - { + } 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) - { + 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 eb8314908..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,17 +12,19 @@ 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. */ 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 index 89ce1888c..5ca4eebde 100644 --- a/src/main/java/org/asteriskjava/util/internal/streamreader/FastScanner.java +++ b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScanner.java @@ -3,8 +3,7 @@ import java.io.Closeable; import java.io.IOException; -public interface FastScanner extends Closeable -{ +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 index c6d48e826..cdbfac239 100644 --- a/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerCrNl.java +++ b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerCrNl.java @@ -1,39 +1,30 @@ package org.asteriskjava.util.internal.streamreader; -public class FastScannerCrNl extends FastScannerNl -{ +public class FastScannerCrNl extends FastScannerNl { private char crChar = '\r'; private boolean seenReturn = false; - public FastScannerCrNl(Readable reader) - { + public FastScannerCrNl(Readable reader) { super(reader); } - protected String getLine(boolean endOfLine) - { + 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) - { + 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) - { + } 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) - { + if (i == start) { // back track to remove a /r in the last packet result.setLength(result.length() - 1); } - if (i > start) - { + if (i > start) { // append the data to the StringBuilder result.append(cbuf.subSequence(start, start + (i - start) - 1)); } @@ -50,15 +41,12 @@ else if (seenReturn && cbuf.get(i) == nlChar) seenReturn = false; return tmp; - } - else - { + } else { // clear the delimiter seen flag seenReturn = false; } } - if (end >= start) - { + 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 diff --git a/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerFactory.java b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerFactory.java index 130a2baec..10c48ac77 100644 --- a/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerFactory.java +++ b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerFactory.java @@ -1,29 +1,24 @@ 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; -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; - -public class FastScannerFactory -{ +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")) - { + 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")) - { + if (pattern.pattern().equals("\n")) { return new FastScannerNl(reader); } } @@ -38,32 +33,24 @@ public static FastScanner getReader(Readable reader, Pattern pattern) } - public static void useLegacyScanner(boolean b) - { + public static void useLegacyScanner(boolean b) { useLegacyScanner = b; } - private static FastScanner getWrappedScanner(final Scanner scanner) - { - return new FastScanner() - { + private static FastScanner getWrappedScanner(final Scanner scanner) { + return new FastScanner() { @Override - public String next() throws IOException - { - try - { + public String next() throws IOException { + try { return scanner.next(); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { return null; } } @Override - public void close() - { + 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 index fab787e00..a24327aa9 100644 --- a/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerNl.java +++ b/src/main/java/org/asteriskjava/util/internal/streamreader/FastScannerNl.java @@ -1,6 +1,8 @@ - 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; @@ -11,11 +13,7 @@ import java.nio.file.StandardOpenOption; import java.util.concurrent.atomic.AtomicReference; -import org.asteriskjava.util.Log; -import org.asteriskjava.util.LogFactory; - -public class FastScannerNl implements FastScanner -{ +public class FastScannerNl implements FastScanner { private static final Log logger = LogFactory.getLog(FastScannerNl.class); private static final int BUFFER_SIZE = 8192; @@ -27,7 +25,7 @@ public class FastScannerNl implements FastScanner protected int end = 0; protected int start = 0; private boolean closed = false; - protected final Object sync = new Object(); + // protected final Object sync = new Object(); private boolean isFirst = true; @@ -35,22 +33,19 @@ public class FastScannerNl implements FastScanner private BufferedWriter writer; - public FastScannerNl(Readable reader) - { + public FastScannerNl(Readable reader) { this.readableReference.set(reader); // createFileWriter(); } - public String next() throws IOException - { + public String next() throws IOException { int bytes = 0; // check for a line in the buffer String line = getLine(false); - if (line == null) - { + 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 @@ -58,8 +53,7 @@ public String next() throws IOException Readable readable = readableReference.get(); // read from the stream to the buffer - while (readable != null && (bytes = readable.read(cbuf)) > -1) - { + while (readable != null && (bytes = readable.read(cbuf)) > -1) { // writeToFile(bytes); // set buffer position to 0 @@ -70,10 +64,8 @@ public String next() throws IOException // try to get a line from the buffer line = getLine(bytes >= 0); - if (line != null) - { - if (isFirst && line.length() == 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); @@ -85,22 +77,18 @@ public String next() throws IOException } // clear the first line flag isFirst = false; - if (line == null) - - { + 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) - { + 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) - { + if (bytes == -1 && tmp.length() == 0) { return null; } return tmp; @@ -109,15 +97,11 @@ public String next() throws IOException } - protected String getLine(boolean endOfLine) - { + 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) - { + 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))); } @@ -133,8 +117,7 @@ protected String getLine(boolean endOfLine) } } - if (end >= start) - { + 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 @@ -145,53 +128,42 @@ protected String getLine(boolean endOfLine) 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); - } + 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; } + readableReference.set(null); + closed = true; + // } } @SuppressWarnings("unused") - private void createFileWriter() - { - try - { + private void createFileWriter() { + try { logfile = File.createTempFile(this.getClass().getSimpleName(), "txt"); writer = Files.newBufferedWriter(logfile.toPath(), Charset.defaultCharset(), StandardOpenOption.APPEND); - } - catch (IOException e) - { + } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("unused") - private void writeToFile(int bytes) throws IOException - { + 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 - { + 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/test/java/org/asteriskjava/AsteriskVersionTest.java b/src/test/java/org/asteriskjava/AsteriskVersionTest.java index 8942533c5..24f28bace 100644 --- a/src/test/java/org/asteriskjava/AsteriskVersionTest.java +++ b/src/test/java/org/asteriskjava/AsteriskVersionTest.java @@ -1,36 +1,38 @@ package org.asteriskjava; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -public class AsteriskVersionTest -{ +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +class AsteriskVersionTest { @Test - public void testNullIfNoMatch() - { + void testNullIfNoMatch() { assertNull(AsteriskVersion.getDetermineVersionFromString("")); } - + @Test - public void test13() - { + void test13() { assertTrue(AsteriskVersion.getDetermineVersionFromString("Asterisk 13.1.0~dfsg-1.1ubuntu4.1") .equals(AsteriskVersion.ASTERISK_13)); } @Test - public void test14() - { + void test14() { assertTrue(AsteriskVersion.getDetermineVersionFromString("Asterisk 14.1.0").equals(AsteriskVersion.ASTERISK_14)); } @Test - public void test15() - { + 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)); + } } diff --git a/src/test/java/org/asteriskjava/config/ConfigFileParserTest.java b/src/test/java/org/asteriskjava/config/ConfigFileParserTest.java index c35a43564..9327f9bb1 100644 --- a/src/test/java/org/asteriskjava/config/ConfigFileParserTest.java +++ b/src/test/java/org/asteriskjava/config/ConfigFileParserTest.java @@ -1,27 +1,22 @@ package org.asteriskjava.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.CharBuffer; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; -public class ConfigFileParserTest -{ +class ConfigFileParserTest { ConfigFileReader configFileReader; - @Before - public void setUp() - { + @BeforeEach + void setUp() { configFileReader = new ConfigFileReader(); } @Test - public void testProcessLine() throws Exception - { + void testProcessLine() throws Exception { String s = " a ;-- comment --; = b ; a line comment"; CharBuffer buffer = CharBuffer.allocate(s.length()); @@ -30,137 +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"); } @Test - public void testParseCategoryHeader() throws Exception - { + 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"); } } @Test - public void testParseDirective() throws ConfigParseException - { + 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) - { + } catch (MissingDirectiveParameterException e) { assertEquals("Directive '#include' needs an argument (filename) at line 805 of /etc/asterisk/sip.conf", e.getMessage()); } } @Test - public void testParseVariable() throws ConfigParseException - { + 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() - { - 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 5b990ae5e..4e887cfaf 100644 --- a/src/test/java/org/asteriskjava/fastagi/ClassNameMappingStrategyTest.java +++ b/src/test/java/org/asteriskjava/fastagi/ClassNameMappingStrategyTest.java @@ -16,34 +16,29 @@ */ package org.asteriskjava.fastagi; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ClassNameMappingStrategyTest -{ +class ClassNameMappingStrategyTest { private ClassNameMappingStrategy mappingStrategy; - @Before - public void setUp() - { + @BeforeEach + void setUp() { this.mappingStrategy = new ClassNameMappingStrategy(); } @Test - public void testDetermineScript() - { + void testDetermineScript() { AgiScript scriptFirstPass; AgiScript scriptSecondPass; AgiRequest request; - request = new SimpleAgiRequest() - { + request = new SimpleAgiRequest() { @Override - public String getScript() - { + public String getScript() { return "org.asteriskjava.fastagi.HelloAgiScript"; } }; @@ -51,24 +46,21 @@ 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"); } @Test - public void testDetermineScriptWithNonSharedInstance() - { + void testDetermineScriptWithNonSharedInstance() { AgiScript scriptFirstPass; AgiScript scriptSecondPass; AgiRequest request; mappingStrategy.setShareInstances(false); - request = new SimpleAgiRequest() - { + request = new SimpleAgiRequest() { @Override - public String getScript() - { + public String getScript() { return "org.asteriskjava.fastagi.HelloAgiScript"; } }; @@ -76,8 +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 8878415d0..eb8c9f3f3 100644 --- a/src/test/java/org/asteriskjava/fastagi/CompositeMappingStrategyTest.java +++ b/src/test/java/org/asteriskjava/fastagi/CompositeMappingStrategyTest.java @@ -1,39 +1,35 @@ package org.asteriskjava.fastagi; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -public class CompositeMappingStrategyTest -{ +class CompositeMappingStrategyTest { private CompositeMappingStrategy strategy; - @Before - public void setUp() - { + @BeforeEach + void setUp() { strategy = new CompositeMappingStrategy(new ResourceBundleMappingStrategy("test-mapping"), new ClassNameMappingStrategy()); } @Test - public void testAJ37ResourceBundle() - { + 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"); } @Test - public void testAJ37ClassName() - { + 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 3fc9ca04f..2e08c0ffb 100644 --- a/src/test/java/org/asteriskjava/fastagi/DefaultAgiServerTest.java +++ b/src/test/java/org/asteriskjava/fastagi/DefaultAgiServerTest.java @@ -16,144 +16,119 @@ */ package org.asteriskjava.fastagi; -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 static org.junit.Assert.assertEquals; +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 org.asteriskjava.util.ServerSocketFacade; -import org.asteriskjava.util.SocketConnectionFacade; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class DefaultAgiServerTest -{ +class DefaultAgiServerTest { private DefaultAgiServer server; private MockedServerSocketFacade serverSocket; private SocketConnectionFacade socket; - @Before - public void setUp() - { + @BeforeEach + void setUp() { serverSocket = new MockedServerSocketFacade(); server = new MockedDefaultAgiServer(); } - @After - public void tearDown() throws Exception - { + @AfterEach + void tearDown() throws Exception { server.shutdown(); } @Test - public void testDummy() - { + void testDummy() { } - public void XtestStartup() throws Exception - { - socket = createMock(SocketConnectionFacade.class); + void XtestStartup() throws Exception { + socket = mock(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); + 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; } throw new IOException("Provoked IOException"); } - public void close() throws IOException - { + public void close() throws IOException { closeCalls++; } - public void setSocketReadTimeout(int socketReadTimeout) - { + public void setSocketReadTimeout(int socketReadTimeout) { } } @Test - public void testLoadConfigWithDefaultPort() - { + void testLoadConfigWithDefaultPort() { DefaultAgiServer defaultAgiServer; defaultAgiServer = new DefaultAgiServer(); - assertEquals("Invalid default port", 4573, defaultAgiServer.getPort()); + assertEquals(4573, defaultAgiServer.getPort(), "Invalid default port"); } @Test - public void testLoadConfigWithPort() - { + 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"); } @Test - public void testLoadConfigWithBindPort() - { + 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 c235f290a..e8d24b332 100644 --- a/src/test/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategyTest.java +++ b/src/test/java/org/asteriskjava/fastagi/ResourceBundleMappingStrategyTest.java @@ -16,28 +16,22 @@ */ package org.asteriskjava.fastagi; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; -public class ResourceBundleMappingStrategyTest -{ +class ResourceBundleMappingStrategyTest { private ResourceBundleMappingStrategy mappingStrategy; - @Before - public void setUp() - { + @BeforeEach + void setUp() { this.mappingStrategy = new ResourceBundleMappingStrategy(); this.mappingStrategy.setResourceBundleName("test-mapping"); } @Test - public void testDetermineScript() - { + void testDetermineScript() { AgiScript scriptFirstPass; AgiScript scriptSecondPass; AgiRequest request; @@ -47,15 +41,14 @@ 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"); } @Test - public void testDetermineScriptWithResourceBundleUnavailable() - { + void testDetermineScriptWithResourceBundleUnavailable() { AgiRequest request; request = new SimpleAgiRequest(); @@ -65,8 +58,7 @@ public void testDetermineScriptWithResourceBundleUnavailable() } @Test - public void testDetermineScriptWithNonSharedInstance() - { + void testDetermineScriptWithNonSharedInstance() { AgiScript scriptFirstPass; AgiScript scriptSecondPass; AgiRequest request; @@ -77,8 +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 205ec0988..31f6e03d2 100644 --- a/src/test/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategyTest.java +++ b/src/test/java/org/asteriskjava/fastagi/ScriptEngineMappingStrategyTest.java @@ -1,28 +1,25 @@ package org.asteriskjava.fastagi; -import static org.asteriskjava.fastagi.ScriptEngineMappingStrategy.getExtension; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; +import static org.asteriskjava.fastagi.ScriptEngineMappingStrategy.getExtension; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -public class ScriptEngineMappingStrategyTest -{ +class ScriptEngineMappingStrategyTest { private ScriptEngineMappingStrategy scriptEngineMappingStrategy; - @Before - public void setUp() - { + @BeforeEach + void setUp() { this.scriptEngineMappingStrategy = new ScriptEngineMappingStrategy(); } @Test - public void testSearchFile() throws IOException - { + 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[]{})); @@ -32,16 +29,14 @@ public void testSearchFile() throws IOException } @Test - public void testSearchFileOutsidePath() - { + 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"})); } @Test - public void testGetExtension() - { + 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 1d1cd65e5..411678e29 100644 --- a/src/test/java/org/asteriskjava/fastagi/SimpleAgiRequest.java +++ b/src/test/java/org/asteriskjava/fastagi/SimpleAgiRequest.java @@ -16,13 +16,12 @@ */ package org.asteriskjava.fastagi; +import org.asteriskjava.AsteriskVersion; + import java.net.InetAddress; import java.util.Map; -import org.asteriskjava.AsteriskVersion; - -public class SimpleAgiRequest implements AgiRequest -{ +public class SimpleAgiRequest implements AgiRequest { InetAddress localAddress; int localPort; InetAddress remoteAddress; @@ -30,48 +29,39 @@ public class SimpleAgiRequest implements AgiRequest 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(); } @@ -82,142 +72,115 @@ public String getLanguage() * Caller ID. * * @return the Caller*ID number, for example "1234", if no Caller*ID is set - * or it is "unknown" null is returned. + * 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; } @Override - public AsteriskVersion getAsteriskVersion() - { + 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 d15e6ec28..e0e0c0790 100644 --- a/src/test/java/org/asteriskjava/fastagi/command/AbstractAgiCommandTest.java +++ b/src/test/java/org/asteriskjava/fastagi/command/AbstractAgiCommandTest.java @@ -1,90 +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 static org.junit.Assert.assertEquals; +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(); -import org.junit.Test; + //then + assertThat(actual).isEqualTo("MY \"\""); + } + + @Test + void shouldHandleEmptyString() { + //given + MyCommand myCommand = new MyCommand(""); -public class AbstractAgiCommandTest -{ - private MyCommand myCommand; + //when + String actual = myCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("MY \"\""); + } @Test - public void testEscapeAndQuote() - { - myCommand = new MyCommand("just a string"); + void shouldEscapeAndQuoteWithStringContainingQuotes() { + //given + MyCommand myCommand = new MyCommand("\"John Doe\" is calling"); - assertEquals("MY \"just a string\"", myCommand.buildCommand()); + //given + String actual = myCommand.buildCommand(); + + //when + assertThat(actual).isEqualTo("MY \"\\\"John Doe\\\" is calling\""); } @Test - public void testEscapeAndQuoteWithNullString() - { - myCommand = new MyCommand(null); + 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\""); } @Test - public void testEscapeAndQuoteWithEmptyString() - { - myCommand = new MyCommand(""); + void shouldEscapedQuotesAJ192() { + //given + MyCommand myCommand = new MyCommand("first \\\" second \\\" third"); + + //when + String actual = myCommand.buildCommand(); - assertEquals("MY \"\"", myCommand.buildCommand()); + //then + assertThat(actual).isEqualTo("MY \"first \\\\\\\" second \\\\\\\" third\""); } @Test - public void testEscapeAndQuoteWithStringContainingQuotes() - { - myCommand = new MyCommand("\"John Doe\" is calling"); + void shouldFormatToString() { + //given + MyCommand myCommand = new MyCommand("just a string"); - assertEquals("MY \"\\\"John Doe\\\" is calling\"", myCommand.buildCommand()); + //when + String actual = myCommand.toString(); + + //then + assertThat(actual).contains("command='MY \"just a string\"'"); } @Test - public void testEscapeAndQuoteWithStringContainingNewline() - { - myCommand = new MyCommand("Caller is:\nJohn Doe"); + 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\""); } @Test - public void testEscapedQuotesAJ192() { - myCommand = new MyCommand("first \\\" second \\\" third"); + 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 be722d18c..09cf4d6c9 100644 --- a/src/test/java/org/asteriskjava/fastagi/command/ExecCommandTest.java +++ b/src/test/java/org/asteriskjava/fastagi/command/ExecCommandTest.java @@ -1,61 +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 static org.junit.Assert.assertEquals; - -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ExecCommandTest -{ - private ExecCommand execCommand; +import static org.assertj.core.api.Assertions.assertThat; +class ExecCommandTest { @Test - public void testDefault() - { - execCommand = new ExecCommand("DIAL"); - assertEquals("EXEC \"DIAL\" \"\"", execCommand.buildCommand()); + void shouldExecApplicationWithoutOptions() { + //given + ExecCommand execCommand = new ExecCommand("DIAL"); + + //when + String actual = execCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"DIAL\" \"\""); } @Test - public void testWithSingleOption() - { - execCommand = new ExecCommand("DIAL", "SIP/1234"); - assertEquals("EXEC \"DIAL\" \"SIP/1234\"", execCommand.buildCommand()); + void shouldExecApplicationWithSingleOption() { + //given + ExecCommand execCommand = new ExecCommand("DIAL", "SIP/1234"); + + //when + String actual = execCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("EXEC \"DIAL\" \"SIP/1234\""); } @Test - public void testWithMultipleOptionsSingleParameterPipeSeparated() - { - execCommand = new ExecCommand("DIAL", "SIP/1234|30"); - assertEquals("EXEC \"DIAL\" \"SIP/1234|30\"", execCommand.buildCommand()); + 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\""); } @Test - public void testWithMultipleOptionsSingleParameterCommaSeparated() - { - execCommand = new ExecCommand("DIAL", "SIP/1234,30"); - assertEquals("EXEC \"DIAL\" \"SIP/1234,30\"", execCommand.buildCommand()); + 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\""); } @Test - public void testWithMultipleOptionsMultipleParameters() - { - execCommand = new ExecCommand("DIAL", "SIP/1234", "30"); - assertEquals("EXEC \"DIAL\" \"SIP/1234,30\"", execCommand.buildCommand()); + 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 c6a1430a2..1c78d5f5d 100644 --- a/src/test/java/org/asteriskjava/fastagi/command/GetDataCommandTest.java +++ b/src/test/java/org/asteriskjava/fastagi/command/GetDataCommandTest.java @@ -1,64 +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 static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class GetDataCommandTest -{ +class GetDataCommandTest { private GetDataCommand getDataCommand; @Test - public void testDefault() - { - getDataCommand = new GetDataCommand("VAR1"); - assertEquals("GET DATA \"VAR1\"", getDataCommand.buildCommand()); + void shouldBuildGetDataCommand() { + //given + GetDataCommand getDataCommand = new GetDataCommand("VAR1"); + + //when + String actual = getDataCommand.buildCommand(); + + //then + assertThat(actual).isEqualTo("GET DATA \"VAR1\""); } @Test - public void testSetTimeout() - { - getDataCommand = new GetDataCommand("VAR1"); + 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); } @Test - public void testSetMaxDigits() - { - getDataCommand = new GetDataCommand("VAR1"); + 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); } @Test - public void testSetTimeoutAndMaxDigits() - { - getDataCommand = new GetDataCommand("VAR1"); + 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 83d5228a1..8a9b8ffff 100644 --- a/src/test/java/org/asteriskjava/fastagi/internal/AgiChannelImplTest.java +++ b/src/test/java/org/asteriskjava/fastagi/internal/AgiChannelImplTest.java @@ -16,42 +16,33 @@ */ package org.asteriskjava.fastagi.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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.asteriskjava.fastagi.*; +import org.asteriskjava.fastagi.command.NoopCommand; +import org.asteriskjava.fastagi.reply.AgiReply; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; -import org.asteriskjava.fastagi.AgiChannel; -import org.asteriskjava.fastagi.AgiReader; -import org.asteriskjava.fastagi.AgiWriter; -import org.asteriskjava.fastagi.InvalidCommandSyntaxException; -import org.asteriskjava.fastagi.InvalidOrUnknownCommandException; -import org.asteriskjava.fastagi.command.NoopCommand; -import org.asteriskjava.fastagi.reply.AgiReply; -import org.junit.Before; -import org.junit.Test; +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 -{ +class AgiChannelImplTest { private AgiWriter agiWriter; private AgiReader agiReader; private AgiChannel agiChannel; - @Before - public void 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); } @Test - public void testSendCommand() throws Exception - { + void testSendCommand() throws Exception { SimpleAgiReply reply; NoopCommand command; @@ -61,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); } @Test - public void testSendCommandWithInvalidOrUnknownCommandResponse() throws Exception - { + void testSendCommandWithInvalidOrUnknownCommandResponse() throws Exception { SimpleAgiReply reply; NoopCommand command; @@ -85,29 +68,18 @@ public void testSendCommandWithInvalidOrUnknownCommandResponse() throws Exceptio 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 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); } @Test - public void testSendCommandWithInvalidCommandSyntaxResponse() throws Exception - { + void testSendCommandWithInvalidCommandSyntaxResponse() throws Exception { SimpleAgiReply reply; NoopCommand command; @@ -119,103 +91,78 @@ public void testSendCommandWithInvalidCommandSyntaxResponse() throws Exception 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 - { + 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 fbf3a3b6a..58e351cb0 100644 --- a/src/test/java/org/asteriskjava/fastagi/internal/AgiReaderImplTest.java +++ b/src/test/java/org/asteriskjava/fastagi/internal/AgiReaderImplTest.java @@ -16,154 +16,124 @@ */ package org.asteriskjava.fastagi.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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.net.InetAddress; - import org.asteriskjava.fastagi.AgiHangupException; import org.asteriskjava.fastagi.AgiReader; import org.asteriskjava.fastagi.AgiRequest; import org.asteriskjava.fastagi.reply.AgiReply; import org.asteriskjava.util.SocketConnectionFacade; -import org.junit.Before; -import org.junit.Test; +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 -{ +class AgiReaderImplTest { private AgiReader agiReader; private SocketConnectionFacade socket; - @Before - public void setUp() - { - this.socket = createMock(SocketConnectionFacade.class); + @BeforeEach + void setUp() { + this.socket = mock(SocketConnectionFacade.class); this.agiReader = new FastAgiReader(socket); } @Test - public void testReadRequest() throws Exception - { + 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"); } @Test - public void testReadReply() throws Exception - { + 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"); } @Test - public void testReadReplyInvalidOrUnknownCommand() throws Exception - { + 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"); } @Test - public void testReadReplyInvalidCommandSyntax() throws Exception - { + 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"); } @Test - public void testReadReplyWhenHungUp() throws Exception - { - expect(socket.readLine()).andReturn(null); - - replay(socket); + 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 7690bb8e7..6b8699bdd 100644 --- a/src/test/java/org/asteriskjava/fastagi/internal/AgiReplyImplTest.java +++ b/src/test/java/org/asteriskjava/fastagi/internal/AgiReplyImplTest.java @@ -16,156 +16,144 @@ */ package org.asteriskjava.fastagi.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class AgiReplyImplTest -{ +class AgiReplyImplTest { private List lines; - @Before - public void setUp() - { - this.lines = new ArrayList(); + @BeforeEach + void setUp() { + this.lines = new ArrayList<>(); } @Test - public void testBuildReply() - { + 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()"); } @Test - public void testBuildReplyWithAdditionalAttribute() - { + 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"); } @Test - public void testBuildReplyWithMultipleAdditionalAttribute() - { + 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"); } @Test - public void testBuildReplyWithQuotedAttribute() - { + 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"); } @Test - public void testBuildReplyWithQuotedAttribute2() - { + 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); } @Test - public void testBuildReplyWithParenthesis() - { + 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"); } @Test - public void testBuildReplyWithAdditionalAttributeAndParenthesis() - { + 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"); } @Test - public void testBuildReplyInvalidOrUnknownCommand() - { + 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"); } @Test - public void testBuildReplyInvalidCommandSyntax() - { + void testBuildReplyInvalidCommandSyntax() { AgiReplyImpl reply; lines.add("520-Invalid command syntax. Proper usage follows:"); @@ -177,16 +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"); } @Test - public void testBuildReplyInvalidCommandSyntaxWithOnlyUsage() - { + void testBuildReplyInvalidCommandSyntaxWithOnlyUsage() { AgiReplyImpl reply; lines.add("520-Invalid command syntax. Proper usage follows:"); @@ -198,40 +183,36 @@ public void testBuildReplyInvalidCommandSyntaxWithOnlyUsage() reply = new AgiReplyImpl(lines); - assertEquals("Incorrect status", AgiReplyImpl.SC_INVALID_COMMAND_SYNTAX, reply.getStatus()); + 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("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("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"); } @Test - public void testBuildReplyWithLeadingSpace() - { + 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"); } @Test - public void testBuildReplyWithEmptyResultAndTimeout() - { + 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 4c49d8e49..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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import org.asteriskjava.AsteriskVersion; +import org.asteriskjava.fastagi.AgiRequest; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import org.asteriskjava.AsteriskVersion; -import org.asteriskjava.fastagi.AgiRequest; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; -public class AgiRequestImplTest -{ +class AgiRequestImplTest { @SuppressWarnings("deprecation") @Test - public void testBuildRequest() - { + void testBuildRequest() { List lines; AgiRequest request; @@ -58,28 +53,27 @@ public void testBuildRequest() 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("incorret Asterisk Version Number", AsteriskVersion.ASTERISK_13, request.getAsteriskVersion()); + 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"); } @Test - public void testBuildRequestWithAccountCode() - { + void testBuildRequestWithAccountCode() { List lines; AgiRequest request; @@ -91,13 +85,12 @@ public void testBuildRequestWithAccountCode() request = new AgiRequestImpl(lines); - assertEquals("incorrect accountCode", "12345", request.getAccountCode()); + assertEquals("12345", request.getAccountCode(), "incorrect accountCode"); } @SuppressWarnings("deprecation") @Test - public void testBuildRequestWithoutCallerIdName() - { + void testBuildRequestWithoutCallerIdName() { List lines; AgiRequest request; @@ -107,16 +100,15 @@ public void testBuildRequestWithoutCallerIdName() request = new AgiRequestImpl(lines); - assertEquals("incorrect callerId", "1234", request.getCallerId()); - assertEquals("incorrect callerIdNumber", "1234", request.getCallerIdNumber()); + assertEquals("1234", request.getCallerId(), "incorrect callerId"); + assertEquals("1234", request.getCallerIdNumber(), "incorrect callerIdNumber"); // assertNull("callerIdName must not be set", // request.getCallerIdName()); } @SuppressWarnings("deprecation") @Test - public void testBuildRequestWithoutCallerIdNameButBracket() - { + void testBuildRequestWithoutCallerIdNameButBracket() { List lines; AgiRequest request; @@ -126,15 +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") @Test - public void testBuildRequestWithoutCallerIdNameButBracketAndQuotesAndSpace() - { + void testBuildRequestWithoutCallerIdNameButBracketAndQuotesAndSpace() { List lines; AgiRequest request; @@ -144,15 +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") @Test - public void testBuildRequestWithQuotedCallerIdName() - { + void testBuildRequestWithQuotedCallerIdName() { List lines; AgiRequest request; @@ -162,15 +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") @Test - public void testBuildRequestWithQuotedCallerIdNameAndSpace() - { + void testBuildRequestWithQuotedCallerIdNameAndSpace() { List lines; AgiRequest request; @@ -180,15 +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") @Test - public void testBuildRequestWithoutCallerId() - { + void testBuildRequestWithoutCallerId() { List lines; AgiRequest request; @@ -198,9 +186,9 @@ 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"); } /* @@ -209,8 +197,7 @@ public void testBuildRequestWithoutCallerId() */ @SuppressWarnings("deprecation") @Test - public void testBuildRequestCallerIdAsterisk12() - { + void testBuildRequestCallerIdAsterisk12() { List lines; AgiRequest request; @@ -221,15 +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") @Test - public void testBuildRequestCallerIdAsterisk12WithUnknownCallerId() - { + void testBuildRequestCallerIdAsterisk12WithUnknownCallerId() { List lines; AgiRequest request; @@ -240,15 +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") @Test - public void testBuildRequestCallerIdAsterisk12WithUnknownCallerIdName() - { + void testBuildRequestCallerIdAsterisk12WithUnknownCallerIdName() { List lines; AgiRequest request; @@ -259,14 +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\""); } @Test - public void testBuildRequestCallerIdWithUnknownDnid() - { + void testBuildRequestCallerIdWithUnknownDnid() { List lines; AgiRequest request; @@ -276,12 +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\""); } @Test - public void testBuildRequestCallerIdWithUnknownRdnis() - { + void testBuildRequestCallerIdWithUnknownRdnis() { List lines; AgiRequest request; @@ -291,25 +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\""); } @Test - public void testBuildRequestWithNullEnvironment() - { - try - { + void testBuildRequestWithNullEnvironment() { + try { new AgiRequestImpl(null); fail("No IllegalArgumentException thrown."); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { } } @Test - public void testBuildRequestWithUnusualInput() - { + void testBuildRequestWithUnusualInput() { List lines; AgiRequest request; @@ -322,12 +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"); } @Test - public void testBuildRequestWithoutParameters() - { + void testBuildRequestWithoutParameters() { List lines; AgiRequest request; @@ -338,19 +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()"); } @Test - public void testBuildRequestWithSingleValueParameters() - { + void testBuildRequestWithSingleValueParameters() { List lines; AgiRequest request; @@ -361,19 +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", - 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"); } @Test - public void testBuildRequestWithMultiValueParameter() - { + void testBuildRequestWithMultiValueParameter() { List lines; AgiRequest request; @@ -384,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'"); } @Test - public void testBuildRequestWithEmptyValueParameter() - { + void testBuildRequestWithEmptyValueParameter() { List lines; AgiRequest request; @@ -404,16 +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'"); } @Test - public void testBuildRequestWithUrlEncodedParameter() - { + void testBuildRequestWithUrlEncodedParameter() { List lines; AgiRequest request; @@ -424,14 +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'"); } @Test - public void testGetParameter() - { + void testGetParameter() { List lines; AgiRequest request; @@ -442,13 +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'"); } @Test - public void testGetArguments() - { + void testGetArguments() { List lines; AgiRequest request; @@ -461,15 +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"); } @Test - public void testGetArgumentsWithEmptyArgument() - { + void testGetArgumentsWithEmptyArgument() { List lines; AgiRequest request; @@ -483,16 +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"); } @Test - public void testGetArgumentsWithNoArgumentsPassed() - { + void testGetArgumentsWithNoArgumentsPassed() { List lines; AgiRequest request; @@ -503,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 1c934bab3..d6188bbac 100644 --- a/src/test/java/org/asteriskjava/fastagi/internal/AgiWriterImplTest.java +++ b/src/test/java/org/asteriskjava/fastagi/internal/AgiWriterImplTest.java @@ -16,42 +16,34 @@ */ package org.asteriskjava.fastagi.internal; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - import org.asteriskjava.fastagi.AgiWriter; import org.asteriskjava.fastagi.command.StreamFileCommand; import org.asteriskjava.util.SocketConnectionFacade; -import org.junit.Before; -import org.junit.Test; +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 -{ +class AgiWriterImplTest { private AgiWriter agiWriter; private SocketConnectionFacade socket; - @Before - public void setUp() - { - this.socket = createMock(SocketConnectionFacade.class); + @BeforeEach + void setUp() { + this.socket = mock(SocketConnectionFacade.class); this.agiWriter = new FastAgiWriter(socket); } @Test - public void testSendCommand() throws Exception - { + 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 06070ecbb..8c3ba17de 100644 --- a/src/test/java/org/asteriskjava/live/CallerIdTest.java +++ b/src/test/java/org/asteriskjava/live/CallerIdTest.java @@ -1,14 +1,12 @@ package org.asteriskjava.live; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class CallerIdTest -{ +class CallerIdTest { @Test - public void testEquals() - { + void testEquals() { CallerId callerId1; CallerId callerId2; @@ -30,8 +28,7 @@ public void testEquals() } @Test - public void testValueOf() - { + void testValueOf() { CallerId callerId = new CallerId("Hans Wurst", "1234"); assertEquals(callerId, CallerId.valueOf("\"Hans Wurst\" <1234>")); assertEquals(callerId, CallerId.valueOf("Hans Wurst <1234>")); @@ -39,8 +36,7 @@ public void testValueOf() } @Test - public void testValueOfWithNullLiteralInName() - { + void testValueOfWithNullLiteralInName() { CallerId callerId = new CallerId(null, "1234"); assertEquals(callerId, CallerId.valueOf("\"\" <1234>")); assertEquals(callerId, CallerId.valueOf("\"\" <1234>")); @@ -49,8 +45,7 @@ public void testValueOfWithNullLiteralInName() } @Test - public void testValueOfWithNullLiteralInNumber() - { + void testValueOfWithNullLiteralInNumber() { CallerId callerId = new CallerId("Hans Wurst", null); assertEquals(callerId, CallerId.valueOf("\"Hans Wurst\" <>")); // assertEquals(callerId, @@ -59,8 +54,7 @@ public void testValueOfWithNullLiteralInNumber() } @Test - public void testValueOfWithNullLiteralInNameAndNumber() - { + void testValueOfWithNullLiteralInNameAndNumber() { CallerId callerId = new CallerId(null, null); assertEquals(callerId, CallerId.valueOf("\"\" <>")); // assertEquals(callerId, CallerId.valueOf("<>")); @@ -72,14 +66,12 @@ public void testValueOfWithNullLiteralInNameAndNumber() } @Test - public void testConstructorWithNullLiteral() - { + void testConstructorWithNullLiteral() { assertEquals(new CallerId(null, "1234"), new CallerId("", "1234")); } @Test - public void testToString() - { + 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 562a1a5c5..49e1b633f 100644 --- a/src/test/java/org/asteriskjava/live/HangupCauseTest.java +++ b/src/test/java/org/asteriskjava/live/HangupCauseTest.java @@ -1,14 +1,12 @@ package org.asteriskjava.live; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class HangupCauseTest -{ +class HangupCauseTest { @Test - public void testGetByCode() - { - assertEquals("Valid enum for cause code 18", HangupCause.AST_CAUSE_NO_USER_RESPONSE, HangupCause.getByCode(18)); + 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 c02581595..537714c4a 100644 --- a/src/test/java/org/asteriskjava/live/QueueMemberStateTest.java +++ b/src/test/java/org/asteriskjava/live/QueueMemberStateTest.java @@ -1,21 +1,18 @@ package org.asteriskjava.live; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class QueueMemberStateTest -{ +class QueueMemberStateTest { @Test - public void testValueOf() - { + void testValueOf() { assertEquals(QueueMemberState.DEVICE_INUSE, QueueMemberState.valueOf("DEVICE_INUSE")); assertEquals(QueueMemberState.DEVICE_INUSE, QueueMemberState.valueOf(2)); } @Test - public void testToString() - { + 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 28e0ddbb1..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,50 +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 * @version $Id$ + * @since 0.1 */ -public class AsteriskAgentImplTest -{ +class AsteriskAgentImplTest { private AsteriskAgentImpl agent; private int numberOfChanges; - @Before - public void setUp() - { + @BeforeEach + void setUp() { AsteriskServerImpl server = new AsteriskServerImpl(); agent = new AsteriskAgentImpl(server, "Testagent", "Agent/999", AgentState.AGENT_IDLE); numberOfChanges = 0; } @Test - public void testUpdateStatus() - { + 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()); + 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("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/AsteriskChannelImplTest.java b/src/test/java/org/asteriskjava/live/internal/AsteriskChannelImplTest.java index 3c00156d3..897f312b6 100644 --- a/src/test/java/org/asteriskjava/live/internal/AsteriskChannelImplTest.java +++ b/src/test/java/org/asteriskjava/live/internal/AsteriskChannelImplTest.java @@ -1,23 +1,21 @@ package org.asteriskjava.live.internal; -import static org.junit.Assert.assertEquals; +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 org.asteriskjava.live.ChannelState; -import org.asteriskjava.util.DateUtil; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AsteriskChannelImplTest -{ +class AsteriskChannelImplTest { private AsteriskChannelImpl channel; private int numberOfChanges; - @Before - 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); @@ -25,21 +23,18 @@ public void setUp() } @Test - 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()); + 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 a77c53380..0550ac5a5 100644 --- a/src/test/java/org/asteriskjava/live/internal/AsteriskQueueMemberImplTest.java +++ b/src/test/java/org/asteriskjava/live/internal/AsteriskQueueMemberImplTest.java @@ -16,22 +16,21 @@ */ package org.asteriskjava.live.internal; -import static org.junit.Assert.assertEquals; +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 org.asteriskjava.live.QueueMemberState; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Patrick Breucking * @version $Id$ * @since 0.1 */ -public class AsteriskQueueMemberImplTest -{ +class AsteriskQueueMemberImplTest { private AsteriskQueueMemberImpl queueMember; private int numberOfChanges; @@ -39,9 +38,8 @@ public class AsteriskQueueMemberImplTest // private QueueManager qManager; private AsteriskQueueImpl queue; - @Before - public void setUp() - { + @BeforeEach + void setUp() { server = new AsteriskServerImpl(); // ChannelManager channelManager = new ChannelManager(server); // qManager = new QueueManager(server, channelManager); @@ -54,8 +52,7 @@ public void setUp() } @Test - public void testQueueMemberEvents() - { + void testQueueMemberEvents() { /* * Test should generate a new member like queueMember = new */ @@ -80,14 +77,12 @@ public void testQueueMemberEvents() // 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++; } @@ -96,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()); @@ -112,7 +107,7 @@ public void propertyChange(PropertyChangeEvent evt) // // } // - // public void onNewEntry(AsteriskChannel channel) + // void onNewEntry(AsteriskChannel channel) // { // // TODO Auto-generated method stub // @@ -126,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 index 38a1e0cdb..2a86c1072 100644 --- a/src/test/java/org/asteriskjava/manager/AbstractManagerEventListenerTest.java +++ b/src/test/java/org/asteriskjava/manager/AbstractManagerEventListenerTest.java @@ -2,48 +2,48 @@ import org.asteriskjava.manager.event.JoinEvent; import org.asteriskjava.manager.event.LeaveEvent; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class AbstractManagerEventListenerTest { +class AbstractManagerEventListenerTest { - @Test - public void shouldHandleJoinEvent() { - //given - EventListener listener = new EventListener(); + @Test + void shouldHandleJoinEvent() { + //given + EventListener listener = new EventListener(); - //when - listener.onManagerEvent(new JoinEvent(this)); + //when + listener.onManagerEvent(new JoinEvent(this)); - //then - assertTrue(listener.joinEventHandled); - } + //then + assertTrue(listener.joinEventHandled); + } - @Test - public void shouldHandleLeaveEvent() { - //given - EventListener listener = new EventListener(); + @Test + void shouldHandleLeaveEvent() { + //given + EventListener listener = new EventListener(); - //when - listener.onManagerEvent(new LeaveEvent(this)); + //when + listener.onManagerEvent(new LeaveEvent(this)); - //then - assertTrue(listener.leaveEventHandled); - } + //then + assertTrue(listener.leaveEventHandled); + } - private static class EventListener extends AbstractManagerEventListener { - public boolean joinEventHandled; - public boolean 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(JoinEvent event) { + this.joinEventHandled = true; + } - @Override - public void handleEvent(LeaveEvent event) { - this.leaveEventHandled = true; - } - } -} \ No newline at end of file + @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 588c0b855..5a2fa9c0c 100644 --- a/src/test/java/org/asteriskjava/manager/event/AsyncAgiEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/AsyncAgiEventTest.java @@ -1,16 +1,14 @@ package org.asteriskjava.manager.event; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; import java.util.List; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class AsyncAgiEventTest -{ +class AsyncAgiEventTest { @Test - public void testDecodeEnv() - { + void testDecodeEnv() { AsyncAgiEvent event = new AsyncAgiEvent(this); List env; @@ -41,8 +39,7 @@ public void testDecodeEnv() } @Test - public void testDecodeEnvWithMoreThanTwoDelimiters() - { + 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 f5ddb39fb..66162e811 100644 --- a/src/test/java/org/asteriskjava/manager/event/CdrEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/CdrEventTest.java @@ -1,49 +1,43 @@ package org.asteriskjava.manager.event; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.TimeZone; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class CdrEventTest -{ +class CdrEventTest { CdrEvent cdrEvent; TimeZone defaultTimeZone; - @Before - public void setUp() - { + @BeforeEach + void setUp() { cdrEvent = new CdrEvent(this); cdrEvent.setStartTime("2006-05-19 11:54:48"); defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } - @After - public void tearDown() - { + @AfterEach + void tearDown() { TimeZone.setDefault(defaultTimeZone); } @Test - public void testGetStartTimeAsDate() - { + void testGetStartTimeAsDate() { assertEquals(1148039688000L, cdrEvent.getStartTimeAsDate().getTime()); } @Test - public void testGetStartTimeAsDateWithTimeZone() - { + void testGetStartTimeAsDateWithTimeZone() { TimeZone tz = TimeZone.getTimeZone("GMT+2"); assertEquals(1148032488000L, cdrEvent.getStartTimeAsDate(tz).getTime()); } @Test - public void testBug() - { + void testBug() { TimeZone.setDefault(TimeZone.getTimeZone("Europe/Monaco")); cdrEvent.setStartTime("2006-05-29 13:17:21"); 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 3dddbf562..1618cccac 100644 --- a/src/test/java/org/asteriskjava/manager/event/ChannelReloadEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/ChannelReloadEventTest.java @@ -1,40 +1,35 @@ package org.asteriskjava.manager.event; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -public class ChannelReloadEventTest -{ +class ChannelReloadEventTest { private ChannelReloadEvent event; - @Before - public void setUp() - { + @BeforeEach + void setUp() { this.event = new ChannelReloadEvent(this); } @Test - public void testNullReloadReason() - { + void testNullReloadReason() { event.setReloadReason(null); assertNull(event.getReloadReasonCode()); assertNull(event.getReloadReasonDescription()); } @Test - public void testGetReloadReasonCode() - { + void testGetReloadReasonCode() { event.setReloadReason("CLIRELOAD (Channel module reload by CLI command)"); assertEquals("CLIRELOAD", event.getReloadReasonCode()); assertEquals(ChannelReloadEvent.REASON_CLI_RELOAD, event.getReloadReasonCode()); } @Test - public void testGetReloadReasonDescription() - { + 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 d07c1e05f..47e92601d 100644 --- a/src/test/java/org/asteriskjava/manager/event/NewStateEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/NewStateEventTest.java @@ -1,32 +1,28 @@ package org.asteriskjava.manager.event; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class NewStateEventTest -{ +class NewStateEventTest { private NewStateEvent newStateEvent; - @Before - public void setUp() - { + @BeforeEach + void setUp() { newStateEvent = new NewStateEvent(this); } @Test - public void testWithState() - { + void testWithState() { newStateEvent.setState("Ring"); - assertEquals(new Integer(4), newStateEvent.getChannelState()); + assertEquals(Integer.valueOf(4), newStateEvent.getChannelState()); assertEquals("Ring", newStateEvent.getChannelStateDesc()); } @Test - public void testWithUnknownState() - { + void testWithUnknownState() { newStateEvent.setState("Unknown (4)"); - assertEquals(new Integer(4), newStateEvent.getChannelState()); + assertEquals(Integer.valueOf(4), newStateEvent.getChannelState()); } } diff --git a/src/test/java/org/asteriskjava/manager/event/RtcpReceivedEventTest.java b/src/test/java/org/asteriskjava/manager/event/RtcpReceivedEventTest.java index f9b81e27b..c7485ea6a 100644 --- a/src/test/java/org/asteriskjava/manager/event/RtcpReceivedEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/RtcpReceivedEventTest.java @@ -1,54 +1,47 @@ package org.asteriskjava.manager.event; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class RtcpReceivedEventTest -{ +class RtcpReceivedEventTest { private RtcpReceivedEvent rtcpReceivedEvent; - @Before - public void setUp() - { + @BeforeEach + void setUp() { rtcpReceivedEvent = new RtcpReceivedEvent(this); } @Test - public void testFrom() - { + 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()); } @Test - public void testPt() - { + 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()); } @Test - public void testDlSr() - { + void testDlSr() { rtcpReceivedEvent.setDlSr("1.2345(sec)"); assertEquals(1.2345, rtcpReceivedEvent.getDlSr(), 0.00001); } @Test - public void testDlSrWithSpace() - { + void testDlSrWithSpace() { rtcpReceivedEvent.setDlSr("1.2345 (sec)"); // as used in RTCPSent assertEquals(1.2345, rtcpReceivedEvent.getDlSr(), 0.00001); } @Test - public void testRtt() - { + void testRtt() { rtcpReceivedEvent.setRtt("12345(sec)"); - assertEquals(new Double(12345), rtcpReceivedEvent.getRtt()); + assertEquals(Double.valueOf(12345), rtcpReceivedEvent.getRtt()); } } diff --git a/src/test/java/org/asteriskjava/manager/event/SkypeBuddyStatusEventTest.java b/src/test/java/org/asteriskjava/manager/event/SkypeBuddyStatusEventTest.java index 5fb8e1c12..bf8bfc728 100644 --- a/src/test/java/org/asteriskjava/manager/event/SkypeBuddyStatusEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/SkypeBuddyStatusEventTest.java @@ -1,30 +1,26 @@ package org.asteriskjava.manager.event; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class SkypeBuddyStatusEventTest -{ +class SkypeBuddyStatusEventTest { private SkypeBuddyStatusEvent event; - @Before - public void setUp() - { + @BeforeEach + void setUp() { event = new SkypeBuddyStatusEvent(this); event.setBuddy("Skype/user@the.buddy"); } @Test - public void testGetUser() - { + void testGetUser() { assertEquals("user", event.getUser()); } @Test - public void testGetBuddySkypename() - { + 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 786e26d89..e68a3f656 100644 --- a/src/test/java/org/asteriskjava/manager/event/SkypeChatMessageEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/SkypeChatMessageEventTest.java @@ -1,16 +1,14 @@ package org.asteriskjava.manager.event; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class SkypeChatMessageEventTest -{ +class SkypeChatMessageEventTest { @Test - public void testGetDecodedMessage() - { + 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 966bb2c7f..02af226bd 100644 --- a/src/test/java/org/asteriskjava/manager/event/T38FaxStatusEventTest.java +++ b/src/test/java/org/asteriskjava/manager/event/T38FaxStatusEventTest.java @@ -1,24 +1,18 @@ package org.asteriskjava.manager.event; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -/** - * - */ -public class T38FaxStatusEventTest -{ +class T38FaxStatusEventTest { @Test - public void testStripUnit() - { + void testStripUnit() { T38FaxStatusEvent event = new T38FaxStatusEvent(this); assertEquals("0.022", event.stripUnit("0.022 sec.")); } @Test - public void testParseProperties() - { + void testParseProperties() { T38FaxStatusEvent event = new T38FaxStatusEvent(this); event.setTotalLag("-9 ms"); event.setMaxLag("4 ms"); 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 de6e1a015..a36214a46 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ActionBuilderImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ActionBuilderImplTest.java @@ -16,36 +16,26 @@ */ package org.asteriskjava.manager.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 org.asteriskjava.AsteriskVersion; -import org.asteriskjava.manager.action.AbstractManagerAction; -import org.asteriskjava.manager.action.AgentsAction; -import org.asteriskjava.manager.action.OriginateAction; -import org.asteriskjava.manager.action.SipNotifyAction; -import org.asteriskjava.manager.action.UpdateConfigAction; -import org.asteriskjava.manager.action.UserEventAction; -import org.junit.Before; -import org.junit.Test; - -public class ActionBuilderImplTest -{ +import static org.junit.jupiter.api.Assertions.*; + +class ActionBuilderImplTest { private ActionBuilderImpl actionBuilder; - @Before - public void setUp() - { + @BeforeEach + void setUp() { this.actionBuilder = new ActionBuilderImpl(); } @Test - public void testBuildAction() - { + void testBuildAction() { MyAction myAction; String actual; @@ -56,16 +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"); } @Test - public void testBuildActionWithNullValue() - { + void testBuildActionWithNullValue() { MyAction myAction; String actual; @@ -74,15 +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"); } @Test - public void testBuildEventGeneratingAction() - { + void testBuildEventGeneratingAction() { AgentsAction action; String actual; @@ -90,14 +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"); } - + @Test - public void testBuildUpdateConfigAction() - { + void testBuildUpdateConfigAction() { UpdateConfigAction action; action = new UpdateConfigAction(); action.setSrcFilename("sourcefile.conf"); @@ -106,20 +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); } @Test - public void testBuildUserEventAction() - { + void testBuildUserEventAction() { UserEventAction action; action = new UserEventAction(); @@ -136,17 +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") @Test - public void testBuildActionWithVariablesForAsterisk10() - { + void testBuildActionWithVariablesForAsterisk10() { OriginateAction originateAction; String actual; @@ -155,14 +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") @Test - public void testBuildActionWithVariablesForAsterisk10WithNullValues() - { + void testBuildActionWithVariablesForAsterisk10WithNullValues() { OriginateAction originateAction; String actual; @@ -171,14 +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") @Test - public void testBuildActionWithVariablesForAsterisk12() - { + void testBuildActionWithVariablesForAsterisk12() { OriginateAction originateAction; String actual; @@ -188,14 +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") @Test - public void testBuildActionWithVariablesForAsterisk12WithNullValues() - { + void testBuildActionWithVariablesForAsterisk12WithNullValues() { OriginateAction originateAction; String actual; @@ -205,13 +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"); } @Test - public void testBuildActionWithVariableMapForAsterisk12() - { + void testBuildActionWithVariableMapForAsterisk12() { OriginateAction originateAction; Map map; String actual; @@ -227,13 +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"); } @Test - public void testBuildActionForSipNotifyAction() - { + void testBuildActionForSipNotifyAction() { SipNotifyAction action; String actual; @@ -244,105 +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"); } @Test - public void testBuildActionWithAnnotatedGetter() - { + 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"); } @Test - public void testDetermineSetterName() - { + void testDetermineSetterName() { assertEquals("setProperty1", ActionBuilderImpl.determineSetterName("getProperty1")); assertEquals("setProperty1", ActionBuilderImpl.determineSetterName("isProperty1")); } @Test - public void testBuildActionWithAnnotatedSetter() - { + 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"); } @Test - public void testDetermineFieldName() - { + void testDetermineFieldName() { assertEquals("property1", ActionBuilderImpl.determineFieldName("getProperty1")); assertEquals("property1", ActionBuilderImpl.determineFieldName("isProperty1")); assertEquals("property1", ActionBuilderImpl.determineFieldName("setProperty1")); } @Test - public void testBuildActionWithAnnotatedField() - { + 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 f476b5c4c..c68cd2e9c 100644 --- a/src/test/java/org/asteriskjava/manager/internal/AnnotatedAction.java +++ b/src/test/java/org/asteriskjava/manager/internal/AnnotatedAction.java @@ -19,8 +19,7 @@ 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 5a238802c..19782a6d3 100644 --- a/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/EventBuilderImplTest.java @@ -16,94 +16,66 @@ */ package org.asteriskjava.manager.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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; -import org.asteriskjava.manager.event.AbstractChannelEvent; -import org.asteriskjava.manager.event.AgentCalledEvent; -import org.asteriskjava.manager.event.CdrEvent; -import org.asteriskjava.manager.event.HangupEvent; -import org.asteriskjava.manager.event.LogChannelEvent; -import org.asteriskjava.manager.event.ManagerEvent; -import org.asteriskjava.manager.event.MeetMeLeaveEvent; -import org.asteriskjava.manager.event.MusicOnHoldEvent; -import org.asteriskjava.manager.event.NewCallerIdEvent; -import org.asteriskjava.manager.event.NewChannelEvent; -import org.asteriskjava.manager.event.NewExtenEvent; -import org.asteriskjava.manager.event.PeersEvent; -import org.asteriskjava.manager.event.ResponseEvent; -import org.asteriskjava.manager.event.RtpReceiverStatEvent; -import org.asteriskjava.manager.event.ShutdownEvent; -import org.asteriskjava.manager.event.StatusCompleteEvent; -import org.asteriskjava.manager.event.T38FaxStatusEvent; -import org.asteriskjava.manager.event.TransferEvent; -import org.junit.Before; -import org.junit.Test; - -public class EventBuilderImplTest -{ +import static org.junit.jupiter.api.Assertions.*; + +class EventBuilderImplTest { private EventBuilder eventBuilder; private Map properties; - @Before - public void setUp() - { + @BeforeEach + void setUp() { this.eventBuilder = new EventBuilderImpl(); this.properties = new HashMap(); } @Test - public void testRegisterEvent() - { + void testRegisterEvent() { eventBuilder.registerEventClass(NewChannelEvent.class); } @Test - public void testRegisterUserEventWithA() - { + 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"); } @Test - public void testRegisterUserEventWithBEvent() - { + 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"); } @Test - public void testRegisterUserEventWithUserEventC() - { + 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"); } @Test - public void testRegisterUserEventWithUserEventCAndAsterisk14() - { + void testRegisterUserEventWithUserEventCAndAsterisk14() { ManagerEvent event; eventBuilder.registerEventClass(UserEventC.class); @@ -111,44 +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"); } @Test - public void testRegisterUserEventWithUserEventDEvent() - { + 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"); + } + + @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 - public void testRegisterEventWithAbstractEvent() - { - try - { + 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 + * void testGetSetters() { Map setters; EventBuilderImpl eventBuilder * = getEventBuilder(); setters = * eventBuilder.getSetters(NewChannelEvent.class); assertTrue("Setter not * found", setters.containsKey("callerid")); } */ @Test - public void testBuildEventWithMixedCaseSetter() - { + void testBuildEventWithMixedCaseSetter() { String callerid = "1234"; NewChannelEvent event; @@ -157,14 +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"); } @Test - public void testBuildEventWithIntegerProperty() - { + void testBuildEventWithIntegerProperty() { String channel = "SIP/1234"; Integer priority = 1; NewExtenEvent event; @@ -175,14 +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"); } @Test - public void testBuildEventWithBooleanProperty() - { + void testBuildEventWithBooleanProperty() { ShutdownEvent event; eventBuilder.registerEventClass(ShutdownEvent.class); @@ -191,13 +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"); } @Test - public void testBuildEventWithBooleanPropertyOfValueYes() - { + void testBuildEventWithBooleanPropertyOfValueYes() { ShutdownEvent event; eventBuilder.registerEventClass(ShutdownEvent.class); @@ -206,13 +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"); } @Test - public void testBuildEventWithBooleanPropertyOfValueNo() - { + void testBuildEventWithBooleanPropertyOfValueNo() { ShutdownEvent event; eventBuilder.registerEventClass(ShutdownEvent.class); @@ -221,13 +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"); } @Test - public void testBuildEventWithUnregisteredEvent() - { + void testBuildEventWithUnregisteredEvent() { ManagerEvent event; properties.put("event", "Nonexisting"); @@ -237,8 +214,7 @@ public void testBuildEventWithUnregisteredEvent() } @Test - public void testBuildEventWithEmptyAttributes() - { + void testBuildEventWithEmptyAttributes() { ManagerEvent event; event = eventBuilder.buildEvent(this, properties); @@ -247,8 +223,7 @@ public void testBuildEventWithEmptyAttributes() } @Test - public void testBuildEventWithResponseEvent() - { + void testBuildEventWithResponseEvent() { ManagerEvent event; properties.put("event", "StatusComplete"); @@ -256,13 +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"); } @Test - public void testBuildEventWithSourceProperty() - { + void testBuildEventWithSourceProperty() { ManagerEvent event; properties.put("event", "Cdr"); @@ -270,12 +244,11 @@ 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 - public void testBuildEventWithClassProperty() - { + void testBuildEventWithClassProperty() { ManagerEvent event; properties.put("event", "MusicOnHold"); @@ -283,12 +256,11 @@ public void testBuildEventWithClassProperty() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("ClassName property not set correctly", "default", ((MusicOnHoldEvent) event).getClassName()); + assertEquals("default", ((MusicOnHoldEvent) event).getClassName(), "ClassName property not set correctly"); } @Test - public void testBuildEventWithSpecialCharacterProperty() - { + void testBuildEventWithSpecialCharacterProperty() { ManagerEvent event; properties.put("event", "Hangup"); @@ -296,12 +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"); } @Test - public void testBuildEventWithCidCallingPres() - { + void testBuildEventWithCidCallingPres() { ManagerEvent event; properties.put("event", "Newcallerid"); @@ -309,15 +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"); } @Test - public void testBuildEventWithCidCallingPresAndEmptyTxt() - { + void testBuildEventWithCidCallingPresAndEmptyTxt() { ManagerEvent event; properties.put("event", "Newcallerid"); @@ -325,15 +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)"); } @Test - public void testBuildEventWithCidCallingPresAndMissingTxt() - { + void testBuildEventWithCidCallingPresAndMissingTxt() { ManagerEvent event; properties.put("event", "Newcallerid"); @@ -341,15 +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)"); } @Test - public void testBuildEventWithInvalidCidCallingPres() - { + void testBuildEventWithInvalidCidCallingPres() { ManagerEvent event; properties.put("event", "Newcallerid"); @@ -357,15 +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)"); } @Test - public void testBuildEventWithReason() - { + void testBuildEventWithReason() { ManagerEvent event; properties.put("event", "LogChannel"); @@ -373,13 +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"); } @Test - public void testBuildEventWithTimestamp() - { + void testBuildEventWithTimestamp() { ManagerEvent event; properties.put("event", "NewChannel"); @@ -387,12 +345,11 @@ public void testBuildEventWithTimestamp() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Timestamp property not set correctly", 1159310429.569108D, event.getTimestamp(), 0.0001); + assertEquals(1159310429.569108D, event.getTimestamp(), 0.0001, "Timestamp property not set correctly"); } @Test - public void testBuildEventWithLong() - { + void testBuildEventWithLong() { ManagerEvent event; properties.put("event", "MeetmeLeave"); @@ -400,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"); } @Test - public void testBuildEventWithDouble() - { + void testBuildEventWithDouble() { ManagerEvent event; properties.put("event", "RTPReceiverStat"); @@ -413,12 +369,11 @@ public void testBuildEventWithDouble() event = eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Transit property not set correctly", 12.3456, ((RtpReceiverStatEvent) event).getTransit(), 0.0001); + assertEquals(12.3456, ((RtpReceiverStatEvent) event).getTransit(), 0.0001, "Transit property not set correctly"); } @Test - public void testBuildEventWithNullLiteral() - { + void testBuildEventWithNullLiteral() { CdrEvent event; properties.put("event", "Cdr"); @@ -426,13 +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"); } @Test - public void testBuildEventWithDashInPropertyName() - { + void testBuildEventWithDashInPropertyName() { TransferEvent event; properties.put("event", "Transfer"); @@ -440,13 +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"); } @Test - public void testBuildEventForRtpReceiverStatEventAJ162() - { + void testBuildEventForRtpReceiverStatEventAJ162() { RtpReceiverStatEvent event; properties.put("event", "RtpReceiverStat"); @@ -455,13 +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"); } @Test - public void testBuildEventForRtpReceiverStatEventAJ139() - { + void testBuildEventForRtpReceiverStatEventAJ139() { RtpReceiverStatEvent event; properties.put("event", "RtpReceiverStat"); @@ -469,13 +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"); } @Test - public void testBuildEventWithMapProperty() - { + void testBuildEventWithMapProperty() { AgentCalledEvent event; properties.put("event", "AgentCalled"); @@ -483,15 +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"); } @Test - public void testBuildEventWithMapPropertyAndOnlyOneEntry() - { + void testBuildEventWithMapPropertyAndOnlyOneEntry() { AgentCalledEvent event; properties.put("event", "AgentCalled"); @@ -499,14 +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"); } @Test - public void testBuildEventWithSpace() - { + void testBuildEventWithSpace() { T38FaxStatusEvent event; properties.put("event", "T38FaxStatus"); @@ -514,13 +463,12 @@ 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 - public void testBuildEventWithPeerEntryEventList() - { + void testBuildEventWithPeerEntryEventList() { PeersEvent event; properties.put("event", Arrays.asList("PeerEntry", "PeerEntry", "PeerEntry", "PeerlistComplete")); @@ -531,23 +479,19 @@ public void testBuildEventWithPeerEntryEventList() event = (PeersEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", PeersEvent.class, event.getClass()); - assertEquals("ActionId is invalid", "123", event.getActionId()); - assertEquals("Property events[objectname] is not set correctly", "a101", - event.getChildEvents().get(0).getObjectName()); - assertEquals("Property events[status] is not set correctly", "OK", event.getChildEvents().get(0).getStatus()); - assertEquals("Property events[objectname] is not set correctly", "a102", - event.getChildEvents().get(1).getObjectName()); - assertNull("UNKNOWN literal returns NULL status", event.getChildEvents().get(1).getStatus()); - assertEquals("Property events[objectname] is not set correctly", "a103", - event.getChildEvents().get(2).getObjectName()); - assertEquals("Property events[status] is not set correctly", "LAGGED", event.getChildEvents().get(2).getStatus()); - assertEquals("Invalid size of peers property", 3, event.getChildEvents().size()); - } - - @Test - public void testBuildEventWithOnePeerEntryEventList() - { + 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")); @@ -558,11 +502,10 @@ public void testBuildEventWithOnePeerEntryEventList() event = (PeersEvent) eventBuilder.buildEvent(this, properties); assertNotNull(event); - assertEquals("Returned event is of wrong type", PeersEvent.class, event.getClass()); - assertEquals("ActionId is invalid", "123", event.getActionId()); - assertEquals("Property events[objectname] is not set correctly", "a101", - event.getChildEvents().get(0).getObjectName()); - assertEquals("Property events[status] is not set correctly", "OK", event.getChildEvents().get(0).getStatus()); - assertEquals("Invalid size of peers property", 1, event.getChildEvents().size()); + 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 a7dbf7a60..2565925a9 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ManagerConnectionImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ManagerConnectionImplTest.java @@ -16,19 +16,6 @@ */ 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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - import org.asteriskjava.AsteriskVersion; import org.asteriskjava.manager.AuthenticationFailedException; import org.asteriskjava.manager.ManagerConnectionState; @@ -44,60 +31,60 @@ import org.asteriskjava.manager.event.NewChannelEvent; import org.asteriskjava.manager.response.ManagerResponse; import org.asteriskjava.util.SocketConnectionFacade; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class ManagerConnectionImplTest -{ +class ManagerConnectionImplTest { protected SocketConnectionFacade mockSocket; protected ManagerWriterMock mockWriter; protected ManagerReaderMock mockReader; protected MockedManagerConnectionImpl mc; - @Before - public void setUp() - { + @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); } @Test - public void testDefaultConstructor() - { - assertEquals("Invalid default hostname", "localhost", mc.getHostname()); - assertEquals("Invalid default port", 5038, mc.getPort()); + void testDefaultConstructor() { + assertEquals("localhost", mc.getHostname(), "Invalid default hostname"); + assertEquals(5038, mc.getPort(), "Invalid default port"); } @Test - public void testRegisterUserEventClass() - { + 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"); } @Test - public void testLogin() throws Exception - { + void testLogin() throws Exception { MockedManagerEventListener listener; long startTime; long endTime; @@ -105,8 +92,6 @@ public void testLogin() throws Exception listener = new MockedManagerEventListener(); - replay(mockSocket); - mc.setUsername("username"); mc.setPassword("password"); mc.addEventListener(listener); @@ -117,52 +102,46 @@ public void testLogin() throws Exception 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 // 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()); + 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("event handled must be a ConnectEvent", listener.eventsHandled.get(0) instanceof ConnectEvent); + assertTrue(listener.eventsHandled.get(0) instanceof ConnectEvent, "event handled must be a ConnectEvent"); - verify(mockSocket); - assertTrue("login() took longer than 2 second, probably a notify error (duration was " + duration + " is msec)", - duration <= 2000); + assertTrue(duration <= 2000, + "login() took longer than 2 second, probably a notify error (duration was " + duration + " is msec)"); } @Test - public void testLoginIncorrectKey() throws Exception - { + void testLoginIncorrectKey() throws Exception { mockSocket.close(); - replay(mockSocket); mockWriter.setExpectedUsername("username"); // md5 sum of 12345password @@ -171,160 +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 // 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()"); } @Test - public void testLoginIOExceptionOnConnect() throws Exception - { - replay(mockSocket); - + 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(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 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("unexpected call to setSocket()", 0, mockReader.setSocketCalls); - assertEquals("unexpected call to run()", 0, mockReader.runCalls); - assertEquals("unexpected call to die()", 0, mockReader.dieCalls); - - 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()"); } @Test - public void testLoginTimeoutOnConnect() throws Exception - { + 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()"); } @Test - public void testLoginTimeoutOnChallengeAction() throws Exception - { + 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()"); } @Test - public void testLogoffWhenConnected() throws Exception - { + void testLogoffWhenConnected() throws Exception { mockSocket.close(); - replay(mockSocket); // fake connect mc.connect(); @@ -332,64 +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"); } @Test - public void testLogoffWhenNotConnected() - { - replay(mockSocket); - - try - { + 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"); } @Test - public void testSendActionWithNullAction() throws Exception - { + void testSendActionWithNullAction() throws Exception { // fake connect mc.connect(); - try - { + try { mc.sendAction(null); fail("No IllgealArgumentException thrown"); - } - catch (IllegalArgumentException e) - { + } catch (IllegalArgumentException e) { } } @Test - public void testSendActionWhenNotConnected() throws Exception - { + void testSendActionWhenNotConnected() throws Exception { StatusAction statusAction; statusAction = new StatusAction(); - try - { + try { mc.sendAction(statusAction); fail("No IllegalStateException thrown"); - } - catch (IllegalStateException e) - { + } catch (IllegalStateException e) { } } @Test - public void testSendAction() throws Exception - { + void testSendAction() throws Exception { StatusAction statusAction; ManagerResponse response; @@ -401,16 +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"); } @Test - public void testSendActionTimeout() throws Exception - { + void testSendActionTimeout() throws Exception { StatusAction statusAction; statusAction = new StatusAction(); @@ -423,21 +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"); } @Test - public void testDispatchResponseUnexpectedResponse() - { + void testDispatchResponseUnexpectedResponse() { ManagerResponse response; response = new ManagerResponse(); @@ -446,12 +371,11 @@ public void testDispatchResponseUnexpectedResponse() response.setResponse("Success"); // expected result is ignoring the response and logging - mc.dispatchResponse(response); + mc.dispatchResponse(response, null); } @Test - public void testDispatchResponseMissingInternalActionId() - { + void testDispatchResponseMissingInternalActionId() { ManagerResponse response; response = new ManagerResponse(); @@ -459,12 +383,11 @@ public void testDispatchResponseMissingInternalActionId() response.setResponse("Success"); // expected result is ignoring the response and logging - mc.dispatchResponse(response); + mc.dispatchResponse(response, null); } @Test - public void testDispatchResponseNullActionId() - { + void testDispatchResponseNullActionId() { ManagerResponse response; response = new ManagerResponse(); @@ -472,22 +395,19 @@ public void testDispatchResponseNullActionId() response.setResponse("Success"); // expected result is ignoring the response and logging - mc.dispatchResponse(response); + mc.dispatchResponse(response, null); } @Test - public void testDispatchResponseNullResponse() - { + void testDispatchResponseNullResponse() { // expected result is ignoring and logging - mc.dispatchResponse(null); + mc.dispatchResponse(null, null); } @Test - public void testReconnect() throws Exception - { + void testReconnect() throws Exception { DisconnectEvent disconnectEvent; - replay(mockSocket); disconnectEvent = new DisconnectEvent(this); // fake successful login @@ -496,30 +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"); } @Test - public void testReconnectWithIOException() throws Exception - { + void testReconnectWithIOException() throws Exception { DisconnectEvent disconnectEvent; - replay(mockSocket); disconnectEvent = new DisconnectEvent(this); // fake successful login @@ -530,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("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(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("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"); } @Test - public void testReconnectWithTimeoutException() throws Exception - { + void testReconnectWithTimeoutException() throws Exception { DisconnectEvent disconnectEvent; mockSocket.close(); - replay(mockSocket); disconnectEvent = new DisconnectEvent(this); // fake successful login @@ -565,78 +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") @Test - public void testDispatchEventWithMultipleEventHandlers() - { + 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); } @Test - public void testIsShowVersionCommandAction() - { + void testIsShowVersionCommandAction() { assertTrue(mc.isShowVersionCommandAction(new CoreSettingsAction())); assertTrue(mc.isShowVersionCommandAction(new CommandAction("core 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; @@ -651,62 +550,52 @@ private class MockedManagerConnectionImpl extends ManagerConnectionImpl public int loginCalls = 0; public MockedManagerConnectionImpl(ManagerReader mockReader, ManagerWriter mockWriter, - SocketConnectionFacade mockSocket) - { + 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; @@ -714,12 +603,10 @@ protected SocketConnectionFacade createSocket() throws IOException @Override protected synchronized void doLogin(long timeout, String events) - throws IOException, AuthenticationFailedException, TimeoutException - { + throws IOException, AuthenticationFailedException, TimeoutException { loginCalls++; - if (throwTimeoutExceptionOnFirstLogin && loginCalls == 1) - { + if (throwTimeoutExceptionOnFirstLogin && loginCalls == 1) { disconnect(); throw new TimeoutException("Provoked timeout"); } @@ -727,8 +614,7 @@ protected synchronized void doLogin(long timeout, String 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 6dac7843a..22bbb9f23 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ManagerReaderImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ManagerReaderImplTest.java @@ -16,361 +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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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 org.asteriskjava.manager.event.AgentCalledEvent; -import org.asteriskjava.manager.event.DisconnectEvent; -import org.asteriskjava.manager.event.ManagerEvent; -import org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent; -import org.asteriskjava.manager.event.RtcpReceivedEvent; -import org.asteriskjava.manager.event.StatusCompleteEvent; -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.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -public class ManagerReaderImplTest -{ +class ManagerReaderImplTest { private Date now; private MockedDispatcher dispatcher; private SocketConnectionFacade socketConnectionFacade; private ManagerReader managerReader; - @Before - public 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); } - @After - public void tearDown() - { + @AfterEach + void tearDown() { DateUtil.overrideCurrentDate(null); } - @SuppressWarnings("cast") @Test - public void testRunWithoutSocket() - { - try - { + 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"); } } @Test - public void testRunReceivingProtocolIdentifier() throws Exception - { - expect(socketConnectionFacade.readLine()).andReturn("Asterisk Call Manager/1.0"); - expect(socketConnectionFacade.readLine()).andReturn(null); - - replay(socketConnectionFacade); + 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"); } @Test - public void testRunReceivingEvent() throws Exception - { - expect(socketConnectionFacade.readLine()).andReturn("Event: StatusComplete"); - expect(socketConnectionFacade.readLine()).andReturn(""); - expect(socketConnectionFacade.readLine()).andReturn(null); - - replay(socketConnectionFacade); + 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"); } @Test - 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); + 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(2, dispatcher.dispatchedEvents.size(), "not exactly two events dispatched"); - assertEquals("not exactly two events dispatched", 2, dispatcher.dispatchedEvents.size()); - - 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"); } @Test - 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); + 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()); - } - - @Test - 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()); } @Test - 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); + 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"); } @Test - public void testRunReceivingCommandResponse() throws Exception - { + 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"); } @Test - public void testRunCatchingIOException() throws Exception - { - expect(socketConnectionFacade.readLine()).andThrow(new IOException("Something happened to the network...")); - - replay(socketConnectionFacade); + 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 d3c8f0a0f..e4bc3332b 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ManagerReaderMock.java +++ b/src/test/java/org/asteriskjava/manager/internal/ManagerReaderMock.java @@ -16,61 +16,51 @@ */ 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; -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< ? extends ManagerEvent> 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< ? extends ManagerResponse> 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< ? extends ManagerEvent> eventClass) - { + 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 ba2289038..b988375b0 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ManagerWriterImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ManagerWriterImplTest.java @@ -16,54 +16,42 @@ */ package org.asteriskjava.manager.internal; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import org.asteriskjava.manager.action.StatusAction; import org.asteriskjava.util.SocketConnectionFacade; -import org.junit.Before; -import org.junit.Test; +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 -{ +class ManagerWriterImplTest { private ManagerWriter managerWriter; - @Before - public void setUp() - { + @BeforeEach + void setUp() { managerWriter = new ManagerWriterImpl(); } - @SuppressWarnings("cast") @Test - public void testSendActionWithoutSocket() throws Exception - { - try - { + 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"); } } @Test - public void testSendAction() throws Exception - { + 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 aedd4176a..86f785fee 100644 --- a/src/test/java/org/asteriskjava/manager/internal/MyUserEvent.java +++ b/src/test/java/org/asteriskjava/manager/internal/MyUserEvent.java @@ -16,51 +16,45 @@ */ package org.asteriskjava.manager.internal; -import java.util.Map; - import org.asteriskjava.manager.event.UserEvent; -public class MyUserEvent extends UserEvent -{ +import java.util.Map; + +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 31a0ec9f0..65cd4d8d1 100644 --- a/src/test/java/org/asteriskjava/manager/internal/ResponseBuilderImplTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/ResponseBuilderImplTest.java @@ -16,72 +16,61 @@ */ package org.asteriskjava.manager.internal; -import static org.junit.Assert.assertEquals; +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; -import org.asteriskjava.manager.response.ChallengeResponse; -import org.asteriskjava.manager.response.ExtensionStateResponse; -import org.asteriskjava.manager.response.MailboxCountResponse; -import org.asteriskjava.manager.response.MailboxStatusResponse; -import org.asteriskjava.manager.response.ManagerError; -import org.asteriskjava.manager.response.ManagerResponse; -import org.junit.Before; -import org.junit.Test; - -public class ResponseBuilderImplTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ResponseBuilderImplTest { private ResponseBuilderImpl responseBuilder; private Map attributes; - @Before - public void setUp() - { + @BeforeEach + void setUp() { this.responseBuilder = new ResponseBuilderImpl(); this.attributes = new HashMap(); } @Test - public void testBuildResponse() - { + 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"); } @Test - public void testBuildResponseWithoutResponseClass() - { + 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"); } @Test - public void testBuildError() - { + 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"); } @Test - public void testBuildErrorWithActionId() - { + void testBuildErrorWithActionId() { ManagerResponse response; attributes.put("response", "Error"); @@ -89,25 +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"); } @Test - public void testBuildChallengeResponse() - { + 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"); } @Test - public void testBuildMailboxStatusResponse() - { + void testBuildMailboxStatusResponse() { ManagerResponse response; attributes.put("response", "Success"); @@ -116,16 +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"); } @Test - public void testBuildMailboxStatusResponseWithNoWaiting() - { + void testBuildMailboxStatusResponseWithNoWaiting() { ManagerResponse response; attributes.put("response", "Success"); @@ -134,16 +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"); } @Test - public void testBuildMailboxCountResponse() - { + void testBuildMailboxCountResponse() { ManagerResponse response; attributes.put("response", "Success"); @@ -153,17 +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"); } @Test - public void testBuildExtensionStateResponse() - { + void testBuildExtensionStateResponse() { ManagerResponse response; attributes.put("response", "Success"); @@ -174,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 index da6261875..f31ea51c6 100644 --- a/src/test/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparatorTest.java +++ b/src/test/java/org/asteriskjava/manager/internal/backwardsCompatibility/bridge/BridgeEnterEventComparatorTest.java @@ -17,16 +17,15 @@ package org.asteriskjava.manager.internal.backwardsCompatibility.bridge; import org.asteriskjava.manager.event.BridgeEnterEvent; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class BridgeEnterEventComparatorTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BridgeEnterEventComparatorTest { private BridgeEnterEventComparator bridgeEnterEventComparator = new BridgeEnterEventComparator(); @Test - public void withoutPrefix_shouldId2BeGreater() - { + void withoutPrefix_shouldId2BeGreater() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590350.29"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.30"); @@ -35,12 +34,11 @@ public void withoutPrefix_shouldId2BeGreater() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(-1, compareResult); + assertEquals(-1, compareResult); } @Test - public void withoutPrefix_shouldId1BeGreater() - { + void withoutPrefix_shouldId1BeGreater() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590350.29"); @@ -49,12 +47,11 @@ public void withoutPrefix_shouldId1BeGreater() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(1, compareResult); + assertEquals(1, compareResult); } @Test - public void withoutPrefix_shouldId2BeGreaterForSameSerials() - { + void withoutPrefix_shouldId2BeGreaterForSameSerials() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590350.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.30"); @@ -63,12 +60,11 @@ public void withoutPrefix_shouldId2BeGreaterForSameSerials() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(-1, compareResult); + assertEquals(-1, compareResult); } @Test - public void withoutPrefix_shouldId1BeGreaterForSameSerials() - { + void withoutPrefix_shouldId1BeGreaterForSameSerials() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590350.30"); @@ -77,12 +73,11 @@ public void withoutPrefix_shouldId1BeGreaterForSameSerials() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(1, compareResult); + assertEquals(1, compareResult); } @Test - public void withoutPrefix_shouldId2BeGreaterForSameEpoch() - { + void withoutPrefix_shouldId2BeGreaterForSameEpoch() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.29"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.30"); @@ -91,12 +86,11 @@ public void withoutPrefix_shouldId2BeGreaterForSameEpoch() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(-1, compareResult); + assertEquals(-1, compareResult); } @Test - public void withoutPrefix_shouldId1BeGreaterForSameEpoch() - { + void withoutPrefix_shouldId1BeGreaterForSameEpoch() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.29"); @@ -105,12 +99,11 @@ public void withoutPrefix_shouldId1BeGreaterForSameEpoch() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(1, compareResult); + assertEquals(1, compareResult); } @Test - public void withoutPrefix_shouldIdsBeEqual() - { + void withoutPrefix_shouldIdsBeEqual() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("1515590353.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("1515590353.30"); @@ -119,12 +112,11 @@ public void withoutPrefix_shouldIdsBeEqual() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(0, compareResult); + assertEquals(0, compareResult); } @Test - public void withPrefix_shouldId2BeGreater() - { + void withPrefix_shouldId2BeGreater() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590350.29"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590353.30"); @@ -133,12 +125,11 @@ public void withPrefix_shouldId2BeGreater() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(-1, compareResult); + assertEquals(-1, compareResult); } @Test - public void withPrefix_shouldId1BeGreater() - { + void withPrefix_shouldId1BeGreater() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590353.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590350.29"); @@ -147,12 +138,11 @@ public void withPrefix_shouldId1BeGreater() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(1, compareResult); + assertEquals(1, compareResult); } @Test - public void withPrefix_shouldId2BeGreaterForSameSerials() - { + void withPrefix_shouldId2BeGreaterForSameSerials() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590350.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590353.30"); @@ -161,12 +151,11 @@ public void withPrefix_shouldId2BeGreaterForSameSerials() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(-1, compareResult); + assertEquals(-1, compareResult); } @Test - public void withPrefix_shouldId1BeGreaterForSameSerials() - { + void withPrefix_shouldId1BeGreaterForSameSerials() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590353.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590350.30"); @@ -175,12 +164,11 @@ public void withPrefix_shouldId1BeGreaterForSameSerials() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(1, compareResult); + assertEquals(1, compareResult); } @Test - public void withPrefix_shouldId2BeGreaterForSameEpoch() - { + void withPrefix_shouldId2BeGreaterForSameEpoch() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590350.29"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590350.30"); @@ -189,12 +177,11 @@ public void withPrefix_shouldId2BeGreaterForSameEpoch() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(-1, compareResult); + assertEquals(-1, compareResult); } @Test - public void withPrefix_shouldId1BeGreaterForSameEpoch() - { + void withPrefix_shouldId1BeGreaterForSameEpoch() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590350.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590350.29"); @@ -203,12 +190,11 @@ public void withPrefix_shouldId1BeGreaterForSameEpoch() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(1, compareResult); + assertEquals(1, compareResult); } @Test - public void withPrefix_shouldIdsBeEqual() - { + void withPrefix_shouldIdsBeEqual() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590353.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590353.30"); @@ -217,12 +203,11 @@ public void withPrefix_shouldIdsBeEqual() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(0, compareResult); + assertEquals(0, compareResult); } @Test - public void shouldBothIdsDoesNotMatchPattern() - { + void shouldBothIdsDoesNotMatchPattern() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_id_1"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_id_2"); @@ -231,12 +216,11 @@ public void shouldBothIdsDoesNotMatchPattern() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(0, compareResult); + assertEquals(0, compareResult); } @Test - public void shouldId1DoesNotMatchPattern() - { + void shouldId1DoesNotMatchPattern() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_id_1"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_prefix-1515590353.30"); @@ -245,11 +229,11 @@ public void shouldId1DoesNotMatchPattern() int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(-1, compareResult); + assertEquals(-1, compareResult); } @Test - public void shouldId2DoesNotMatchPattern() { + void shouldId2DoesNotMatchPattern() { // given BridgeEnterEvent bridgeEnterEvent1 = createBridgeEnterEvent("some_prefix-1515590353.30"); BridgeEnterEvent bridgeEnterEvent2 = createBridgeEnterEvent("some_id_2"); @@ -258,13 +242,12 @@ public void shouldId2DoesNotMatchPattern() { int compareResult = bridgeEnterEventComparator.compare(bridgeEnterEvent1, bridgeEnterEvent2); // then - Assert.assertEquals(1, compareResult); + assertEquals(1, compareResult); } - private static BridgeEnterEvent createBridgeEnterEvent(String uniqueId) - { + private static BridgeEnterEvent createBridgeEnterEvent(String uniqueId) { BridgeEnterEvent bridgeEnterEvent = new BridgeEnterEvent(new Object()); bridgeEnterEvent.setUniqueId(uniqueId); return bridgeEnterEvent; } -} \ No newline at end of file +} diff --git a/src/test/java/org/asteriskjava/manager/response/CoreStatusResponseTest.java b/src/test/java/org/asteriskjava/manager/response/CoreStatusResponseTest.java index 16529b8c5..763268942 100644 --- a/src/test/java/org/asteriskjava/manager/response/CoreStatusResponseTest.java +++ b/src/test/java/org/asteriskjava/manager/response/CoreStatusResponseTest.java @@ -1,39 +1,33 @@ package org.asteriskjava.manager.response; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.TimeZone; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; -public class CoreStatusResponseTest -{ +class CoreStatusResponseTest { private TimeZone tz = TimeZone.getTimeZone("Europe/Berlin"); private CoreStatusResponse response; private TimeZone defaultTimeZone; - @Before - public void setUp() - { + @BeforeEach + void setUp() { this.response = new CoreStatusResponse(); defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(tz); } - @After - public void tearDown() - { + @AfterEach + void tearDown() { TimeZone.setDefault(defaultTimeZone); } @Test - public void testGetCoreStartupTimeAsDate() - { - assertNotNull("TimeZone not found", tz); + void testGetCoreStartupTimeAsDate() { + assertNotNull(tz, "TimeZone not found"); response.setCoreStartupDate("2009-05-27"); response.setCoreStartupTime("02:49:15"); @@ -41,9 +35,8 @@ public void testGetCoreStartupTimeAsDate() } @Test - public void testGetCoreStartupTimeAsDateIfDateIsNull() - { - assertNotNull("TimeZone not found", tz); + 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 9002a77b0..d886a45f3 100644 --- a/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java +++ b/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java @@ -1,47 +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 static org.junit.Assert.assertEquals; +import org.asteriskjava.manager.util.EventAttributesHelper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; -public class SipShowPeerResponseTest -{ +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SipShowPeerResponseTest { private SipShowPeerResponse response; - @Before - public void setUp() - { + @BeforeEach + void setUp() { response = new SipShowPeerResponse(); } @Test - public void testSetQualifyFreq() - { + 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"); } @Test - public void testSetQualifyFreqWithWorkaround() - { + void testSetQualifyFreqWithWorkaround() { response.setQualifyFreq(": 6000 ms\n"); - assertEquals("Incorrect qualifyFreq", 6000, (int) response.getQualifyFreq()); + assertEquals(6000, (int) response.getQualifyFreq(), "Incorrect qualifyFreq"); } @Test - public void testSetQualifyFreqWithWorkaroundAndChanVariable() - { + 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 - public void testSetMohsuggest() - { + void testSetMohsuggest() { response.setMohsuggest("default"); - assertEquals("Incorrect mohsuggest", "default",response.getMohsuggest()); + assertEquals("default", response.getMohsuggest(), "Incorrect mohsuggest"); } - - + + } diff --git a/src/test/java/org/asteriskjava/pbx/agi/RateLimiterTest.java b/src/test/java/org/asteriskjava/pbx/agi/RateLimiterTest.java deleted file mode 100644 index bbd63098c..000000000 --- a/src/test/java/org/asteriskjava/pbx/agi/RateLimiterTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.asteriskjava.pbx.agi; - -import static org.junit.Assert.assertTrue; - -import org.asteriskjava.pbx.agi.RateLimiter; -import org.junit.Test; - -public class RateLimiterTest -{ - - @Test - public void test() throws InterruptedException - { - long now = System.currentTimeMillis(); - RateLimiter limiter = new RateLimiter(3); - for (int i = 0; i < 15; i++) - { - limiter.acquire(); - - System.out.println(System.currentTimeMillis()); - Thread.sleep(100); - } - - // this should have taken around 5 seconds - assertTrue(System.currentTimeMillis() - now > 4000L); - } - -} diff --git a/src/test/java/org/asteriskjava/pbx/internal/core/ListenerManagerTest.java b/src/test/java/org/asteriskjava/pbx/internal/core/ListenerManagerTest.java index 658077c59..33d55902a 100644 --- a/src/test/java/org/asteriskjava/pbx/internal/core/ListenerManagerTest.java +++ b/src/test/java/org/asteriskjava/pbx/internal/core/ListenerManagerTest.java @@ -1,39 +1,30 @@ package org.asteriskjava.pbx.internal.core; -import static org.junit.Assert.assertTrue; - -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - import org.asteriskjava.pbx.ListenerPriority; import org.asteriskjava.pbx.asterisk.wrap.events.ManagerEvent; import org.asteriskjava.pbx.asterisk.wrap.events.VarSetEvent; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import java.util.*; -public class ListenerManagerTest -{ +import static org.junit.jupiter.api.Assertions.assertTrue; +class ListenerManagerTest { volatile boolean managereventRecevied = false; @Test - public void listenerTest() throws InterruptedException - { + void listenerTest() throws InterruptedException { List> listeners = new LinkedList<>(); ListenerManager queue = new ListenerManager(); - for (int i = 0; i < 1000; i++) - { + for (int i = 0; i < 1000; i++) { FilteredManagerListener listener = getListener(); listeners.add(listener); queue.addListener(listener); } Collections.shuffle(listeners); - for (FilteredManagerListener listener : listeners) - { + for (FilteredManagerListener listener : listeners) { assertTrue(queue.removeListener(listener)); } @@ -41,34 +32,28 @@ public void listenerTest() throws InterruptedException } - private FilteredManagerListener getListener() - { - return new FilteredManagerListener() - { + private FilteredManagerListener getListener() { + return new FilteredManagerListener() { @Override - public Set> requiredEvents() - { - Set> events = new HashSet<>(); + public Set> requiredEvents() { + Set> events = new HashSet<>(); events.add(VarSetEvent.class); return events; } @Override - public void onManagerEvent(ManagerEvent event) - { + public void onManagerEvent(ManagerEvent event) { managereventRecevied = true; } @Override - public ListenerPriority getPriority() - { + public ListenerPriority getPriority() { return ListenerPriority.NORMAL; } @Override - public String getName() - { + 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 569a748f0..86f1bf075 100644 --- a/src/test/java/org/asteriskjava/util/AstUtilTest.java +++ b/src/test/java/org/asteriskjava/util/AstUtilTest.java @@ -1,27 +1,22 @@ package org.asteriskjava.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; -public class AstUtilTest -{ +class AstUtilTest { @Test - 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)); + 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"); } @Test - public void testParseCallerIdName() - { + 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]); @@ -42,8 +37,7 @@ public void testParseCallerIdName() } @Test - public void testParseCallerIdNumber() - { + 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]); @@ -57,30 +51,26 @@ public void testParseCallerIdNumber() } @Test - public void testAJ120() - { + void testAJ120() { String s = "\"3496853210\" <3496853210>"; assertEquals("3496853210", AstUtil.parseCallerId(s)[0]); assertEquals("3496853210", AstUtil.parseCallerId(s)[1]); } @Test - 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("")); + 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 - public void testIsNullForIpAddressInPeerEntryEvent() - { - assertTrue("\"-none-\" must be considered null", AstUtil.isNull("-none-")); + void testIsNullForIpAddressInPeerEntryEvent() { + assertTrue(AstUtil.isNull("-none-"), "\"-none-\" must be considered null"); } @Test - public void testIsEqual() - { + void testIsEqual() { assertTrue(AstUtil.isEqual(null, null)); assertTrue(AstUtil.isEqual("", "")); assertFalse(AstUtil.isEqual(null, "")); diff --git a/src/test/java/org/asteriskjava/util/DateUtilTest.java b/src/test/java/org/asteriskjava/util/DateUtilTest.java index 081adf121..38eb8650f 100644 --- a/src/test/java/org/asteriskjava/util/DateUtilTest.java +++ b/src/test/java/org/asteriskjava/util/DateUtilTest.java @@ -1,43 +1,38 @@ package org.asteriskjava.util; -import static org.junit.Assert.assertEquals; +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 org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class DateUtilTest -{ +class DateUtilTest { TimeZone defaultTimeZone; final String dateString = "2006-05-19 11:54:48"; - @Before - public void setUp() - { + @BeforeEach + void setUp() { defaultTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } - @After - public void tearDown() - { + @AfterEach + void tearDown() { TimeZone.setDefault(defaultTimeZone); } @Test - public void testGetStartTimeAsDate() - { + void testGetStartTimeAsDate() { final Date result = DateUtil.parseDateTime(dateString); assertEquals(1148039688000L, result.getTime()); assertEquals("Fri May 19 11:54:48 GMT 2006", result.toString()); } @Test - public void testGetStartTimeAsDateWithTimeZone() - { + 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 index 664c3df56..1c218228d 100644 --- a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerDeterministicTest.java +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerDeterministicTest.java @@ -1,36 +1,32 @@ package org.asteriskjava.util.internal.streamreader; -import static org.junit.Assert.assertTrue; +import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; -import java.io.File; 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 org.asteriskjava.util.internal.SocketConnectionFacadeImpl; -import org.junit.Test; - -public class FastScannerDeterministicTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +class FastScannerDeterministicTest { @Test - public void testCrNlScanner() throws Exception - { + void testCrNlScanner() throws Exception { testScanner(10000, SocketConnectionFacadeImpl.NL_PATTERN); } @Test - public void testNlScanner() throws Exception - { + void testNlScanner() throws Exception { testScanner(10000, SocketConnectionFacadeImpl.CRNL_PATTERN); } - private void testScanner(int testLines, Pattern pattern) throws Exception - { + private void testScanner(int testLines, Pattern pattern) throws Exception { final byte[] bytes = buildTestData(testLines, pattern).getBytes(); @@ -39,57 +35,46 @@ private void testScanner(int testLines, Pattern pattern) throws Exception InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); // factory will return the correct reader for the pattern - try (FastScanner scanner = FastScannerFactory.getReader(reader, 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) - { + while ((t = scanner.next()) != null) { // System.out.println("L: " + t + " " + t.length()); ctr++; } - assertTrue("Counter expected : " + (testLines) + " got " + ctr, (testLines) == ctr); + assertEquals((testLines), ctr, "Counter expected : " + (testLines) + " got " + ctr); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { } System.out.println("Done\n"); } @Test - public void testBR2Accuraccy3() throws Exception - { - - final byte[] bytes = Files.readAllBytes(new File("NlStreamReaderFast273316816601633219txt").toPath()); + 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);) - { + try (FastScannerNl scanner = new FastScannerNl(reader);) { String t; - while ((t = scanner.next()) != null) - { + while ((t = scanner.next()) != null) { System.out.println("L: " + t + " " + t.length()); } - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { } } - String buildTestData(int lines, Pattern terminator) - { + String buildTestData(int lines, Pattern terminator) { StringBuilder builder = new StringBuilder(lines * 30); int ctr = 0; - while (ctr < lines) - { + while (ctr < lines) { ctr++; builder.append("Hallo hello: one line with text! " + ctr + terminator.pattern()); } diff --git a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerRandomTest.java b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerRandomTest.java index 6ef155c8e..328414419 100644 --- a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerRandomTest.java +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerRandomTest.java @@ -1,6 +1,8 @@ package org.asteriskjava.util.internal.streamreader; -import static org.junit.Assert.fail; +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; @@ -13,55 +15,39 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; -import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; -import org.junit.Test; - -import ch.qos.logback.core.encoder.ByteArrayUtil; +import static org.junit.jupiter.api.Assertions.fail; -public class FastScannerRandomTest -{ +class FastScannerRandomTest { @Test - public void compareOutputOfNlFastScannerToScanner() throws Exception - { + void compareOutputOfNlFastScannerToScanner() throws Exception { setupTest(SocketConnectionFacadeImpl.NL_PATTERN, "NL"); - } @Test - public void compareOutputOfCrNlFastScannerToScanner() throws Exception - { + void compareOutputOfCrNlFastScannerToScanner() throws Exception { setupTest(SocketConnectionFacadeImpl.CRNL_PATTERN, "CR NL"); - } - void setupTest(final Pattern pattern, String caption) throws InterruptedException - { + void setupTest(final Pattern pattern, String caption) { final AtomicInteger ctr = new AtomicInteger(); int tests = 50; - for (int i = 0; i < tests; i++) - { + for (int i = 0; i < tests; i++) { - try - { + try { String testData = generateTestData(1_000_000); compare(testData, pattern); System.out.println(caption + " Completed " + (ctr.incrementAndGet()) * 1 + "MB"); - } - catch (Exception e) - { + } catch (Exception e) { e.printStackTrace(); fail(); } - } - } - boolean compare(String testData, Pattern pattern) throws IOException - { + void compare(String testData, Pattern pattern) throws IOException { InputStream inputStream1 = new ByteArrayInputStream(testData.getBytes()); InputStreamReader reader1 = new InputStreamReader(inputStream1, StandardCharsets.UTF_8); @@ -79,43 +65,33 @@ boolean compare(String testData, Pattern pattern) throws IOException scanner.useDelimiter(pattern); - try - { - while ((scannerResult = scanner.next()) != null) - { + try { + while ((scannerResult = scanner.next()) != null) { ctr++; fastResult = fast.next(); - if (!fastResult.equals(scannerResult)) - { + if (!fastResult.equals(scannerResult)) { - System.out.println("Expected " + ByteArrayUtil.toHexString(scannerResult.getBytes())); - System.out.println("Got " + ByteArrayUtil.toHexString(fastResult.getBytes())); + 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) - { + } 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 - { + } finally { scanner.close(); fast.close(); } - return false; } - public static String generateTestData(int byteSize) - { + public static String generateTestData(int byteSize) { Random rand = new Random(); String bodyData = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(),.<>[] {};':\""; bodyData += bodyData.toUpperCase(); @@ -123,21 +99,16 @@ public static String generateTestData(int byteSize) 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) - { + 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 - { + } 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 index 598ca064b..d58fd7ba6 100644 --- a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTest.java +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTest.java @@ -1,5 +1,8 @@ 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; @@ -8,18 +11,12 @@ import java.util.Scanner; import java.util.regex.Pattern; -import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; -import org.junit.Test; - -public class FastScannerSpeedTest -{ +class FastScannerSpeedTest { @Test - public void testScannerSpeed() throws Exception - { + void testScannerSpeed() throws Exception { final byte[] bytes = FastScannerRandomTest.generateTestData(10_000_000).getBytes(); - for (int i = 10; i-- > 0;) - { + for (int i = 10; i-- > 0; ) { System.out.print("Scanner " + i + ":\t"); InputStream inputStream = new ByteArrayInputStream(bytes); @@ -28,22 +25,18 @@ public void testScannerSpeed() throws Exception long start = System.currentTimeMillis(); int ctr = 0; - try (Scanner scanner = new Scanner(reader);) - { + try (Scanner scanner = new Scanner(reader);) { scanner.useDelimiter(Pattern.compile("\r\n")); @SuppressWarnings("unused") String t; - while ((t = scanner.next()) != null) - { + while ((t = scanner.next()) != null) { // System.out.println(t); ctr++; } System.out.print(ctr + "\t"); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { System.out.print(ctr + "\t"); } System.out.println((System.currentTimeMillis() - start) + " ms"); @@ -51,15 +44,13 @@ public void testScannerSpeed() throws Exception } @Test - public void test1() throws Exception - { + void test1() throws Exception { System.out.println("\nTesting fast CrNlStream"); fastScannerSpeedTest(SocketConnectionFacadeImpl.CRNL_PATTERN); } @Test - public void test2() throws Exception - { + 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 @@ -68,12 +59,10 @@ public void test2() throws Exception fastScannerSpeedTest(SocketConnectionFacadeImpl.NL_PATTERN); } - private void fastScannerSpeedTest(Pattern pattern) throws Exception - { + private void fastScannerSpeedTest(Pattern pattern) throws Exception { final byte[] bytes = FastScannerRandomTest.generateTestData(10_000_000).getBytes(); - for (int i = 10; i-- > 0;) - { + for (int i = 10; i-- > 0; ) { System.out.print("Fast " + i + ":\t"); InputStream inputStream = new ByteArrayInputStream(bytes); @@ -82,21 +71,17 @@ private void fastScannerSpeedTest(Pattern pattern) throws Exception FastScanner scanner = FastScannerFactory.getReader(reader, pattern); long start = System.currentTimeMillis(); - try - { + try { int ctr = 0; @SuppressWarnings("unused") String t; - while ((t = scanner.next()) != null) - { + while ((t = scanner.next()) != null) { // System.out.println(t); ctr++; } System.out.print(ctr + "\t"); - } - catch (NoSuchElementException e) - { + } 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 index 125493749..fe5179e46 100644 --- a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTestOnSocket.java +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerSpeedTestOnSocket.java @@ -1,5 +1,8 @@ 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; @@ -10,19 +13,11 @@ import java.util.Scanner; import java.util.regex.Pattern; -import org.asteriskjava.util.internal.SocketConnectionFacadeImpl; -import org.junit.Test; - -public class FastScannerSpeedTestOnSocket -{ - +class FastScannerSpeedTestOnSocket { @Test - public void testScannerSpeed() throws Exception - { - try - { - for (int i = 10; i-- > 0;) - { + void testScannerSpeed() throws Exception { + try { + for (int i = 10; i-- > 0; ) { Socket echoSocket = new Socket("127.0.0.1", FastScannerTestSocketSource.portNumber); @@ -31,36 +26,29 @@ public void testScannerSpeed() throws Exception long start = System.currentTimeMillis(); int ctr = 0; - try (Scanner scanner = new Scanner(reader);) - { + try (Scanner scanner = new Scanner(reader);) { scanner.useDelimiter(Pattern.compile("\r\n")); @SuppressWarnings("unused") String t; - while ((t = scanner.next()) != null) - { + while ((t = scanner.next()) != null) { // System.out.println(t); ctr++; } System.out.print(ctr + "\t"); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { System.out.print(ctr + "\t"); } System.out.println((System.currentTimeMillis() - start) + " ms"); } - } - catch (Exception e) - { + } 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 - { + private InputStreamReader getReader(Socket echoSocket) throws UnknownHostException, IOException, InterruptedException { InputStream inputStream = echoSocket.getInputStream(); @@ -69,15 +57,13 @@ private InputStreamReader getReader(Socket echoSocket) throws UnknownHostExcepti } @Test - public void test1() throws Exception - { + void test1() throws Exception { System.out.println("\nTesting fast CrNlStream"); fastScannerSpeedTest(SocketConnectionFacadeImpl.CRNL_PATTERN); } @Test - public void test2() throws Exception - { + 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 @@ -86,12 +72,9 @@ public void test2() throws Exception fastScannerSpeedTest(SocketConnectionFacadeImpl.NL_PATTERN); } - private void fastScannerSpeedTest(Pattern pattern) throws Exception - { - try - { - for (int i = 10; i-- > 0;) - { + 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); @@ -99,27 +82,21 @@ private void fastScannerSpeedTest(Pattern pattern) throws Exception FastScanner scanner = FastScannerFactory.getReader(reader, pattern); long start = System.currentTimeMillis(); - try - { + try { int ctr = 0; @SuppressWarnings("unused") String t; - while ((t = scanner.next()) != null) - { + while ((t = scanner.next()) != null) { // System.out.println(t); ctr++; } System.out.print(ctr + "\t"); - } - catch (NoSuchElementException e) - { + } catch (NoSuchElementException e) { } System.out.println((System.currentTimeMillis() - start) + " ms"); } - } - catch (Exception e) - { + } 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 index f14a9e055..fbd18cdc5 100644 --- a/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerTestSocketSource.java +++ b/src/test/java/org/asteriskjava/util/internal/streamreader/FastScannerTestSocketSource.java @@ -4,29 +4,23 @@ import java.net.ServerSocket; import java.net.Socket; -public class FastScannerTestSocketSource -{ - +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 - { + public static void main(String[] args) throws IOException { - while (true) - { + while (true) { listen(); } } - static void listen() throws IOException - { + static void listen() throws IOException { System.out.println("Waiting for connect on " + portNumber); - try (ServerSocket serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept();) - { + try (ServerSocket serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept();) { clientSocket.getOutputStream().write(bytes); } } diff --git a/NlStreamReaderFast273316816601633219txt b/src/test/resources/NlStreamReaderFast273316816601633219.txt similarity index 100% rename from NlStreamReaderFast273316816601633219txt rename to src/test/resources/NlStreamReaderFast273316816601633219.txt diff --git a/triggerRelease.dart b/triggerRelease.dart deleted file mode 100755 index 831ff1096..000000000 --- a/triggerRelease.dart +++ /dev/null @@ -1,62 +0,0 @@ -#! /usr/bin/env dshell -import 'dart:io'; - -import 'package:dshell/dshell.dart'; - -/// comment - -void main() { - int major; - int minor; - int rev = 0; - var dir = dirname(Settings().scriptPath); - print(dir); - read(join(dir, "pom.xml")).forEach((line) { - if (line.contains("")) { - line = line.replaceFirst("-SNAPSHOT", ""); - var parts = line.split("."); - if (parts.length != 3) { - exit(1); - } - major = int.parse(parts[0].split(">")[1]); - minor = int.parse(parts[1]); - rev = int.parse(parts[2].split("<")[0]); - } - }); - - var postFix = ""; - if (confirm(prompt: "Is this a SNAPSHOT release (y/n)?")) { - postFix = "-SNAPSHOT"; - rev++; - } else { - rev = 0; - minor++; - } - - String version = "$major.$minor.$rev$postFix"; - - replace(join(dir, "pom.xml"), version); - - 'git pull'.run; - 'git add .'.run; - 'git commit -m "for version $version"'.run; - 'git tag -a $version -m "$version"'.run; - 'git push origin'.run; - 'git push origin tag $version'.run; -} - -void replace(String path, String version) { - var tmp = '$path.tmp'; - if (exists(tmp)) { - delete(tmp); - } - read(path).forEach((line) { - if (line.contains("")) { - line = " $version"; - } - tmp.append(line); - }); - move(path, '$path.bak'); - move(tmp, path); - delete('$path.bak'); -}
    "); writer.append(uniqueId.substring(0, uniqueId.lastIndexOf('.') + 1)); writer.append(""); @@ -142,8 +115,7 @@ public void write() writer.append("
    ").append(text).append("