diff --git a/.classpath b/.classpath deleted file mode 100644 index f42fb64..0000000 --- a/.classpath +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/.gitignore b/.gitignore index 4dc0091..7880b16 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ /target /bin +/.settings/ +/.classpath +/.project diff --git a/.project b/.project deleted file mode 100644 index 34c2c90..0000000 --- a/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - tropo-webapi-java - WebApi Java implementation for the Tropo Cloud platform. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.maven.ide.eclipse.maven2Nature - - diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index fdd9648..0000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,6 +0,0 @@ -#Sat Feb 05 08:41:16 CET 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.5 diff --git a/README.md b/README.md index f1f183e..3bd2793 100644 --- a/README.md +++ b/README.md @@ -6,14 +6,14 @@ Java library to interact with [Tropo's Webapi](https://www.tropo.com/docs/webapi Overview -------- -This is a very lightweight library that will help you to create applications that interact with Tropo from your Java based server. This library offers a type-safe object model that helps you to create requests to Tropo without having to deal with JSON at all. This way, you can minimize the errors that may happen due to invalid JSON being sent or parsed. +This is a very lightweight library that will help you to create applications that interact with Tropo from your Java based server. This library offers a type-safe object model that helps you to create requests to Tropo without having to deal with JSON at all. This way, you can minimize the errors that may happen due to invalid JSON being sent or parsed. -Additionally, this library implements the session method from Tropo [Rest API](https://www.tropo.com/docs/rest/rest_api.htm) which means it can be used from Java web or stand-alone applications to execute remote scripts. For example you can integrate this library with a Java Swing application to do simple but powerful tasks like sending SMS, sending voice calls, transfering calls, etc. +Additionally, this library implements the session method from Tropo [Rest API](https://www.tropo.com/docs/rest/rest_api.htm) which means it can be used from Java web or stand-alone applications to execute remote scripts. For example you can integrate this library with a Java Swing application to do simple but powerful tasks like sending SMS, sending voice calls, transfering calls, etc. Requirements ------------ -Current version is 0.3. +Current version is 15.13.0. License ------------ @@ -25,13 +25,12 @@ Requirements You can install this library in any Java application or application server. The library depends primarily on Json-lib and Commons Httpclient. These libraries also depend on other artifacts. The following listing shows all the libraries that need to be present in an application that uses Tropo's Java Webapi: - * commons-beanutils-1.8.1.jar - * commons-collections-3.2.1.jar - * commons-lang-2.5.jar - * commons-logging-1.1.1.jar - * commons-httpclient-3.1.jar - * json-lib-2.4-jdk15.jar - * ezmorph-1.0.6.jar + * gson-2.4.jar + * httpclient-4.5.2.jar + * httpcore-4.4.4.jar + * commons-logging-1.2.jar + * common-codec-1.9.jar + All libraries have been included in the [dist/dependencies](https://github.com/tropo/tropo-webapi-java/tree/master/dist/dependencies) folder. @@ -44,24 +43,10 @@ If you want to use the Maven artifact from your own projects you can add the fol com.voxeo.tropo tropo-webapi-java - 0.3 + 15.13.0 ``` -You will have also to link to your public maven Repository: - -```xml - - - voxeo-public - Uncle Voxeo's Public Maven Repo - http://maven.voxeo.net/nexus/content/groups/public - - -``` - -You can also check the build status of the project at any time from our public [CI server](http://ci.voxeolabs.net/jenkins/job/tropo-java-webapi/). - Building it from Source ------------------------ @@ -78,7 +63,7 @@ Say Hello and render text to the HTTP Servlet response object: HttpServletResponse response = ... Tropo tropo = new Tropo(); - tropo.say("1234"); + tropo.say("1234"); tropo.render(response) Launch an application (can also be done from stand-alone apps) : @@ -99,16 +84,16 @@ With Tropo's Java Webapi you can build Tropo apps with type-safety and tradition // Example 1 Tropo tropo = new Tropo(); - RecordAction record = tropo.record("foo","http://sendme.com/tropo",true,true,"#"); + RecordAction record = tropo.record("foo","http://sendme.com/tropo",true); record.transcription(ID("bling"), URL("mailto:jose@voxeo.com"), EMAIL_FORMAT("encoded")); record.say(VALUE("Please say your account number")); record.choices(VALUE("[5 DIGITS]")); // Example 2 Tropo tropo = new Tropo(); - tropo.on(EVENT("error"), NEXT("/error.json")); // For fatal programming errors. Log some details so we can fix it - tropo.on(EVENT("hangup"), NEXT("/hangup.json")); // When a user hangs or call is done. We will want to log some details. - tropo.on(EVENT("continue"), NEXT("/next.json")); + tropo.on(EVENT("error"), NEXT("/error.json"), SAY_OF_ON(new com.voxeo.tropo.actions.OnAction.Say("error"))); // For fatal programming errors. Log some details so we can fix it + tropo.on(EVENT("hangup"), NEXT("/hangup.json"), SAY_OF_ON(new com.voxeo.tropo.actions.OnAction.Say("hangup"))); // When a user hangs or call is done. We will want to log some details. + tropo.on(EVENT("continue"), NEXT("/next.json"), SAY_OF_ON(new com.voxeo.tropo.actions.OnAction.Say("continue"))); tropo.say("Hello"); tropo.startRecording(URL("http://heroku-voip.marksilver.net/post_audio_to_s3?filename=foo.wav&unique_id=bar")); // [From this point, until stop_recording(), we will record what the caller *and* the IVR say] @@ -126,30 +111,26 @@ At the same time, Tropo's Java Webapi defines a complete DSL to create applicati // Example 1 Tropo tropo = new Tropo(); tropo - .ask(NAME("foo"),BARGEIN(true),TIMEOUT(30.0f),REQUIRED(true)).and( - Do.say("Please say your account number"), - Do.on(EVENT("success"),NEXT("/result.json")), - Do.choices(VALUE("[5 DIGITS]"))); + .ask(Key.CHOICES("[5 DIGITS]"), Key.SAY_OF_ASK(new Say("Please say your account number")), Key.NAME("foo"),Key.BARGEIN(true),Key.TIMEOUT(30.0f),Key.REQUIRED(true)); + tropo.on(Key.EVENT("continue"), Key.NEXT("/result.json")); // Example 2 Tropo tropo = new Tropo(); tropo - .conference(NAME("foo"),ID("1234"),MUTE(false),SEND_TONES(false),EXIT_TONE("#")).and( - Do.on(EVENT("join")).say("Welcome to the conference") - ); - + .conference(Key.ID("1234"),Key.NAME("foo"),Key.MUTE(false),Key.PLAY_TONES(false),Key.TERMINATOR("#"),Key.JOIN_PROMPT("Welcome to the conference")); + // Example 3 Tropo tropo = new Tropo(); - tropo.call(TO("foo"), FROM("bar"), NETWORK(Network.SMS), CHANNEL(Channel.TEXT), TIMEOUT(10.0f), ANSWER_ON_MEDIA(false)).and( - Do.headers(new String[]{"fooKey","fooValue"}, new String[]{"barKey","barValue"}), - Do.startRecording(URL("http://foobar"), METHOD("POST"), FORMAT(Format.MP3), USERNAME("jose"), PASSWORD("passwd"))); + Map map = new LinkedHashMap(); + map.put("fooKey", "fooValue"); + map.put("barKey", "barValue"); + tropo.call(Key.NAME("call"), Key.TO("foo"), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false), + Key.HEADERS(map)); // Example 4 Tropo tropo = new Tropo(); - tropo.message(TO("foo"), FROM("bar"), NETWORK(Network.SMS), CHANNEL(Channel.TEXT), TIMEOUT(10.0f), ANSWER_ON_MEDIA(false)).and( - Do.headers(new String[]{"fooKey","fooValue"}, new String[]{"barKey","barValue"}), - Do.startRecording(URL("http://foobar"), METHOD("POST"), FORMAT(Format.MP3), USERNAME("jose"), PASSWORD("passwd")), - Do.say("Please say your account number")); + tropo.message(Key.NAME("message"), Key.SAY_OF_MESSAGE(new Say("This is an announcement")),Key.TO("foo"), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), + Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false)); Below you can also find a very trivial servlet POST method: @@ -164,8 +145,8 @@ Below you can also find a very trivial servlet POST method: And of course, you can read Tropo's session from the request and use it in your Java apps. Again, no Json knowledge required! protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + Tropo tropo = new Tropo(); TropoSession session = tropo.session(request); System.out.println("Call id: " + session.getCallId()); - } \ No newline at end of file + } diff --git a/dist/dependencies/commons-beanutils-1.8.1.jar b/dist/dependencies/commons-beanutils-1.8.1.jar deleted file mode 100644 index c3fb1f2..0000000 Binary files a/dist/dependencies/commons-beanutils-1.8.1.jar and /dev/null differ diff --git a/dist/dependencies/commons-codec-1.3.jar b/dist/dependencies/commons-codec-1.3.jar deleted file mode 100644 index 957b675..0000000 Binary files a/dist/dependencies/commons-codec-1.3.jar and /dev/null differ diff --git a/dist/dependencies/commons-codec-1.9.jar b/dist/dependencies/commons-codec-1.9.jar new file mode 100644 index 0000000..ef35f1c Binary files /dev/null and b/dist/dependencies/commons-codec-1.9.jar differ diff --git a/dist/dependencies/commons-collections-3.2.1.jar b/dist/dependencies/commons-collections-3.2.1.jar deleted file mode 100644 index c35fa1f..0000000 Binary files a/dist/dependencies/commons-collections-3.2.1.jar and /dev/null differ diff --git a/dist/dependencies/commons-httpclient-3.1.jar b/dist/dependencies/commons-httpclient-3.1.jar deleted file mode 100644 index 7c59774..0000000 Binary files a/dist/dependencies/commons-httpclient-3.1.jar and /dev/null differ diff --git a/dist/dependencies/commons-lang-2.5.jar b/dist/dependencies/commons-lang-2.5.jar deleted file mode 100644 index ae491da..0000000 Binary files a/dist/dependencies/commons-lang-2.5.jar and /dev/null differ diff --git a/dist/dependencies/commons-logging-1.1.1.jar b/dist/dependencies/commons-logging-1.1.1.jar deleted file mode 100644 index 1deef14..0000000 Binary files a/dist/dependencies/commons-logging-1.1.1.jar and /dev/null differ diff --git a/dist/dependencies/commons-logging-1.2.jar b/dist/dependencies/commons-logging-1.2.jar new file mode 100644 index 0000000..93a3b9f Binary files /dev/null and b/dist/dependencies/commons-logging-1.2.jar differ diff --git a/dist/dependencies/ezmorph-1.0.6.jar b/dist/dependencies/ezmorph-1.0.6.jar deleted file mode 100644 index 30fad12..0000000 Binary files a/dist/dependencies/ezmorph-1.0.6.jar and /dev/null differ diff --git a/dist/dependencies/gson-2.4.jar b/dist/dependencies/gson-2.4.jar new file mode 100644 index 0000000..8b95cc9 Binary files /dev/null and b/dist/dependencies/gson-2.4.jar differ diff --git a/dist/dependencies/httpclient-4.5.2.jar b/dist/dependencies/httpclient-4.5.2.jar new file mode 100644 index 0000000..701609f Binary files /dev/null and b/dist/dependencies/httpclient-4.5.2.jar differ diff --git a/dist/dependencies/httpcore-4.4.4.jar b/dist/dependencies/httpcore-4.4.4.jar new file mode 100644 index 0000000..ac4a877 Binary files /dev/null and b/dist/dependencies/httpcore-4.4.4.jar differ diff --git a/dist/dependencies/json-lib-2.4-jdk15.jar b/dist/dependencies/json-lib-2.4-jdk15.jar deleted file mode 100644 index 68d4f3b..0000000 Binary files a/dist/dependencies/json-lib-2.4-jdk15.jar and /dev/null differ diff --git a/dist/tropo-webapi-java-0.3.jar b/dist/tropo-webapi-java-0.3.jar deleted file mode 100644 index 8b637ad..0000000 Binary files a/dist/tropo-webapi-java-0.3.jar and /dev/null differ diff --git a/dist/tropo-webapi-java-0.4.7-SNAPSHOT.jar b/dist/tropo-webapi-java-0.4.7-SNAPSHOT.jar new file mode 100644 index 0000000..09a4696 Binary files /dev/null and b/dist/tropo-webapi-java-0.4.7-SNAPSHOT.jar differ diff --git a/pom.xml b/pom.xml index 93a1909..1eb2ff9 100644 --- a/pom.xml +++ b/pom.xml @@ -1,37 +1,56 @@ - + 4.0.0 com.voxeo.tropo tropo-webapi-java - 0.3 + 15.13.0 jar Tropo Java WebApi WebApi Java implementation for the Tropo Cloud platform + https://github.com/tropo/tropo-webapi-java + + + MIT License + http://www.opensource.org/licenses/mit-license.php + + + + + Tropo LLC + engineering@tropo.com + Tropo LLC + http://tropo.com + + + + scm:git:git://github.com/tropo/tropo-webapi-java.git + scm:git:ssh://github.com:tropo/tropo-webapi-java.git + https://github.com/tropo/tropo-webapi-java + - - net.sf.json-lib - json-lib - jdk15 - 2.4 - - - commons-httpclient - commons-httpclient - 3.1 - - - javax.servlet - servlet-api - 2.5 - provided - - - junit - junit - 4.0 - jar - test - true - + + com.google.code.gson + gson + 2.4 + + + org.apache.httpcomponents + httpclient + 4.5.2 + + + javax.servlet + servlet-api + 2.5 + provided + + + junit + junit + 4.11 + test + true + @@ -46,4 +65,73 @@ + + + release + + false + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + 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/ + + diff --git a/samples/tropo-conference-example/.gitignore b/samples/tropo-conference-example/.gitignore new file mode 100644 index 0000000..22ff669 --- /dev/null +++ b/samples/tropo-conference-example/.gitignore @@ -0,0 +1,4 @@ +/target +/.settings/ +/.classpath +/.project diff --git a/samples/tropo-conference-example/pom.xml b/samples/tropo-conference-example/pom.xml new file mode 100644 index 0000000..c5c57f8 --- /dev/null +++ b/samples/tropo-conference-example/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + com.tropo.samples + tropo-conference-example + war + 1.0-SNAPSHOT + tropo-conference-example Maven Webapp + http://maven.apache.org + + + javax.servlet + servlet-api + 2.5 + provided + + + + junit + junit + 3.8.1 + test + + + com.voxeo.tropo + tropo-webapi-java + 0.4.4 + + + + tropo-conference-example + + + + tropo + Tropo Releases Repository + http://maven.tropo.com:8081/nexus/content/repositories/releases/ + + + diff --git a/samples/tropo-conference-example/src/main/java/com/tropo/samples/ConferenceServlet.java b/samples/tropo-conference-example/src/main/java/com/tropo/samples/ConferenceServlet.java new file mode 100644 index 0000000..09a142a --- /dev/null +++ b/samples/tropo-conference-example/src/main/java/com/tropo/samples/ConferenceServlet.java @@ -0,0 +1,38 @@ +package com.tropo.samples; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.voxeo.tropo.Key; +import com.voxeo.tropo.Tropo; +import com.voxeo.tropo.TropoSession; + +public class ConferenceServlet extends HttpServlet { + + private static final long serialVersionUID = 7658399518995371027L; + + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + Tropo tropo = new Tropo(); + + TropoSession tropoSession = tropo.session(req); + System.out.println(tropoSession.getId()); + + tropo.say("Thank you for calling. You will now join the conference."); + + tropo.conference(Key.ID("1234"), Key.ALLOW_SIGNALS("exit", "quit", "bye"), Key.INTERDIGIT_TIMEOUT(11.2F), + //Key.JOIN_PROMPT("Welcome to the conference"), Key.LEAVE_PROMPT("There is someone that leave the conference"), + Key.JOIN_PROMPT(true), Key.LEAVE_PROMPT(true), + Key.MUTE(false), Key.NAME("foo"), Key.PLAY_TONES(true), Key.REQUIRED(true), Key.TERMINATOR("#")); + + tropo.render(resp); + } + + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + doGet(req, resp); + } +} diff --git a/samples/tropo-conference-example/src/main/webapp/META-INF/MANIFEST.MF b/samples/tropo-conference-example/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/samples/tropo-conference-example/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/samples/tropo-conference-example/src/main/webapp/WEB-INF/web.xml b/samples/tropo-conference-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..5e39291 --- /dev/null +++ b/samples/tropo-conference-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,17 @@ + + + + + ConferenceServlet + com.tropo.samples.ConferenceServlet + + + + ConferenceServlet + /ConferenceServlet + + + \ No newline at end of file diff --git a/samples/tropo-record-example/.classpath b/samples/tropo-record-example/.classpath new file mode 100644 index 0000000..e6822d5 --- /dev/null +++ b/samples/tropo-record-example/.classpath @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/tropo-record-example/.gitignore b/samples/tropo-record-example/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/samples/tropo-record-example/.gitignore @@ -0,0 +1 @@ +/target diff --git a/samples/tropo-record-example/pom.xml b/samples/tropo-record-example/pom.xml new file mode 100644 index 0000000..4eddeac --- /dev/null +++ b/samples/tropo-record-example/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + com.tropo.samples + tropo-record-example + war + 1.0-SNAPSHOT + tropo-record-example Maven Webapp + http://maven.apache.org + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + com.voxeo.tropo + tropo-webapi-java + 0.3.2 + + + + junit + junit + 3.8.1 + test + + + + tropo-record-example + + + + tropo + Tropo Releases Repository + http://maven.tropo.com:8081/nexus/content/repositories/releases/ + + + diff --git a/samples/tropo-record-example/src/main/java/com/tropo/samples/RecordServlet.java b/samples/tropo-record-example/src/main/java/com/tropo/samples/RecordServlet.java new file mode 100644 index 0000000..5de75cf --- /dev/null +++ b/samples/tropo-record-example/src/main/java/com/tropo/samples/RecordServlet.java @@ -0,0 +1,37 @@ +package com.tropo.samples; + +import static com.voxeo.tropo.Key.BEEP; +import static com.voxeo.tropo.Key.EVENT; +import static com.voxeo.tropo.Key.EXIT_TONE; +import static com.voxeo.tropo.Key.ID; +import static com.voxeo.tropo.Key.MUTE; +import static com.voxeo.tropo.Key.NAME; +import static com.voxeo.tropo.Key.SEND_TONES; +import static com.voxeo.tropo.Key.URL; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.voxeo.tropo.Tropo; +import com.voxeo.tropo.actions.Do; + +@SuppressWarnings("serial") +public class RecordServlet extends HttpServlet { + + @Override + public void service(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + + Tropo tropo = new Tropo(); + + tropo.say("Thank you for calling. This call will be recorded."); + + tropo.record(NAME("foo"),URL("mailto:mperez@tropo.com"),BEEP(true),SEND_TONES(false),EXIT_TONE("#")); + + tropo.render(response); + } +} diff --git a/samples/tropo-record-example/src/main/webapp/WEB-INF/web.xml b/samples/tropo-record-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..1442ce2 --- /dev/null +++ b/samples/tropo-record-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,17 @@ + + + + Archetype Created Web Application + + + test + com.tropo.samples.RecordServlet + 1 + + + test + /record + + diff --git a/samples/tropo-transfer-example/.classpath b/samples/tropo-transfer-example/.classpath new file mode 100644 index 0000000..e6822d5 --- /dev/null +++ b/samples/tropo-transfer-example/.classpath @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/tropo-transfer-example/.gitignore b/samples/tropo-transfer-example/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/samples/tropo-transfer-example/.gitignore @@ -0,0 +1 @@ +/target diff --git a/samples/tropo-transfer-example/.project b/samples/tropo-transfer-example/.project new file mode 100644 index 0000000..3d79d48 --- /dev/null +++ b/samples/tropo-transfer-example/.project @@ -0,0 +1,14 @@ + + + tropo-transfer-example + NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse. + + + + org.eclipse.jdt.core.javabuilder + + + + org.eclipse.jdt.core.javanature + + \ No newline at end of file diff --git a/samples/tropo-transfer-example/pom.xml b/samples/tropo-transfer-example/pom.xml new file mode 100644 index 0000000..43deffd --- /dev/null +++ b/samples/tropo-transfer-example/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + com.tropo.samples + tropo-transfer-example + war + 1.0-SNAPSHOT + tropo-transfer-example Maven Webapp + http://maven.apache.org + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + com.voxeo.tropo + tropo-webapi-java + 0.3.2 + + + + junit + junit + 3.8.1 + test + + + + tropo-transfer-example + + + + tropo + Tropo Releases Repository + http://maven.tropo.com:8081/nexus/content/repositories/releases/ + + + diff --git a/samples/tropo-transfer-example/src/main/java/com/tropo/samples/TransferServlet.java b/samples/tropo-transfer-example/src/main/java/com/tropo/samples/TransferServlet.java new file mode 100644 index 0000000..f37adeb --- /dev/null +++ b/samples/tropo-transfer-example/src/main/java/com/tropo/samples/TransferServlet.java @@ -0,0 +1,24 @@ +package com.tropo.samples; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.voxeo.tropo.Tropo; + +@SuppressWarnings("serial") +public class TransferServlet extends HttpServlet { + + @Override + public void service(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + + Tropo tropo = new Tropo(); + tropo.say("Thank you for calling. Your call will be transfered."); + tropo.transfer("+14074873689"); + tropo.render(response); + } +} diff --git a/samples/tropo-transfer-example/src/main/webapp/WEB-INF/web.xml b/samples/tropo-transfer-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..58866d7 --- /dev/null +++ b/samples/tropo-transfer-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,17 @@ + + + + Archetype Created Web Application + + + test + com.tropo.samples.TransferServlet + 1 + + + test + /transfer + + diff --git a/src/main/java/com/voxeo/tropo/ActionResult.java b/src/main/java/com/voxeo/tropo/ActionResult.java index e2bca57..d650aff 100644 --- a/src/main/java/com/voxeo/tropo/ActionResult.java +++ b/src/main/java/com/voxeo/tropo/ActionResult.java @@ -17,8 +17,20 @@ public class ActionResult implements Serializable { private Integer attempts; private String disposition; private String interpretation; - private String utterrance; + private String utterance; private Integer confidence; + private String value; + private String concept; + private String xml; + private Integer duration; + private String url; + + /*Depend on upload status after recording completion. "uploadStatus": ["success"|"failed"|"unavailable"], will provide + information about the recording status + */ + private String uploadStatus; + private Integer connectedDuration; + private String userType; public String getName() { return name; @@ -50,11 +62,11 @@ public String getInterpretation() { public void setInterpretation(String interpretation) { this.interpretation = interpretation; } - public String getUtterrance() { - return utterrance; + public String getUtterance() { + return utterance; } - public void setUtterrance(String utterrance) { - this.utterrance = utterrance; + public void setUtterance(String utterrance) { + this.utterance = utterrance; } public String getValue() { return value; @@ -74,8 +86,39 @@ public String getXml() { public void setXml(String xml) { this.xml = xml; } - private String value; - private String concept; - private String xml; - + public Integer getDuration() { + return duration; + } + public void setDuration(Integer duration) { + this.duration = duration; + } + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + public String getuploadStatus() { + return uploadStatus; + } + public void setuploadStatus(String uploadStatus) { + this.uploadStatus = uploadStatus; + } + public Integer getConnectedDuration() { + return connectedDuration; + } + public void setConnectedDuration(Integer connectedDuration) { + this.connectedDuration = connectedDuration; + } + public String getUserType() { + return userType; + } + public void setUserType(String userType) { + this.userType = userType; + } + + @Override + public String toString(){ + return TropoUtils.toPrettyString(this); + } } diff --git a/src/main/java/com/voxeo/tropo/InitialMedia.java b/src/main/java/com/voxeo/tropo/InitialMedia.java new file mode 100644 index 0000000..a4f33c6 --- /dev/null +++ b/src/main/java/com/voxeo/tropo/InitialMedia.java @@ -0,0 +1,49 @@ +package com.voxeo.tropo; + +import java.io.Serializable; + +public class InitialMedia implements Serializable { + + private static final long serialVersionUID = 610952828909985978L; + + private String text; + + private String media; + + private String status; + + private String disposition; + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getMedia() { + return media; + } + + public void setMedia(String media) { + this.media = media; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDisposition() { + return disposition; + } + + public void setDisposition(String disposition) { + this.disposition = disposition; + } + +} diff --git a/src/main/java/com/voxeo/tropo/Key.java b/src/main/java/com/voxeo/tropo/Key.java index f96edb9..959c193 100644 --- a/src/main/java/com/voxeo/tropo/Key.java +++ b/src/main/java/com/voxeo/tropo/Key.java @@ -1,188 +1,888 @@ package com.voxeo.tropo; -import com.voxeo.tropo.enums.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.voxeo.tropo.actions.AskAction.Choices; +import com.voxeo.tropo.actions.RecordAction.Transcription; +import com.voxeo.tropo.actions.RecordAction.Url; +import com.voxeo.tropo.enums.As; +import com.voxeo.tropo.enums.AsrLogSecurity; +import com.voxeo.tropo.enums.Channel; +import com.voxeo.tropo.enums.EmailFormat; +import com.voxeo.tropo.enums.Format; +import com.voxeo.tropo.enums.Method; +import com.voxeo.tropo.enums.Mode; +import com.voxeo.tropo.enums.Network; +import com.voxeo.tropo.enums.Recognizer; +import com.voxeo.tropo.enums.Terminator; +import com.voxeo.tropo.enums.Voice; public class Key { private String name; private Object value; - + private Key(String name) { - + this.name = name; } public static Key NAME(String value) { - + return createKey("name", value); } public static Key VALUE(String value) { - + return createKey("value", value); } + /** + * This determines whether Tropo should move on to the next verb; if required + * is set to 'true', Tropo will only move on to the next verb if the current + * operation completely successfully. + *

+ * Default: true + *

+ */ public static Key REQUIRED(Boolean value) { - + return createKey("required", value); - } + } public static Key BARGEIN(Boolean value) { - + return createKey("bargein", value); - } - + } + public static Key TIMEOUT(Float value) { - + return createKey("timeout", value); - } - + } + + /** + * This is useful to allow to help users restart the process if they mistyped. + * + * @deprecated The preferred way to do this is via the + * {@link #INTERDIGIT_TIMEOUT(Float)} + * @param value + * How long does Tropo wait between key presses to determine the user + * is done with their input. + */ + @Deprecated public static Key INTERDIGIT_TIMEOUT(Integer value) { - + return createKey("interdigitTimeout", value); - } - - public static Key CHOICES(String value) { - - return createKey("choices", value); } - + + public static Key CHOICES_OF_ASK(String value) { + + return CHOICES_OF_ASK(new Choices(value)); + } + public static Key EVENT(String value) { - + return createKey("event", value); } - + public static Key NEXT(String value) { - + return createKey("next", value); } - + public static Key MODE(Mode value) { - + return createKey("mode", value); } public static Key ID(String value) { - + return createKey("id", value); } - + + /** + * Adds the user to the conference room with their audio muted. + *

+ * Default: false + *

+ */ public static Key MUTE(Boolean value) { - + return createKey("mute", value); - } + } + + /** + * This is the touch-tone key used to exit the conference. + * + * @deprecated The preferred way to do this is via the + * {@link #TERMINATOR(String)} + */ + @Deprecated public static Key EXIT_TONE(String value) { - + return createKey("exit_tone", value); - } + } + + /** + * This defines whether to send touch tone phone input to the conference or + * block the audio. + * + * @deprecated The preferred way to do this is via the + * {@link #PLAY_TONES(Boolean)} + */ + @Deprecated public static Key SEND_TONES(Boolean value) { - + return createKey("send_tones", value); } + + public static Key SENSITIVITY(Float value) { + + return createKey("sensitivity", value); + } + + /** + *

+ * The FTP or HTTP URL or S3 Bucket to send the recorded audio file. When + * sending via POST, the name of the form field is "filename". Accepts SSL + * (FTPS and HTTPS) and SFTP URLs as well. If the URL is an S3 bucket, Tropo + * will upload to that, using the "username" parameter as the Access Key ID, + * and your "password" parameter as the Access Key Secret. + *

+ *

+ * The file will take a few moments to upload to your server. The exact amount + * of time depends on many factors, including the network connection of your + * server. If your application needs to play back the audio immediately after + * recording is completed, the object returned by the record method has a + * "value" property that contains a url of a temporary local copy of the file. + * This temporary copy will be deleted as soon as the call ends. + *

+ *

+ * Please note this needs to be a fully qualified URL, i.e. + * "http:​//​example.com/folder/subfolder" vs "/folder/subfolder". If you + * don't have a complete URL, the file won't send at all or at the very least + * won't send correctly (0 byte file and similar unusable content). + *

+ *

+ * For FTP, include the full URl including the file name, i.e. + * "ftp:​//example.com/folder/my-recording.wav" + *

+ */ public static Key URL(String value) { - + return createKey("url", value); } + + public static Key URL(String... value) { + + List urls = new ArrayList(); + + for (String url : value) { + urls.add(new Url(url)); + } + + return createKey("url", urls); + } + + public static Key URL(Url value) { + + return createKey("url", value); + } + + public static Key URL(Url... value) { + + return createKey("url", value); + } + public static Key BEEP(Boolean value) { - + return createKey("beep", value); } public static Key TO(String value) { - + return createKey("to", value); } public static Key TO(String... value) { - + return createKey("to", value); } public static Key FROM(String value) { - + return createKey("from", value); } public static Key NETWORK(Network value) { - + return createKey("network", value); } public static Key CHANNEL(Channel value) { - + return createKey("channel", value); } public static Key ANSWER_ON_MEDIA(Boolean value) { - + return createKey("answerOnMedia", value); } + + /** + * This specifies the format for the audio recording; it can be + * {@link Format#WAV}, {@link Format#MP3} or {@link Format#AU}. + *

+ * Default:{@link Format#WAV} + *

+ */ public static Key FORMAT(Format value) { - + return createKey("format", value); } + + /** + *

+ * Defines the username for uploading your recording. For HTTP, this is a + * Basic Auth user. + *

+ *

+ * For FTP, this is your FTP server's user name. + *

+ *

+ * For S3, this is your AWS Access Key ID. + *

+ *

+ * Note: If user name contains @ or /, the character must be URL encoded. + *

+ */ public static Key USERNAME(String value) { - + return createKey("username", value); } + + /** + *

+ * Defines the password for uploading a file. When using HTTP, this will be + * used as a password for Basic Auth to your server. + *

+ *

+ * For FTP, this is your FTP user password. + *

+ *

+ * For S3, this is your AWS access key secret. + *

+ *

+ * Note: If password contains @ or /, the character must be URL encoded. + *

+ */ public static Key PASSWORD(String value) { - + return createKey("password", value); } + + /** + * @deprecated The preferred way to do this is via the {@link #METHOD(Method)} + */ + @Deprecated public static Key METHOD(String value) { - + return createKey("method", value); } public static Key EMAIL_FORMAT(String value) { - + return createKey("emailFormat", value); - } + } public static Key AS(As as) { - + return createKey("as", as); - } + } public static Key VOICE(Voice voice) { - + return createKey("voice", voice); - } + } + + /** + * Define allowSignals as an empty string (""), it defines the function as + * "uninterruptible". + */ public static Key ALLOW_SIGNALS() { - + return createKey("allowSignals", ""); - } + } + + /** + *

+ * It allows you to assign a signal to this function. Events from the Tropo + * REST API with a matching signal name will "interrupt" the function (i.e., + * stop it from running). If it already ran and completed, your interrupt + * request will be ignored. If the function has not run yet, the interrupt + * will be queued until it does run. + *

+ *

+ * By default, allowSignals will accept any signal as valid; you can also use + * an array - the function will stop if it receives an interrupt signal + * matching any of the names in the array. + *

+ */ public static Key ALLOW_SIGNALS(String... signals) { - + return createKey("allowSignals", signals); - } + } public static Key ATTEMPTS(Integer attempts) { - + return createKey("attempts", attempts); } public static Key MAX_SILENCE(Float value) { - + return createKey("maxSilence", value); } public static Key MIN_CONFIDENCE(Integer minConfidence) { - + return createKey("minConfidence", minConfidence); } public static Key RECOGNIZER(Recognizer recognizer) { - + return createKey("recognizer", recognizer); } - + public static Key MILLISECONDS(Long milliseconds) { + + return createKey("milliseconds", milliseconds); + } + + /** + * This is the touch-tone key (also known as "DTMF digit") used to exit. + */ + public static Key TERMINATOR(String value) { + + return createKey("terminator", value); + } + + public static Key MAX_TIME(Float value) { + + return createKey("maxTime", value); + } + + /** + *

+ * Setting to true will instruct Tropo to upload the recording file in the + * background as soon as the recording is completed. + *

+ *

+ * If this is set to false (the default behavior), Tropo will wait until the + * file is uploaded before returning or running the onRecord callback. + *

+ *

+ * Default: false + *

+ */ + public static Key ASYNC_UPLOAD(Boolean value) { + + return createKey("asyncUpload", value); + } + + /** + * How long does Tropo wait between key presses to determine the user is done + * with their input. This is useful to allow to help users restart the process + * if they mistyped. + *

+ * Default: 5.0 + *

+ */ + public static Key INTERDIGIT_TIMEOUT(Float value) { + + return createKey("interdigitTimeout", value); + } + + /** + * Defines a prompt that plays to all participants of a conference when + * someone joins the conference. If set to true, the default beep is played. + *

+ * Default: false + *

+ */ + public static Key JOIN_PROMPT(Boolean value) { + + return createKey("joinPrompt", value); + } + + /** + * Defines a prompt that plays to all participants of a conference when + * someone joins the conference.It's possible to define either TTS or an audio + * URL using additional attributes value and voice + * + * @param value + * value is used to play simple TTS and/or an audio URL, and supports + * SSML + * @param voice + * voice is used to define which of the available voices should be + * used for TTS; if voice is left undefined, the default voice will + * be used + * @return + */ + public static Key JOIN_PROMPT(String value, Voice voice) { + + Map map = new HashMap(); + map.put("value", value); + if (voice != null) { + map.put("voice", voice.toString()); + } + + return createKey("joinPrompt", map); + } + + public static Key JOIN_PROMPT(String value) { + + return JOIN_PROMPT(value, null); + } + + /** + * Defines a prompt that plays to all participants of a conference when + * someone leaves the conference. If set to true, the default beep is played. + *

+ * Default: false + *

+ */ + public static Key LEAVE_PROMPT(Boolean value) { + + return createKey("leavePrompt", value); + } + + /** + * Defines a prompt that plays to all participants of a conference when + * someone leaves the conference.It's possible to define either TTS or an + * audio URL using additional attributes value and voice + * + * @param value + * value is used to play simple TTS and/or an audio URL, and supports + * SSML + * @param voice + * voice is used to define which of the available voices should be + * used for TTS; if voice is left undefined, the default voice will + * be used + * @return + */ + public static Key LEAVE_PROMPT(String value, Voice voice) { + + Map map = new HashMap(); + map.put("value", value); + if (voice != null) { + map.put("voice", voice.toString()); + } + + return createKey("leavePrompt", map); + } + + public static Key LEAVE_PROMPT(String value) { + + return LEAVE_PROMPT(value, null); + } + + /** + * This defines whether to send touch tone phone input to the conference or + * block the audio. + *

+ * Default: false + *

+ */ + public static Key PLAY_TONES(Boolean value) { + + return createKey("playTones", value); + } + + /** + * Controls whether Tropo logs the text to speech string used by the method, + * which disables output logging for this method. + */ + public static Key PROMPT_LOG_SECURITY() { + + return createKey("promptLogSecurity", "suppress"); + } + + /** + * For HTTP recording upload, this parameter determines the method used. This + * can be {@link Method#POST} (which is the default) or {@link Method#PUT}. + * When sending via {@link Method#POST}, the file is sent as if you uploaded + * in a web form with a form field name of "filename". + */ + public static Key METHOD(Method method) { + + return createKey("method", method); + } + + /** + *

+ * Setting this to anything enables transcription on this recording. The + * e-mail address or HTTP URL to send the transcription results to; the + * transcription arrives as the content of the HTTP POST, as opposed to a + * header, named field or variable, and is not sent as form data. + *

+ *

+ * Email addresses must be prefaced with mailto: if used + * (mailto:you@example.com) + *

+ */ + public static Key TRANSCRIPTION_OUT_URI(String value) { + + return createKey("transcriptionOutURI", value); + } + + /** + * Specifies the encoding used when delivering transcriptions via e-mail. + * Values can be {@link EmailFormat#PLAIN} or {@link EmailFormat#ENCODED}. + *

+ * {@link EmailFormat#PLAIN} + *

+ */ + public static Key TRANSCRIPTION_EMAIL_FORMAT(EmailFormat emailFormat) { + + return createKey("transcriptionEmailFormat", emailFormat); + } + + /** + * User definable ID that can be included when the transcription is posted to + * transcriptionOutURI. + */ + public static Key TRANSCRIPTION_ID(String value) { + + return createKey("transcriptionID", value); + } + + public static Key TRANSCRIPTION_LANGUAGE(String value) { + + return createKey("transcriptionLanguage", value); + } + + /** + *

+ * The choices object tells Tropo how to handle user input. It indicates the + * structure of the expected data, if any, and the various acceptable modes of + * input - some applications require just keypad input (dtmf), others are + * speech driven and some can accept both. + *

+ *

+ * These are the properties for the choices object: + *

+ *
    + *
  • value -- This is the grammar which determines the type + * of expected data. See the examples below for more detail.
  • + *
  • mode (default: any) -- Only applies to the voice + * channel and can be either 'speech', 'dtmf', or 'any'.
  • + *
  • terminator (default: #) -- This is the touch-tone key + * (also known as "DTMF digit") that indicates the end of input. A common use + * of the terminator is the # key, eg: + * "Please enter your five digit zip code, then press the pound key."
  • + *
+ */ + public static Key CHOICES_OF_ASK(Choices choices) { + + return createKey("choices", choices); + } + + /** + *

+ * This determines what is played or sent to the caller. This can be a single + * object or an array of objects. When say is a part of an ask, it takes an + * event key. This determines if the prompt will be played based on a + * particular event; the possible events are: + *

+ *
    + *
  • nomatch -- Returned if the user did not say or input a + * valid response.
  • + *
  • timeout -- Returned if there was no user input in the + * allotted time.
  • + *
+ *

+ * Each of these event descriptors can also take an attempt value, based on + * the number of attempted input requests. For example, if you want to define + * a different say depending on the attempt, you would specify one say with + * the event 'nomatch:1' and a different say for the event 'nomatch:2'. + *

+ */ + public static Key SAY_OF_ASK(com.voxeo.tropo.actions.AskAction.Say... says) { + + return createKey("say", says); + } + + public static Key SAY_OF_ASK(String value) { + + return SAY_OF_ASK(new com.voxeo.tropo.actions.AskAction.Say(value)); + } + + /** + *

+ * This field defines how long the application should wait - in seconds - + * after input before determining a match. This is most useful for options + * with variable input - for example, if you ask a caller for their 4 OR 5 + * digit pin number and use the [4-5 DIGITS] grammar, the user might reply + * with 4 digits and then stop, even if you define a terminator. This field + * allows you to define how long you want the app to wait before the + * application decided the caller is finished responding and has no further + * input. + *

+ */ + public static Key SPEECH_COMPLETE_TIMEOUT(Float value) { + + return createKey("speechCompleteTimeout", value); + } + + /** + *

+ * This field defines how long the application should wait - in seconds - + * after partial input before determining a "no match". For example, if you + * prompt the caller to select three choices from a list of options, and the + * caller responds with only one then stops talking, this defines how long the + * app will wait before considering the caller finished and returning a no + * match. + *

+ */ + public static Key SPEECH_INCOMPLETE_TIMEOUT(Float value) { + + return createKey("speechIncompleteTimeout", value); + } + + /** + *

+ * Control whether Tropo should log the input from the user in response to the + * ask method. Possible values are "none" (the default), "suppress" (which + * prevents logging entirely), or "mask" (which replaces selected characters + * with a *. If set to "mask", then you also must set the maskTemplate + * parameter to a valid masking pattern. + *

+ */ + public static Key ASR_LOG_SECURITY(AsrLogSecurity asrLogSecurity) { + + return createKey("asrLogSecurity", asrLogSecurity); + } + + /** + *

+ * When asrLogSecurity is set to "mask", this parameter defines the pattern + * that should be masked. Only digit input can be masked, for any other input + * Tropo will ignore the maskTemplate and suppress the input logging entirely. + *

+ *

+ * The mask template is a masking pattern constructed of three characters. "D" + * in any postion indicates that Tropo should log the digit that appears at + * that position. "X" in a position tells Tropo to suppress the digit + * appearing at that position, and Tropo will replace it with a "*". A hyphen + * or dash "-" tells Tropo to replace one or more digits with a star. For + * example, with a maskTemplate of XXDD- the string 123456789 becomes + * "**34*****". + *

+ */ + public static Key MASK_TEMPLATE(String value) { + + return createKey("maskTemplate", value); + } + + /** + * This contains the Session Initiation Protocol (SIP) Headers for the current + * session. This is advanced network information. + */ + public static Key HEADERS(Map object) { + + return createKey("headers", object); + } + + /** + *

+ * If set to false, no machineDetection will be attempted and the field will + * be Boolean. + *

+ *

+ * If you do not include an introduction and machineDetection is true, then + * Tropo will return as soon as it is confident the answering endpoint is a + * user or machine. However, this results in silence while Tropo makes the + * determination. Silence ranges from 1 to 10 seconds. + *

+ */ + public static Key MACHINE_DETECTION(Boolean value) { + + return createKey("machineDetection", value); + } + + public static Key MACHINE_DETECTION(String introduction) { + + return MACHINE_DETECTION(introduction, null); + } + + /** + *

+ * If introduction is set, Tropo plays the TTS string using voice or plays the + * audio file if a URL is defined (same behavior as say) during this wait. + * Tropo will not return until introduction is done playing, even if it has + * determined a human voice or machine response before the introduction is + * complete. + *

+ *

+ * For the most accurate results, the "introduction" should be long enough to + * give Tropo time to detect a human or machine. The longer the introduction, + * the more time we have to determine how the call was answered. If the + * introduction is long enough to play until the voicemail "beep" plays, Tropo + * will have the most accurate detection. It takes a minimum of four seconds + * to determine if a call was answered by a human or machine, so introductions + * four seconds or shorter will always return HUMAN. + *

+ */ + public static Key MACHINE_DETECTION(String introduction, Voice voice) { + + Map map = new LinkedHashMap(); + map.put("introduction", introduction); + if (voice != null) { + map.put("voice", voice.toString()); + } + + return createKey("machineDetection", map); + } + + /** + *

+ * Configures a URL for a webhook for CDRs to be sent at the completion of the + * call. This overrides any URLs you have set in your application + * configuration. + *

+ */ + public static Key CALLBACK_URL(String value) { + + return createKey("callbackUrl", value); + } + + /** + *

+ * Set by you, an arbitrary label for this call. The label you set will appear + * in your CDR, allowing you to track a CDR by a string you define. See + * Labeling your CDRs for examples. + *

+ */ + public static Key LABEL(String value) { + + return createKey("label", value); + } + + /** + *

+ * This determines what is played or sent to the caller. This can be a single + * object or an array of objects. + *

+ */ + public static Key SAY_OF_MESSAGE(com.voxeo.tropo.actions.MessageAction.Say... says) { + + return createKey("say", says); + } + + public static Key SAY_OF_ON(String value) { + + return SAY_OF_ON(new com.voxeo.tropo.actions.OnAction.Say(value)); + } + + /** + *

+ * This determines what is played or sent to the caller. This can be a single + * object or an array of objects. + *

+ */ + public static Key SAY_OF_ON(com.voxeo.tropo.actions.OnAction.Say... says) { + + return createKey("say", says); + } + + /** + *

+ * This parameter is only available in the 'connect' event of transfer. + * Because a transfer is a blocking function, your 'continue' event won't fire + * until the transfer is completed and so your web application doesn't know if + * the transfer succeeded or not. When given a URL, the 'post' action will + * send a simplified Result object as an HTTP POST to this URL. Like all other + * actions that are sent during the connect event, this happens while the + * first caller is hearing the 'ring' event, and before the two parties are + * connected. Any response by your web application to this HTTP post is + * ignored. It is simply a webhook that fires to alert your web application + * that the call has been connected. + *

+ */ + public static Key POST(String value) { + + return createKey("post", value); + } + + /** + *

+ * This specifies the number of times the audio file specified in the ring + * event will repeat itself. + *

+ */ + public static Key RING_REPEAT(Integer value) { + + return createKey("ringRepeat", value); + } + + public static Key CHOICES(Terminator value) { + + Map map = new HashMap(); + map.put("terminator", value.toString()); + + return createKey("choices", map); + } + + /** + *

+ * This determines what is played or sent to the caller. This can be a single + * object or an array of objects. When say is a part of a record action, it + * can also take an event key. This determines if the prompt will be played + * based on a particular event; for record, the only possible event is + * 'timeout'. + *

+ */ + public static Key SAY_OF_RECORD(com.voxeo.tropo.actions.RecordAction.Say... says ) { + + return createKey("say", says); + } + + /** + *

+ * This allows you to submit a recording to be transcribed and specifies where + * to send the transcription. This field is a hash containing other fields. + *

+ *
    + *
  • id - the value that's included with your transcription when it's sent + * to your URL. This allows you to keep track of transcriptions; accepts a + * string.
  • + *
  • url - The address this transcription will be POSTed to; use a mailto: + * url to have the transcription emailed.
  • + *
  • emailFormat - the format of the email. Setting it as "encoded" will + * include a chunk of JSON in the email body or you can set it as "omit" to + * send as a human-readable message. It defaults to "omit", so unless you want + * JSON, this can be left out.
  • + *
+ *

+ * The transcription arrives as the content of the HTTP POST, as opposed to a + * header, named field or variable. + *

+ */ + public static Key TRANSCRIPTION(Transcription transcription) { + + return createKey("transcription", transcription); + } + + public static Key LANGUAGE(String value) { + + return createKey("language", value); + } + + public static Key MEDIA(String... medias) { + + return createKey("media", medias); + } + public static Key createKey(String name, Object value) { - // There is an issue with JSON-LIB. When an element starts with { or [ then json-lib handles it - // as JSON creating wrong text. Ej. "[5 DIGITS]" is transformed to ["5 DIGITS"] - if (value instanceof String) { - String strValue = (String)value; - if (strValue.startsWith("[") || strValue.startsWith("{")) { - strValue = strValue.replace("[", "$[$"); - strValue = strValue.replace("{", "${$"); - value = strValue; - } - } else if (value instanceof Enum) { + if (value instanceof Enum) { value = value.toString(); } Key key = new Key(name); key.value = value; return key; } - + public String getName() { return name; } diff --git a/src/main/java/com/voxeo/tropo/SessionLauncher.java b/src/main/java/com/voxeo/tropo/SessionLauncher.java index e6ebaea..bf23904 100644 --- a/src/main/java/com/voxeo/tropo/SessionLauncher.java +++ b/src/main/java/com/voxeo/tropo/SessionLauncher.java @@ -2,17 +2,36 @@ import java.io.BufferedReader; import java.io.InputStreamReader; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.NameValuePair; -import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicNameValuePair; public class SessionLauncher { + private final HttpClient client; + + public SessionLauncher() { + client = HttpClientBuilder.create().build(); + } + + public SessionLauncher(HttpClient httpClient) { + if (httpClient == null) { + httpClient = HttpClientBuilder.create().build(); + } + client = httpClient; + } + public TropoLaunchResult launchSession(String baseUrl, String token, Map mapParams) { if (mapParams == null) { @@ -21,37 +40,41 @@ public TropoLaunchResult launchSession(String baseUrl, String token, Map params = new ArrayList(); + params.add(new BasicNameValuePair("token", token)); for (Map.Entry entry: mapParams.entrySet()) { - params[i] = new NameValuePair(entry.getKey(), entry.getValue()); - i++; + params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } - method.setRequestBody(params); - - method.setRequestHeader(new Header("User-Agent", "Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4")); - method.setRequestHeader(new Header("Accept", "application/json")); - method.setRequestHeader(new Header("Content-Type", "application/x-www-form-urlencoded")); BufferedReader reader = null; + HttpPost method = null; try { + URIBuilder builder = new URIBuilder(url); + + builder.setParameter("http.useragent", "Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4"); + method = new HttpPost(builder.build()); + + method.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4"); + method.setHeader(HttpHeaders.ACCEPT, "application/json"); + method.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); - int returnCode = client.executeMethod(method); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); + method.setEntity(entity); + HttpResponse httpResponse = client.execute(method); + int returnCode = httpResponse.getStatusLine().getStatusCode(); if (returnCode != HttpStatus.SC_OK) { throw new TropoException(String.format("Server returned with error code: %s", returnCode)); } - reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); + reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); return parser.sessionLaunch(reader); } catch (Exception e) { throw new TropoException("Could not launch session", e); } finally { - method.releaseConnection(); - if(reader != null) try { reader.close(); } catch (Exception fe) {} + if (method != null) { + method.releaseConnection(); + } + if(reader != null) try { reader.close(); } catch (Exception fe) {} } } } diff --git a/src/main/java/com/voxeo/tropo/Tropo.java b/src/main/java/com/voxeo/tropo/Tropo.java index 5589dc0..b5565f1 100644 --- a/src/main/java/com/voxeo/tropo/Tropo.java +++ b/src/main/java/com/voxeo/tropo/Tropo.java @@ -7,17 +7,18 @@ import static com.voxeo.tropo.Key.EXIT_TONE; import static com.voxeo.tropo.Key.FORMAT; import static com.voxeo.tropo.Key.FROM; +import static com.voxeo.tropo.Key.MILLISECONDS; import static com.voxeo.tropo.Key.NAME; import static com.voxeo.tropo.Key.NETWORK; import static com.voxeo.tropo.Key.NEXT; import static com.voxeo.tropo.Key.PASSWORD; import static com.voxeo.tropo.Key.REQUIRED; import static com.voxeo.tropo.Key.SEND_TONES; +import static com.voxeo.tropo.Key.SENSITIVITY; import static com.voxeo.tropo.Key.TIMEOUT; import static com.voxeo.tropo.Key.TO; import static com.voxeo.tropo.Key.URL; import static com.voxeo.tropo.Key.USERNAME; -import static com.voxeo.tropo.Key.VALUE; import java.io.IOException; import java.util.Collections; @@ -26,8 +27,9 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import support.ActionSupportHandler; +import org.apache.http.client.HttpClient; +import com.voxeo.tropo.actions.AnswerAction; import com.voxeo.tropo.actions.ArrayBackedJsonAction; import com.voxeo.tropo.actions.AskAction; import com.voxeo.tropo.actions.CallAction; @@ -40,265 +42,395 @@ import com.voxeo.tropo.actions.SayAction; import com.voxeo.tropo.actions.StartRecordingAction; import com.voxeo.tropo.actions.TransferAction; +import com.voxeo.tropo.actions.WaitAction; import com.voxeo.tropo.enums.Channel; import com.voxeo.tropo.enums.Format; +import com.voxeo.tropo.enums.LogSecurityState; import com.voxeo.tropo.enums.Network; +import support.ActionSupportHandler; + public class Tropo extends ArrayBackedJsonAction { - - private TropoParser parser; - private String baseUrl = "https://api.tropo.com/v1/"; - - private ActionSupportHandler sayActionSupportHandler = new ActionSupportHandler(SayAction.class); - private ActionSupportHandler askActionSupportHandler = new ActionSupportHandler(AskAction.class); - private ActionSupportHandler conferenceActionSupportHandler = new ActionSupportHandler(ConferenceAction.class); - private ActionSupportHandler choicesActionSupportHandler = new ActionSupportHandler(ChoicesAction.class); - private ActionSupportHandler onActionSupportHandler = new ActionSupportHandler(OnAction.class); - private ActionSupportHandler recordActionSupportHandler = new ActionSupportHandler(RecordAction.class); - private ActionSupportHandler redirectActionSupportHandler = new ActionSupportHandler(RedirectAction.class); - private ActionSupportHandler startRecordingActionSupportHandler = new ActionSupportHandler(StartRecordingAction.class); - private ActionSupportHandler transferActionSupportHandler = new ActionSupportHandler(TransferAction.class); - private ActionSupportHandler callActionSupportHandler = new ActionSupportHandler(CallAction.class); - private ActionSupportHandler messageActionSupportHandler = new ActionSupportHandler(MessageAction.class); - - public Tropo() { - - super("tropo"); - parser = new TropoParser(); - } - - public SayAction say(String text) { - - return say(VALUE(text)); - } - - public SayAction say(Key... keys) { - - return sayActionSupportHandler.build(this, "tropo", keys); - } - - public AskAction ask(Key... keys) { - - return askActionSupportHandler.build(this, "tropo", keys); - } - - public AskAction ask(String name, Boolean bargein, Float timeout, Boolean required) { - - return ask(NAME(name),BARGEIN(bargein),TIMEOUT(timeout),REQUIRED(required)); - } - - public ChoicesAction choices(Key... keys) { - - return choicesActionSupportHandler.build(this, "tropo", keys); - } - - public ConferenceAction conference(Key... keys) { - - return conferenceActionSupportHandler.build(this, "tropo", keys); - } - - public OnAction on(Key... keys) { - - return onActionSupportHandler.build(this, "tropo", keys); - } - - public OnAction on(String event, String next) { - - return on(EVENT(event), NEXT(next)); - } - - public RecordAction record(Key... keys) { - - return recordActionSupportHandler.build(this, "tropo", keys); - } - - public RecordAction record(String name, String url, Boolean beep, Boolean sendTones, String exitTone) { - - return record(NAME(name), URL(url), BEEP(beep), SEND_TONES(sendTones), EXIT_TONE(exitTone)); - } - - public RedirectAction redirect(Key... keys) { - - return redirectActionSupportHandler.build(this, "tropo", keys); - } - - public RedirectAction redirect(String to) { - - return redirect(TO(to)); - } - - public RedirectAction redirect(String to, String from) { - - return redirect(TO(to),FROM(from)); - } - - public StartRecordingAction startRecording(Key... keys) { - - return startRecordingActionSupportHandler.build(this, "tropo", keys); - } - - public StartRecordingAction startRecording(String url) { - - return startRecording(URL(url)); - } - - public StartRecordingAction startRecording(String url, Format format) { - - return startRecording(URL(url),FORMAT(format)); - } - - public StartRecordingAction startRecording(String url, Format format, String username, String password) { - - return startRecording(URL(url),FORMAT(format),USERNAME(username),PASSWORD(password)); - } - - public void hangup(Key... key) { - - addNull("tropo", "hangup"); - } - - public void stopRecording(Key... key) { - - addNull("tropo", "stopRecording"); - } - - public void reject(Key... key) { - - addNull("tropo", "reject"); - } - - public TransferAction transfer(Key... keys) { - - return transferActionSupportHandler.build(this, "tropo", keys); - } - - public TransferAction transfer(String to) { - - return transfer(TO(to)); - } - - public TransferAction transfer(String to, String from) { - - return transfer(TO(to), FROM(from)); - } - - public CallAction call(Key... keys) { - - return callActionSupportHandler.build(this, "tropo", keys); - } - - public CallAction call(String to) { - - return call(TO(to)); - } - - public CallAction call(String to, Network network) { - - return call(TO(to),NETWORK(network)); - } - - public CallAction call(String to, Network network, String from) { - - return call(TO(to),NETWORK(network),FROM(from)); - } - - public CallAction call(String to, Network network, String from, Channel channel) { - - return call(TO(to),NETWORK(network),FROM(from),CHANNEL(channel)); - } - - public MessageAction message(Key... keys) { - - return messageActionSupportHandler.build(this, "tropo", keys); - } - - public MessageAction message(String to) { - - return message(TO(to)); - } - - public MessageAction message(String to, Network network) { - - return message(TO(to),NETWORK(network)); - } - - public MessageAction message(String to, Network network, String from) { - - return message(TO(to),NETWORK(network),FROM(from)); - } - - public MessageAction message(String to, Network network, String from, Channel channel) { - - return message(TO(to),NETWORK(network),FROM(from),CHANNEL(channel)); - } - - public TropoResult parse(String json) { - - return parser.parse(json); - } - - public TropoSession session(String json) { - - return parser.session(json); - } - - public TropoResult parse(HttpServletRequest request) { - - return parser.parse(request); - } - - public TropoSession session(HttpServletRequest request) { - - return parser.session(request); - } - - @SuppressWarnings("rawtypes") - public Map parse(Map json) { - - return parser.parse(json); - } - - public void render(HttpServletResponse response) { - - render(response, text()); - } - - public void render(HttpServletResponse response, String json) { - - try { - response.setContentType("application/json"); - response.setCharacterEncoding("UTF-8"); - - response.getWriter().write(text()); - response.getWriter().flush(); - response.getWriter().close(); - } catch (IOException ioe) { - throw new TropoException("An error happened while rendering response", ioe); - } - } - - public boolean isEmpty() { - - return super.isEmpty(); - } - - @SuppressWarnings("unchecked") - public TropoLaunchResult launchSession(String token) { - - return launchSession(token, Collections.EMPTY_MAP); - } - - public TropoLaunchResult launchSession(String token, Map params) { - - SessionLauncher launcher = new SessionLauncher(); - return launcher.launchSession(baseUrl, token, params); - } - - public String getBaseUrl() { - return baseUrl; - } - - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; - } + + private TropoParser parser; + private String baseUrl = "https://api.tropo.com/v1/"; + + private ActionSupportHandler sayActionSupportHandler = new ActionSupportHandler(SayAction.class); + private ActionSupportHandler askActionSupportHandler = new ActionSupportHandler(AskAction.class); + private ActionSupportHandler conferenceActionSupportHandler = new ActionSupportHandler(ConferenceAction.class); + private ActionSupportHandler choicesActionSupportHandler = new ActionSupportHandler(ChoicesAction.class); + private ActionSupportHandler onActionSupportHandler = new ActionSupportHandler(OnAction.class); + private ActionSupportHandler recordActionSupportHandler = new ActionSupportHandler(RecordAction.class); + private ActionSupportHandler redirectActionSupportHandler = new ActionSupportHandler(RedirectAction.class); + private ActionSupportHandler startRecordingActionSupportHandler = new ActionSupportHandler(StartRecordingAction.class); + private ActionSupportHandler transferActionSupportHandler = new ActionSupportHandler(TransferAction.class); + private ActionSupportHandler callActionSupportHandler = new ActionSupportHandler(CallAction.class); + private ActionSupportHandler messageActionSupportHandler = new ActionSupportHandler(MessageAction.class); + private ActionSupportHandler waitActionSupportHandler = new ActionSupportHandler(WaitAction.class); + private ActionSupportHandler answerActionSupportHandler = new ActionSupportHandler(AnswerAction.class); + + public Tropo() { + + super("tropo"); + parser = new TropoParser(); + } + + public SayAction say(String text) { + + return say(Key.VALUE(text)); + } + + public SayAction say(String text, String name) { + + return say(Key.VALUE(text), Key.NAME(name)); + } + + public SayAction say(Key... keys) { + + return sayActionSupportHandler.build(this, "tropo", keys); + } + + public AskAction ask(Key... keys) { + + return askActionSupportHandler.build(this, "tropo", keys); + } + + /** + * @deprecated A choices and a say are required. + * @see Tropo#ask(Key...) + * @since 0.4.6 + */ + @Deprecated + public AskAction ask(String name, Boolean bargein, Float timeout, Boolean required) { + + return ask(NAME(name), BARGEIN(bargein), TIMEOUT(timeout), REQUIRED(required)); + } + + /** + * @deprecated A choices and a say are required. + * @see Tropo#ask(Key...) + * @since 0.4.6 + */ + @Deprecated + public AskAction ask(String name, Boolean bargein, Float timeout, Float sensitivity, Boolean required) { + + return ask(NAME(name), BARGEIN(bargein), TIMEOUT(timeout), SENSITIVITY(sensitivity), REQUIRED(required)); + } + + public ChoicesAction choices(Key... keys) { + + return choicesActionSupportHandler.build(this, "tropo", keys); + } + + public ConferenceAction conference(Key... keys) { + + return conferenceActionSupportHandler.build(this, "tropo", keys); + } + + public OnAction on(Key... keys) { + + return onActionSupportHandler.build(this, "tropo", keys); + } + + /** + * @deprecated A say is required. + * @see Tropo#on(Key...) + * @since 0.4.8 + */ + @Deprecated + public OnAction on(String event, String next) { + + return on(EVENT(event), NEXT(next)); + } + + public RecordAction record(Key... keys) { + + return recordActionSupportHandler.build(this, "tropo", keys); + } + + /** + * @deprecated A sendTones and a exitTone are invalid. + * @see Tropo#record(String, String, Boolean) + * @since 0.4.8 + */ + @Deprecated + public RecordAction record(String name, String url, Boolean beep, Boolean sendTones, String exitTone) { + + return record(NAME(name), URL(url), BEEP(beep), SEND_TONES(sendTones), EXIT_TONE(exitTone)); + } + + public RecordAction record(String url, Boolean beep) { + + return record(URL(url), BEEP(beep)); + } + + public RecordAction record(String name, String url, Boolean beep) { + + return record(NAME(name), URL(url), BEEP(beep)); + } + + public RedirectAction redirect(Key... keys) { + + return redirectActionSupportHandler.build(this, "tropo", keys); + } + + /** + * @deprecated A name is invalid. + * @see Tropo#redirect(Key...) + * @since 0.4.8 + */ + @Deprecated + public RedirectAction redirect(String to) { + + return redirect(TO(to)); + } + + /** + * @deprecated A name is invalid. + * @see Tropo#redirect(Key...) + * @since 0.4.8 + */ + @Deprecated + public RedirectAction redirect(String to, String from) { + + return redirect(TO(to), FROM(from)); + } + + public StartRecordingAction startRecording(Key... keys) { + + return startRecordingActionSupportHandler.build(this, "tropo", keys); + } + + public StartRecordingAction startRecording(String url) { + + return startRecording(URL(url)); + } + + public StartRecordingAction startRecording(String url, Format format) { + + return startRecording(URL(url), FORMAT(format)); + } + + public StartRecordingAction startRecording(String url, Format format, String username, String password) { + + return startRecording(URL(url), FORMAT(format), USERNAME(username), PASSWORD(password)); + } + + public void hangup(Key... key) { + + addNull("tropo", "hangup"); + } + + public void stopRecording(Key... key) { + + addNull("tropo", "stopRecording"); + } + + public void reject(Key... key) { + + addNull("tropo", "reject"); + } + + public TransferAction transfer(Key... keys) { + + return transferActionSupportHandler.build(this, "tropo", keys); + } + + public TransferAction transfer(String to) { + + return transfer(Key.TO(to)); + } + + public TransferAction transfer(String to, String name) { + + return transfer(Key.TO(to), Key.NAME(name)); + } + + public TransferAction transfer(String to, String from, String name) { + + return transfer(Key.TO(to), Key.FROM(from), Key.NAME(name)); + } + + public CallAction call(Key... keys) { + + return callActionSupportHandler.build(this, "tropo", keys); + } + + public CallAction call(String to) { + + return call(TO(to)); + } + + public CallAction call(String name, String to) { + + return call(NAME(name), TO(to)); + } + + public CallAction call(String to, Network network) { + + return call(TO(to), NETWORK(network)); + } + + public CallAction call(String name, String to, Network network) { + + return call(NAME(name), TO(to), NETWORK(network)); + } + + public CallAction call(String to, Network network, String from) { + + return call(TO(to), NETWORK(network), FROM(from)); + } + + public CallAction call(String name, String to, Network network, String from) { + + return call(NAME(name), TO(to), NETWORK(network), FROM(from)); + } + + public CallAction call(String to, Network network, String from, Channel channel) { + + return call(TO(to), NETWORK(network), FROM(from), CHANNEL(channel)); + } + + public CallAction call(String name, String to, Network network, String from, Channel channel) { + + return call(NAME(name), TO(to), NETWORK(network), FROM(from), CHANNEL(channel)); + } + + public MessageAction message(Key... keys) { + + return messageActionSupportHandler.build(this, "tropo", keys); + } + + /** + * @deprecated A say and a name are required. + * @see Tropo#message(Key...) + * @since 0.4.7 + */ + @Deprecated + public MessageAction message(String to) { + + return message(TO(to)); + } + + /** + * @deprecated A say and a name are required. + * @see Tropo#message(Key...) + * @since 0.4.7 + */ + @Deprecated + public MessageAction message(String to, Network network) { + + return message(TO(to), NETWORK(network)); + } + + /** + * @deprecated A say and a name are required. + * @see Tropo#message(Key...) + * @since 0.4.7 + */ + @Deprecated + public MessageAction message(String to, Network network, String from) { + + return message(TO(to), NETWORK(network), FROM(from)); + } + + /** + * @deprecated A say and a name are required. + * @see Tropo#message(Key...) + * @since 0.4.7 + */ + @Deprecated + public MessageAction message(String to, Network network, String from, Channel channel) { + + return message(TO(to), NETWORK(network), FROM(from), CHANNEL(channel)); + } + + public WaitAction serverWait(Long milliseconds) { + + return serverWait(MILLISECONDS(milliseconds)); + } + + public WaitAction serverWait(Key... keys){ + return waitActionSupportHandler.build(this, "tropo", keys); + } + + public TropoResult parse(String json) { + + return parser.parse(json); + } + + public TropoSession session(String json) { + + return parser.session(json); + } + + public TropoResult parse(HttpServletRequest request) { + + return parser.parse(request); + } + + public TropoSession session(HttpServletRequest request) { + + return parser.session(request); + } + + public void render(HttpServletResponse response) { + + render(response, text()); + } + + public void render(HttpServletResponse response, String json) { + + try { + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + response.addHeader("WebAPI-Lang-Ver", "Java V15.9.0 SNAPSHOT"); + + response.getWriter().write(text()); + response.getWriter().flush(); + response.getWriter().close(); + } catch (IOException ioe) { + throw new TropoException("An error happened while rendering response", ioe); + } + } + + public boolean isEmpty() { + + return super.isEmpty(); + } + + @SuppressWarnings("unchecked") + public TropoLaunchResult launchSession(String token) { + + return launchSession(token, Collections.EMPTY_MAP); + } + + public TropoLaunchResult launchSession(String token, Map params) { + + SessionLauncher launcher = new SessionLauncher(); + return launcher.launchSession(baseUrl, token, params); + } + + public TropoLaunchResult launchSession(String token, Map params, HttpClient httpClient) { + SessionLauncher launcher = new SessionLauncher(httpClient); + return launcher.launchSession(baseUrl, token, params); + } + + public void generalLogSecurity(LogSecurityState value) { + + addObject("tropo", "generalLogSecurity", value.toString()); + } + + public AnswerAction answer(Key... keys) { + + return answerActionSupportHandler.build(this, "tropo", keys); + } + + public String getBaseUrl() { + return baseUrl; + } + + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + } } diff --git a/src/main/java/com/voxeo/tropo/TropoEntity.java b/src/main/java/com/voxeo/tropo/TropoEntity.java index 35578d9..aad2b1e 100644 --- a/src/main/java/com/voxeo/tropo/TropoEntity.java +++ b/src/main/java/com/voxeo/tropo/TropoEntity.java @@ -10,6 +10,7 @@ public class TropoEntity implements Serializable { private String name; private String channel; private String network; + private String e164Id; public String getId() { return id; @@ -35,4 +36,15 @@ public String getNetwork() { public void setNetwork(String network) { this.network = network; } + public String getE164Id() { + return e164Id; + } + public void setE164Id(String e164Id) { + this.e164Id = e164Id; + } + + @Override + public String toString(){ + return TropoUtils.toPrettyString(this); + } } diff --git a/src/main/java/com/voxeo/tropo/TropoLaunchResult.java b/src/main/java/com/voxeo/tropo/TropoLaunchResult.java index e9b582e..32262b6 100644 --- a/src/main/java/com/voxeo/tropo/TropoLaunchResult.java +++ b/src/main/java/com/voxeo/tropo/TropoLaunchResult.java @@ -10,7 +10,7 @@ public class TropoLaunchResult implements Serializable { private String token; private String id; - public Boolean getSuccess() { + public Boolean isSuccess() { return success; } public void setSuccess(Boolean success) { @@ -29,5 +29,8 @@ public void setId(String id) { this.id = id; } - + @Override + public String toString(){ + return TropoUtils.toPrettyString(this); + } } diff --git a/src/main/java/com/voxeo/tropo/TropoParser.java b/src/main/java/com/voxeo/tropo/TropoParser.java index 780169f..c11929d 100644 --- a/src/main/java/com/voxeo/tropo/TropoParser.java +++ b/src/main/java/com/voxeo/tropo/TropoParser.java @@ -3,146 +3,132 @@ import java.io.IOException; import java.io.Reader; import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; import javax.servlet.http.HttpServletRequest; -import net.sf.ezmorph.Morpher; -import net.sf.ezmorph.MorpherRegistry; -import net.sf.ezmorph.bean.BeanMorpher; -import net.sf.json.JSONArray; -import net.sf.json.JSONObject; -import net.sf.json.util.JSONUtils; +import com.google.gson.Gson; +import com.google.gson.JsonObject; -@SuppressWarnings("rawtypes") public class TropoParser { - - public TropoSession session(String text) throws TropoException { - - JSONObject json = JSONObject.fromObject(text).getJSONObject("session"); - TropoSession session = (TropoSession) JSONObject.toBean( json, TropoSession.class); - - return session; - } - - public TropoLaunchResult sessionLaunch(String text) throws TropoException { - - if (!text.startsWith("{")) { - text = jsonize(text); - } - - JSONObject json = JSONObject.fromObject(text); - TropoLaunchResult sessionLaunch = (TropoLaunchResult) JSONObject.toBean( json, TropoLaunchResult.class); - - return sessionLaunch; - } - - private String jsonize(String text) { - - // For some reason the server returns A=1&B=2&... although the API states it sould return JSON - text = text.replaceAll("\\n",""); - text = text.replaceAll("\\t",""); - text = text.replaceAll("\\r",""); - StringBuilder json = new StringBuilder("{"); - String[] elements = text.split("&"); - int i=1; - for (String element: elements) { - String[] entry = element.split("="); - json.append(String.format("\"%s\":\"%s\"",entry[0],entry[1])); - if (!(i == elements.length)) { - json.append(","); - } - i++; - } - json.append("}"); - - return json.toString(); - } - - @SuppressWarnings("unchecked") - public TropoResult parse(String text) throws TropoException { - - try { - JSONObject json = JSONObject.fromObject(text).getJSONObject("result"); - - if (json.get("actions") instanceof JSONArray) { - Map classMap = new HashMap(); - classMap.put( "actions", ActionResult.class ); - TropoResult result = (TropoResult) JSONObject.toBean( json, TropoResult.class, classMap); - - MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry(); - Morpher dynaMorpher = new BeanMorpher( ActionResult.class, morpherRegistry ); - morpherRegistry.registerMorpher( dynaMorpher ); - ArrayList output = new ArrayList(); - for (ActionResult action: result.getActions()) { - output.add((ActionResult)morpherRegistry.morph(ActionResult.class,action)); - } - result.setActions(output); - return result; - } else { - TropoResult result = (TropoResult) JSONObject.toBean( json, TropoResult.class); - ActionResult actionResult = (ActionResult) JSONObject.toBean(json.getJSONObject("actions") , ActionResult.class); - ArrayList actions = new ArrayList(); - actions.add(actionResult); - result.setActions(actions); - return result; - } - } catch (Exception e) { - throw new TropoException(e); - } - } - - public Map parse(Map map) { - - return JSONObject.fromObject(map); - } - - public TropoResult parse(HttpServletRequest request) { - - try { - return parse(request.getReader()); - } catch (IOException e) { - throw new TropoException("Could not get reader from HTTP Request", e); - } - } - - public TropoSession session(HttpServletRequest request) { - - try { - return session(request.getReader()); - } catch (IOException e) { - throw new TropoException("Could not get reader from HTTP Request", e); - } - } - - public TropoLaunchResult sessionLaunch(HttpServletRequest request) { - - try { - return sessionLaunch(request.getReader()); - } catch (IOException e) { - throw new TropoException("Could not get reader from HTTP Request", e); - } - } - - public TropoResult parse(Reader reader) { - - return parse(getRequestBody(reader)); - } - - public TropoSession session(Reader reader) { - - return session(getRequestBody(reader)); - } - - public TropoLaunchResult sessionLaunch(Reader reader) { - - return sessionLaunch(getRequestBody(reader)); - } - - private String getRequestBody(Reader reader) { - - return IOUtils.read(reader); - } - + + public TropoSession session(String text) throws TropoException { + + Gson gson = new Gson(); + JsonObject json = gson.fromJson(text, JsonObject.class).getAsJsonObject("session"); + TropoSession session = gson.fromJson(json, TropoSession.class); + return session; + } + + public TropoLaunchResult sessionLaunch(String text) throws TropoException { + + if (!text.startsWith("{")) { + text = jsonize(text); + } + + return new Gson().fromJson(text, TropoLaunchResult.class); + } + + private String jsonize(String text) { + + // For some reason the server returns A=1&B=2&... although the API states it sould + // return JSON + text = text.replaceAll("\\n", ""); + text = text.replaceAll("\\t", ""); + text = text.replaceAll("\\r", ""); + StringBuilder json = new StringBuilder("{"); + String[] elements = text.split("&"); + int i = 1; + for (String element : elements) { + String[] entry = element.split("="); + json.append(String.format("\"%s\":\"%s\"", entry[0], entry[1])); + if (!(i == elements.length)) { + json.append(","); + } + i++; + } + json.append("}"); + + return json.toString(); + } + + public TropoResult parse(String text) throws TropoException { + + try { + Gson gson = new Gson(); + JsonObject json = gson.fromJson(text, JsonObject.class).getAsJsonObject("result"); + + // actions may be an object or array, if it is an object, + // we need to add this object into an array + if (json.get("actions") instanceof JsonObject) { + + ActionResult actionResult = gson.fromJson(json.get("actions"), ActionResult.class); + ArrayList actions = new ArrayList(); + actions.add(actionResult); + + // removing actions as it will cause error, while mapping to bean + json.remove("actions"); + TropoResult result = gson.fromJson(json, TropoResult.class); + result.setActions(actions); + return result; + } + else { + return gson.fromJson(json, TropoResult.class); + } + + } + catch (Exception e) { + throw new TropoException(e); + } + } + + public TropoResult parse(HttpServletRequest request) { + + try { + return parse(request.getReader()); + } + catch (IOException e) { + throw new TropoException("Could not get reader from HTTP Request", e); + } + } + + public TropoSession session(HttpServletRequest request) { + + try { + return session(request.getReader()); + } + catch (IOException e) { + throw new TropoException("Could not get reader from HTTP Request", e); + } + } + + public TropoLaunchResult sessionLaunch(HttpServletRequest request) { + + try { + return sessionLaunch(request.getReader()); + } + catch (IOException e) { + throw new TropoException("Could not get reader from HTTP Request", e); + } + } + + public TropoResult parse(Reader reader) { + + return parse(getRequestBody(reader)); + } + + public TropoSession session(Reader reader) { + + return session(getRequestBody(reader)); + } + + public TropoLaunchResult sessionLaunch(Reader reader) { + + return sessionLaunch(getRequestBody(reader)); + } + + private String getRequestBody(Reader reader) { + + return IOUtils.read(reader); + } + } diff --git a/src/main/java/com/voxeo/tropo/TropoResult.java b/src/main/java/com/voxeo/tropo/TropoResult.java index 8c93ec7..99d4f8a 100644 --- a/src/main/java/com/voxeo/tropo/TropoResult.java +++ b/src/main/java/com/voxeo/tropo/TropoResult.java @@ -3,6 +3,8 @@ import java.io.Serializable; import java.util.ArrayList; +import com.google.gson.annotations.SerializedName; + public class TropoResult implements Serializable { private static final long serialVersionUID = 7944603295887403063L; @@ -14,7 +16,12 @@ public class TropoResult implements Serializable { private Integer sequence; private Integer sessionDuration; private String sessionId; - private String callState; + private String state; + private String callId; + + @SerializedName("calledid") + private String calledId; + private String userType; public ArrayList getActions() { @@ -23,7 +30,7 @@ public ArrayList getActions() { public void setActions(ArrayList actions) { this.actions = actions; } - public Boolean getComplete() { + public Boolean isComplete() { return complete; } public void setComplete(Boolean complete) { @@ -53,10 +60,34 @@ public String getSessionId() { public void setSessionId(String sessionId) { this.sessionId = sessionId; } - public String getCallState() { - return callState; + public String getState() { + return state; + } + public void setState(String state) { + this.state = state; } - public void setCallState(String state) { - this.callState = state; - } + + public String getCallId() { + return callId; + } + public void setCallId(String callId) { + this.callId = callId; + } + public String getCalledId() { + return calledId; + } + public void setCalledId(String calledid) { + this.calledId = calledid; + } + + public String getUserType() { + return userType; + } + public void setUserType(String userType) { + this.userType = userType; + } + @Override + public String toString(){ + return TropoUtils.toPrettyString(this); + } } diff --git a/src/main/java/com/voxeo/tropo/TropoSession.java b/src/main/java/com/voxeo/tropo/TropoSession.java index 0a2faa5..b4ab791 100644 --- a/src/main/java/com/voxeo/tropo/TropoSession.java +++ b/src/main/java/com/voxeo/tropo/TropoSession.java @@ -2,6 +2,7 @@ import java.io.Serializable; import java.util.HashMap; +import java.util.List; public class TropoSession implements Serializable { @@ -18,6 +19,10 @@ public class TropoSession implements Serializable { private HashMap headers; private HashMap parameters; + + private String subject; + + private List initialMedia; public String getAccountId() { return accountId; @@ -79,4 +84,21 @@ public TropoEntity getFrom() { public void setFrom(TropoEntity from) { this.from = from; } + + public String getSubject() { + return subject; + } + public void setSubject(String subject) { + this.subject = subject; + } + public List getInitialMedia() { + return initialMedia; + } + public void setInitialMedia(List initialMedia) { + this.initialMedia = initialMedia; + } + @Override + public String toString(){ + return TropoUtils.toPrettyString(this); + } } diff --git a/src/main/java/com/voxeo/tropo/TropoUtils.java b/src/main/java/com/voxeo/tropo/TropoUtils.java new file mode 100644 index 0000000..312314e --- /dev/null +++ b/src/main/java/com/voxeo/tropo/TropoUtils.java @@ -0,0 +1,15 @@ +package com.voxeo.tropo; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class TropoUtils { + + public static String toPrettyString(Object instance) { + + GsonBuilder builder = new GsonBuilder(); + builder.setPrettyPrinting().disableHtmlEscaping().serializeNulls(); + Gson gson = builder.create(); + return gson.toJson(instance); + } +} diff --git a/src/main/java/com/voxeo/tropo/actions/Action.java b/src/main/java/com/voxeo/tropo/actions/Action.java index 2b30d1c..c5a05ac 100644 --- a/src/main/java/com/voxeo/tropo/actions/Action.java +++ b/src/main/java/com/voxeo/tropo/actions/Action.java @@ -4,165 +4,170 @@ import java.util.Collections; import java.util.List; -import net.sf.json.JSON; -import net.sf.json.JSONArray; -import net.sf.json.JSONObject; - +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import com.voxeo.tropo.Key; import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; public abstract class Action { + + private JsonElement node; + private String name; + private Action parent; + + protected Action(JsonElement node) { + + this.node = node; + } + + protected JsonElement getNode() { + + return node; + } + + protected void setNode(JsonElement node) { + + this.node = node; + } + + JsonObject getJSONObject(String key) { + + if (!node.isJsonArray()) { + return ((JsonObject) node).getAsJsonObject(key); + } + return null; + } + + JsonArray getJSONArray(String key) { + + if (!node.isJsonArray()) { + return ((JsonObject) node).getAsJsonArray(key); + } + return null; + } + + public void addToArray(String arrayName, String key, Action action) { + + addToArray(getJSONArray(arrayName), key, action); + } + + protected void addToArray(JsonArray array, String key, Action action) { + + action.validate(); + JsonObject node = new JsonObject(); + node.add(key, action.json()); + + array.add(node); + action.node = array.get(array.size()-1).getAsJsonObject().get(key); + } + + protected void addNull(String arrayName, String key) { + + JsonArray array = getJSONArray(arrayName); + JsonObject node = new JsonObject(); + node.add(key, null); + array.add(node); + } - private JSON node; - private String name; - private Action parent; - - protected Action(JSON node) { - - this.node = node; - } - - protected JSON getNode() { - - return node; - } - - protected void setNode(JSON node) { - - this.node = node; - } - - JSONObject getJSONObject(String key) { - - if (!node.isArray()) { - return ((JSONObject)node).getJSONObject(key); - } - return null; - } - - JSONArray getJSONArray(String key) { - - if (!node.isArray()) { - return ((JSONObject)node).getJSONArray(key); - } - return null; - } - - public void addToArray(String arrayName, String key, Action action) { - - addToArray(getJSONArray(arrayName),key,action); - } - - protected void addToArray(JSONArray array, String key, Action action) { - - action.validate(); - JSONObject node = new JSONObject(); - node.put(key,action.json()); - - array.element(node); - // Element, creates a copy. If we want to keep an updatable reference we need to update the ref. link - JSON addedNode = (JSON)array.getJSONObject((array.size()-1)).get(key); - action.node = addedNode; - } - - protected void addNull(String arrayName, String key) { - - JSONArray array = getJSONArray(arrayName); - JSONObject node = new JSONObject(); - node.put(key,"null"); - - array.element(node); - } - - public Action and(Action... actions) { - - validate(); - for (Action action: actions) { - while (action.getParent() != null) { - action = action.getParent(); // Nested actions support, e.j. and(on(...).say(...),...) - } - action.setParent(this); - action.validate(); - accumulate(action.getName(),action); - } - return this; - } - - public abstract void put(String key, Action value); - protected abstract void accumulate(String key, Action value); - public abstract void reset(); - protected abstract void validate(); - - public JSON json() { - - return node; - } - - public String text() { + protected void addObject(String arrayName, String objectName, String objectValue) { - String text = node.toString(); - // See Key.CHOICES to know more about this required change - text = text.replace("$[$", "["); - text = text.replace("${$", "{"); - //System.out.println(text); - return text; - } - - protected boolean isValidKey(Key key) { - - List keys = getValidKeys(); - if (keys.isEmpty()) { - return true; - } - return keys.contains(key.getName()); - } - - @SuppressWarnings("unchecked") - private List getValidKeys() { - - ValidKeys validKeysAnnotation = getClass().getAnnotation(ValidKeys.class); - if (validKeysAnnotation != null && validKeysAnnotation.keys() != null) { - return Arrays.asList(validKeysAnnotation.keys()); - } else { - return Collections.EMPTY_LIST; - } - } - - @SuppressWarnings("unchecked") - protected List getRequiredKeys() { - - RequiredKeys requiredKeysAnnotation = getClass().getAnnotation(RequiredKeys.class); - if (requiredKeysAnnotation != null && requiredKeysAnnotation.keys() != null) { - return Arrays.asList(requiredKeysAnnotation.keys()); - } else { - return Collections.EMPTY_LIST; - } - } - - @Override - public String toString() { + JsonArray array = getJSONArray(arrayName); + JsonObject node = new JsonObject(); + node.addProperty(objectName, objectValue); + array.add(node); + } - return text(); - } - - protected void setName(String name) { - - this.name = name; - } - - public String getName() { - - return name; - } - - protected Action getParent() { - - return parent; - } - - protected void setParent(Action parent) { - - this.parent = parent; - } + public Action and(Action... actions) { + + validate(); + for (Action action : actions) { + while (action.getParent() != null) { + action = action.getParent(); + // Nested actions support, e.j. and(on(...).say(...),...) + } + action.setParent(this); + action.validate(); + accumulate(action.getName(), action); + } + return this; + } + + public abstract void put(String key, Action value); + + protected abstract void accumulate(String key, Action value); + + public abstract void reset(); + + protected abstract void validate(); + + public JsonElement json() { + + return node; + } + + public String text() { + + return node.toString(); + } + + protected boolean isValidKey(Key key) { + + List keys = getValidKeys(); + if (keys.isEmpty()) { + return true; + } + return keys.contains(key.getName()); + } + + @SuppressWarnings("unchecked") + private List getValidKeys() { + + ValidKeys validKeysAnnotation = getClass().getAnnotation(ValidKeys.class); + if (validKeysAnnotation != null && validKeysAnnotation.keys() != null) { + return Arrays.asList(validKeysAnnotation.keys()); + } + else { + return Collections.EMPTY_LIST; + } + } + + @SuppressWarnings("unchecked") + protected List getRequiredKeys() { + + RequiredKeys requiredKeysAnnotation = getClass().getAnnotation(RequiredKeys.class); + if (requiredKeysAnnotation != null && requiredKeysAnnotation.keys() != null) { + return Arrays.asList(requiredKeysAnnotation.keys()); + } + else { + return Collections.EMPTY_LIST; + } + } + + @Override + public String toString() { + + return text(); + } + + protected void setName(String name) { + + this.name = name; + } + + public String getName() { + + return name; + } + + protected Action getParent() { + + return parent; + } + + protected void setParent(Action parent) { + + this.parent = parent; + } } diff --git a/src/main/java/com/voxeo/tropo/actions/AnswerAction.java b/src/main/java/com/voxeo/tropo/actions/AnswerAction.java new file mode 100644 index 0000000..40dc06b --- /dev/null +++ b/src/main/java/com/voxeo/tropo/actions/AnswerAction.java @@ -0,0 +1,29 @@ +package com.voxeo.tropo.actions; + +import com.voxeo.tropo.Key; +import com.voxeo.tropo.annotations.ValidKeys; + +import support.HeadersSupportHandler; + +@ValidKeys(keys = {"headers"}) +public class AnswerAction extends JsonAction { + + private HeadersSupportHandler headersSupportHandler = new HeadersSupportHandler(); + + public AnswerAction() { + + super(); + setName("answer"); + } + + public AnswerAction(Key... keys) { + + super(keys); + setName("answer"); + } + + public HeadersAction headers(String[]... keys) { + + return headersSupportHandler.headers(this, keys); + } +} diff --git a/src/main/java/com/voxeo/tropo/actions/ArrayAction.java b/src/main/java/com/voxeo/tropo/actions/ArrayAction.java index 367cda7..0bf0a5d 100644 --- a/src/main/java/com/voxeo/tropo/actions/ArrayAction.java +++ b/src/main/java/com/voxeo/tropo/actions/ArrayAction.java @@ -2,10 +2,10 @@ import java.util.Iterator; -import net.sf.json.JSON; -import net.sf.json.JSONArray; -import net.sf.json.JSONObject; - +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import com.voxeo.tropo.Key; import com.voxeo.tropo.TropoException; @@ -13,7 +13,7 @@ public abstract class ArrayAction extends Action { public ArrayAction() { - super(new JSONArray()); + super(new JsonArray()); } public ArrayAction(Key... keys) { @@ -25,24 +25,43 @@ public ArrayAction(Key... keys) { @Override public void reset() { - setNode(new JSONArray()); + setNode(new JsonArray()); } - protected JSONObject buildObjectFromKeys(Key... keys) { + protected JsonObject buildObjectFromKeys(Key... keys) { - JSONObject object = new JSONObject(); + JsonObject object = new JsonObject(); for(Key key: keys) { if (!isValidKey(key)) { throw new TropoException(String.format("Invalid key '%s' for action",key.getName())); } - object.put(key.getName(), key.getValue()); + putProperty(object, key.getName(), key.getValue()); } return object; } - protected void add(JSON item) { + protected void putProperty(JsonObject object, String key, Object value) { + + if (value instanceof Boolean) { + object.addProperty(key, (Boolean) value); + } + else if (value instanceof Number) { + object.addProperty(key, (Number) value); + } + else if (value instanceof Character) { + object.addProperty(key, (Character) value); + } + else if (value instanceof String) { + object.addProperty(key, (String) value); + } + else { + object.add(key, new Gson().toJsonTree(value)); + } + } + + protected void add(JsonElement item) { - ((JSONArray)getNode()).element(item); + ((JsonArray)getNode()).add(item); } public void put(String key, Action action) { @@ -54,12 +73,12 @@ protected void append(String key, Action action) { action.validate(); action.setParent(this); - JSONArray array = ((JSONArray)getNode()); + JsonArray array = ((JsonArray)getNode()); if (array.size() == 0) { addToArray(array, key, action); } else { - JSONObject node = (JSONObject)array.get(array.size()-1); - node.put(key,action.json()); + JsonObject node = (JsonObject)array.get(array.size()-1); + node.add(key,action.json()); } } @@ -73,13 +92,13 @@ protected void accumulate(String key, Action value) { @SuppressWarnings("rawtypes") private void checkFields(String... fields) throws TropoException { - JSONArray array = ((JSONArray)getNode()); + JsonArray array = ((JsonArray)getNode()); Iterator it = array.iterator(); while (it.hasNext()) { Object element = it.next(); - if (element instanceof JSONObject) { + if (element instanceof JsonObject) { for (String field: fields) { - Object value = ((JSONObject)element).get(field); + Object value = ((JsonObject)element).get(field); if (value == null) { throw new TropoException(String.format("Missing required property: '%s'",field)); } diff --git a/src/main/java/com/voxeo/tropo/actions/ArrayBackedJsonAction.java b/src/main/java/com/voxeo/tropo/actions/ArrayBackedJsonAction.java index 3b5bb25..c141f8e 100644 --- a/src/main/java/com/voxeo/tropo/actions/ArrayBackedJsonAction.java +++ b/src/main/java/com/voxeo/tropo/actions/ArrayBackedJsonAction.java @@ -1,33 +1,32 @@ package com.voxeo.tropo.actions; -import net.sf.json.JSONArray; +import com.google.gson.JsonArray; public abstract class ArrayBackedJsonAction extends JsonAction { - - public ArrayBackedJsonAction(String name) { - - super(); - setName(name); - put(name, new JSONArray()); - } - - @Override - public void reset() { - - super.reset(); - put(getName(), new JSONArray()); - } - - - @Override - protected void accumulate(String key, Action value) { - - addToArray(getName(), key, value); - } - - protected boolean isEmpty() { - - JSONArray array = getJSONArray(getName()); - return array.isEmpty(); - } + + public ArrayBackedJsonAction(String name) { + + super(); + setName(name); + put(getName(), new JsonArray()); + } + + @Override + public void reset() { + + super.reset(); + put(getName(), new JsonArray()); + } + + @Override + protected void accumulate(String key, Action value) { + + addToArray(getName(), key, value); + } + + protected boolean isEmpty() { + + JsonArray array = getJSONArray(getName()); + return array.size() == 0; + } } diff --git a/src/main/java/com/voxeo/tropo/actions/AskAction.java b/src/main/java/com/voxeo/tropo/actions/AskAction.java index e72581d..3f8e6b4 100644 --- a/src/main/java/com/voxeo/tropo/actions/AskAction.java +++ b/src/main/java/com/voxeo/tropo/actions/AskAction.java @@ -3,61 +3,240 @@ import static com.voxeo.tropo.Key.EVENT; import static com.voxeo.tropo.Key.NEXT; import static com.voxeo.tropo.Key.VALUE; -import support.ActionSupportHandler; import com.voxeo.tropo.Key; +import com.voxeo.tropo.TropoException; import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; +import com.voxeo.tropo.enums.As; +import com.voxeo.tropo.enums.Mode; +import com.voxeo.tropo.enums.Voice; +import support.ActionSupportHandler; -@ValidKeys(keys={"name","text","mode","required","choices","allowSignals","attempts","bargein","minConfidence","recognizer","terminator","timeout","voice","interdigitTimeout"}) -@RequiredKeys(keys={"name"}) +@ValidKeys(keys = { "name", "required", "choices", "allowSignals", "attempts", "bargein", "minConfidence", "recognizer", "timeout", "sensitivity", "voice", + "interdigitTimeout", "say", "speechCompleteTimeout", "speechIncompleteTimeout", "promptLogSecurity", "asrLogSecurity", "maskTemplate" }) +@RequiredKeys(keys = { "choices", "say" }) public class AskAction extends JsonAction { - private ActionSupportHandler sayActionSupportHandler = new ActionSupportHandler(SayAction.class); - private ActionSupportHandler choicesActionSupportHandler = new ActionSupportHandler(ChoicesAction.class); - private ActionSupportHandler onActionSupportHandler = new ActionSupportHandler(NestedOnAction.class); - - public AskAction() { - - super(); - setName("ask"); - } - - public AskAction(Key... keys) { - - super(keys); - setName("ask"); - } - - public SayAction say(String text) { - - return say(VALUE(text)); - } - - public SayAction say(Key... keys) { - - return sayActionSupportHandler.build(this,keys); - } - - public NestedOnAction on(Key... keys) { - - return onActionSupportHandler.build(this,keys); - } - - public NestedOnAction on(String event, String next) { - - return on(EVENT(event), NEXT(next)); - } - - public ChoicesAction choices(Key... keys) { - - return choicesActionSupportHandler.build(this,keys); - } - - public AskAction choices(String choice) { - - choices(VALUE(choice)); - return this; - } + private ActionSupportHandler sayActionSupportHandler = new ActionSupportHandler(SayAction.class); + private ActionSupportHandler choicesActionSupportHandler = new ActionSupportHandler(ChoicesAction.class); + private ActionSupportHandler onActionSupportHandler = new ActionSupportHandler(NestedOnAction.class); + + public AskAction() { + + super(); + setName("ask"); + } + + public AskAction(Key... keys) { + + super(keys); + setName("ask"); + } + + public SayAction say(String text) { + + return say(VALUE(text)); + } + + public SayAction say(Key... keys) { + + return sayActionSupportHandler.build(this, keys); + } + + public NestedOnAction on(Key... keys) { + + return onActionSupportHandler.build(this, keys); + } + + public NestedOnAction on(String event, String next) { + + return on(EVENT(event), NEXT(next)); + } + + public ChoicesAction choices(Key... keys) { + + return choicesActionSupportHandler.build(this, keys); + } + + public AskAction choices(String choice) { + + choices(VALUE(choice)); + return this; + } + + public static class Choices { + + public Choices(String value) { + this(value, null, null); + } + + public Choices(String value, Mode mode) { + this(value, mode, null); + } + + public Choices(String value, Mode mode, String terminator) { + if (value == null || value.trim().equals("")) { + throw new TropoException("Missing required property: value of Choices"); + } else { + this.value = value; + } + + this.mode = mode; + + if (!(terminator == null || terminator.trim().equals(""))) { + this.terminator = terminator; + } + } + + private String value; + + private Mode mode; + + private String terminator; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public Mode getMode() { + return mode; + } + + public void setMode(Mode mode) { + this.mode = mode; + } + + public String getTerminator() { + return terminator; + } + + public void setTerminator(String terminator) { + this.terminator = terminator; + } + } + + public static class Say { + + public Say(String value) { + this(value, null, null); + } + + private Say(String value, Voice voice) { + this(value, voice, null); + } + + public Say(String value, String event) { + this(value, null, event); + } + + private Say(String value, Voice voice, String event) { + this(value, null, null, null, null, voice, null, event); + } + + private Say(String value, String[] allowSignals, As as, String name, Boolean required, Voice voice, + String promptLogSecurity, String event) { + if (value == null || value.trim().equals("")) { + throw new TropoException("Missing required property: value of ask.say"); + } else { + this.value = value; + } + this.allowSignals = allowSignals; + this.as = as; + this.name = name; + this.required = required; + this.voice = voice; + if (promptLogSecurity != null && promptLogSecurity.trim().equalsIgnoreCase("suppress")) { + this.promptLogSecurity = "suppress"; + } + if (!(event == null || event.trim().equals(""))) { + this.event = event; + } + } + + private String value; + + private String[] allowSignals; + + private As as; + + private String name; + + private Boolean required; + + private Voice voice; + + private String promptLogSecurity; + + private String event; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String[] getAllowSignals() { + return allowSignals; + } + + public void setAllowSignals(String[] allowSignals) { + this.allowSignals = allowSignals; + } + + public As getAs() { + return as; + } + + public void setAs(As as) { + this.as = as; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Boolean getRequired() { + return required; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public Voice getVoice() { + return voice; + } + + public void setVoice(Voice voice) { + this.voice = voice; + } + + public String getPromptLogSecurity() { + return promptLogSecurity; + } + + public void setPromptLogSecurity(String promptLogSecurity) { + this.promptLogSecurity = promptLogSecurity; + } + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } + } } diff --git a/src/main/java/com/voxeo/tropo/actions/CallAction.java b/src/main/java/com/voxeo/tropo/actions/CallAction.java index 3049b9e..9eab982 100644 --- a/src/main/java/com/voxeo/tropo/actions/CallAction.java +++ b/src/main/java/com/voxeo/tropo/actions/CallAction.java @@ -7,32 +7,32 @@ import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; -@ValidKeys(keys={"to","allowSignals","answerOnMedia","channel","from","headers","name","network","recording","required","timeout"}) -@RequiredKeys(keys={"to"}) +@ValidKeys(keys = { "to", "allowSignals", "answerOnMedia", "channel", "from", "headers", "name", "network", "required", "timeout", "machineDetection", "voice", "callbackUrl", "promptLogSecurity", "label" }) +@RequiredKeys(keys = { "to" }) public class CallAction extends JsonAction { - private ActionSupportHandler startRecordingActionSupportHandler = new ActionSupportHandler(StartRecordingAction.class); - private HeadersSupportHandler headersSupportHandler = new HeadersSupportHandler(); - - public CallAction() { - - super(); - setName("call"); - } - - public CallAction(Key... keys) { - - super(keys); - setName("call"); - } - - public StartRecordingAction startRecording(Key... keys) { - - return startRecordingActionSupportHandler.build(this, keys); - } - - public HeadersAction headers(String[]... keys) { - - return headersSupportHandler.headers(this, keys); - } + private ActionSupportHandler startRecordingActionSupportHandler = new ActionSupportHandler(StartRecordingAction.class); + private HeadersSupportHandler headersSupportHandler = new HeadersSupportHandler(); + + public CallAction() { + + super(); + setName("call"); + } + + public CallAction(Key... keys) { + + super(keys); + setName("call"); + } + + public StartRecordingAction startRecording(Key... keys) { + + return startRecordingActionSupportHandler.build(this, keys); + } + + public HeadersAction headers(String[]... keys) { + + return headersSupportHandler.headers(this, keys); + } } diff --git a/src/main/java/com/voxeo/tropo/actions/ChoicesAction.java b/src/main/java/com/voxeo/tropo/actions/ChoicesAction.java index e82623b..2e54f09 100644 --- a/src/main/java/com/voxeo/tropo/actions/ChoicesAction.java +++ b/src/main/java/com/voxeo/tropo/actions/ChoicesAction.java @@ -3,8 +3,9 @@ import com.voxeo.tropo.Key; import com.voxeo.tropo.TropoException; import com.voxeo.tropo.annotations.ValidKeys; +import com.voxeo.tropo.enums.Mode; -@ValidKeys(keys={"value","mode"}) +@ValidKeys(keys={"value","mode","terminator"}) public class ChoicesAction extends JsonAction { public ChoicesAction() { @@ -25,9 +26,12 @@ protected void validate() throws TropoException { super.validate(); Object mode = get("mode"); if (mode != null) { - if (!mode.equals("dtmf") && !mode.equals("speech")) { - throw new TropoException("If mode is provided, only 'dtmf', 'speech' or 'any' is supported"); + for(Mode modeValue : Mode.values()) { + if(modeValue.toString().equals(mode)){ + return; + } } + throw new TropoException("If mode is provided, only 'dtmf', 'speech' or 'any' is supported"); } } } diff --git a/src/main/java/com/voxeo/tropo/actions/ConferenceAction.java b/src/main/java/com/voxeo/tropo/actions/ConferenceAction.java index 13e901d..ec143cb 100644 --- a/src/main/java/com/voxeo/tropo/actions/ConferenceAction.java +++ b/src/main/java/com/voxeo/tropo/actions/ConferenceAction.java @@ -8,7 +8,24 @@ import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; -@ValidKeys(keys={"name","allowSignals","mute","on","playTones","terminator","id","send_tones","exit_tone","interdigitTimeout"}) +/** + *

+ * Its allows multiple lines in separate sessions to be conferenced together so + * that the parties on each line can talk to each other simultaneously. This is + * a voice channel only feature. + *

+ *

+ * Any conference ID you use in production will be shared among all your + * production applications; likewise any development app conference IDs are + * shared among all your development apps. These IDs are not shared with other + * accounts, so if you have conference ID 1234, you won't conflict if another + * Tropo user is also using 1234. + *

+ *

+ * Each conference can hold up to 100 people at one time. + *

+ */ +@ValidKeys(keys={"name","allowSignals","mute","on","playTones","terminator","id","send_tones","exit_tone","interdigitTimeout","joinPrompt","leavePrompt","required","promptLogSecurity"}) @RequiredKeys(keys={"id"}) public class ConferenceAction extends JsonAction { diff --git a/src/main/java/com/voxeo/tropo/actions/Do.java b/src/main/java/com/voxeo/tropo/actions/Do.java index 0486c17..245c76f 100644 --- a/src/main/java/com/voxeo/tropo/actions/Do.java +++ b/src/main/java/com/voxeo/tropo/actions/Do.java @@ -1,7 +1,5 @@ package com.voxeo.tropo.actions; -import static com.voxeo.tropo.Key.VALUE; - import com.voxeo.tropo.Key; /** @@ -30,9 +28,9 @@ public static SayAction say(Key... keys) { return new SayAction(keys); } - public static SayAction say(String text) { + public static SayAction say(String text, String name) { - return say(VALUE(text)); + return say(Key.VALUE(text), Key.NAME(name)); } public static StartRecordingAction startRecording(Key... keys) { diff --git a/src/main/java/com/voxeo/tropo/actions/JsonAction.java b/src/main/java/com/voxeo/tropo/actions/JsonAction.java index dae32a3..94b2d6e 100644 --- a/src/main/java/com/voxeo/tropo/actions/JsonAction.java +++ b/src/main/java/com/voxeo/tropo/actions/JsonAction.java @@ -2,112 +2,180 @@ import java.net.MalformedURLException; import java.net.URL; -import java.util.Iterator; - -import net.sf.json.JSON; -import net.sf.json.JSONArray; -import net.sf.json.JSONObject; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; import com.voxeo.tropo.Key; import com.voxeo.tropo.TropoException; +import com.voxeo.tropo.actions.RecordAction.Url; public abstract class JsonAction extends Action { - - public JsonAction() { - - super(new JSONObject()); - } - - public JsonAction(Key... keys) { - - this(); - addKeys(keys); - } - - @Override - public void reset() { - - setNode(new JSONObject()); - } - - protected void addKeys(Key... keys) { - - for(Key key: keys) { - if (!isValidKey(key)) { - throw new TropoException(String.format("Invalid key '%s' for action",key.getName())); - } - put(key.getName(), key.getValue()); - } - } - - @SuppressWarnings("unchecked") - protected void accumulate(String key, Action action) { - - JSONObject node = (JSONObject)getNode(); - if (node.get(key) == null) { - put(key,action.json()); - } else { - // There is already an element. Accumulate it! - JSON json = action.json(); - if (json.isArray()) { - JSONArray array = (JSONArray)json; - Iterator it = array.iterator(); - while(it.hasNext()) { - node.accumulate(key,it.next()); - } - } else { - node.accumulate(key, json); - } - } - } - - public void put(String key, Action action) { - - action.setParent(this); - validate(); - put(key,action.json()); - } - - protected void put(String key, Object value) { - - ((JSONObject)getNode()).put(key, value); - } - - protected Object get(String key) { - - if (this instanceof JsonAction) { - return ((JSONObject)getNode()).get(key); - } - return null; - } - - private void checkFields(String... fields) throws TropoException { - - for (String field: fields) { - if (get(field) == null) { - throw new TropoException(String.format("Missing required property: '%s'",field)); - } - } - } - - protected void validate() throws TropoException { - - if (this instanceof JsonAction) { - for(String key: getRequiredKeys()) { - checkFields(key); - } - } - } - - public void checkUrl(String url) throws TropoException { - - String string = (String)get(url); - if (string != null) { - try { - new URL(string); - } catch (MalformedURLException e) { - throw new TropoException("The 'url' parameter must be a valid URL"); - } - } - } + + public JsonAction() { + + super(new JsonObject()); + } + + public JsonAction(Key... keys) { + + this(); + addKeys(keys); + } + + @Override + public void reset() { + + setNode(new JsonObject()); + } + + protected void addKeys(Key... keys) { + + for (Key key : keys) { + if (!isValidKey(key)) { + throw new TropoException(String.format("Invalid key '%s' for action", key.getName())); + } + putProperty(key.getName(), key.getValue()); + } + } + + protected void accumulate(String key, Action action) { + + JsonObject node = (JsonObject) getNode(); + JsonElement oldKeyElement = node.get(key); + if (oldKeyElement == null) { + put(key, action.json()); + } + else if (oldKeyElement.isJsonArray()) { + // There is already an json array element. Accumulate it! + JsonElement json = action.json(); + if (json.isJsonArray()) { + ((JsonArray) oldKeyElement).addAll((JsonArray) json); + } + else { + ((JsonArray) oldKeyElement).add(json); + } + } + else { + // There is already an json object element. Accumulate it! + JsonElement json = action.json(); + JsonArray newArray = new JsonArray(); + newArray.add(oldKeyElement); + if (json.isJsonArray()) { + newArray.addAll((JsonArray) json); + } + else { + newArray.add(json); + } + node.add(key, newArray); + } + } + + public void put(String key, Action action) { + + action.setParent(this); + validate(); + put(key, action.json()); + } + + protected void putProperty(String key, Object value) { + + if (value instanceof Boolean) { + ((JsonObject) getNode()).addProperty(key, (Boolean) value); + } + else if (value instanceof Number) { + ((JsonObject) getNode()).addProperty(key, (Number) value); + } + else if (value instanceof Character) { + ((JsonObject) getNode()).addProperty(key, (Character) value); + } + else if (value instanceof String) { + ((JsonObject) getNode()).addProperty(key, (String) value); + } + else { + ((JsonObject) getNode()).add(key, new Gson().toJsonTree(value)); + } + } + + protected void put(String key, JsonElement value) { + + ((JsonObject) getNode()).add(key, value); + } + + protected Object get(String key) { + + if (this instanceof JsonAction) { + JsonObject node = (JsonObject) getNode(); + JsonElement element = node.get(key); + + if (element instanceof JsonPrimitive) { + JsonPrimitive primitive = (JsonPrimitive)element; + if(primitive.isBoolean()){ + + return primitive.getAsBoolean(); + } + else if(primitive.isNumber()){ + return primitive.getAsNumber(); + } + else{ + return primitive.getAsString(); + } + } + else { + return element; + } + + } + return null; + } + + private void checkFields(String... fields) throws TropoException { + + for (String field : fields) { + if (get(field) == null) { + throw new TropoException(String.format("Missing required property: '%s'", field)); + } + } + } + + protected void validate() throws TropoException { + + if (this instanceof JsonAction) { + for (String key : getRequiredKeys()) { + checkFields(key); + } + } + } + + public void checkUrl(String url) throws TropoException { + + Object urls = get(url); + if (urls != null) { + if (urls instanceof String) { + try { + new URL((String) urls); + } catch (MalformedURLException e) { + throw new TropoException("The 'url' parameter must be a valid URL"); + } + } else if (urls instanceof JsonObject) { + try { + String sUrl = ((JsonPrimitive)((JsonObject) urls).get("url")).getAsString(); + new URL(sUrl); + } catch (MalformedURLException e) { + throw new TropoException("The 'url' parameter must be a valid URL"); + } + } else if (urls instanceof JsonArray) { + for (JsonElement oUrl : (JsonArray) urls) { + try { + String sUrl = ((JsonPrimitive)((JsonObject) oUrl).get("url")).getAsString(); + new URL(sUrl); + } catch (MalformedURLException e) { + throw new TropoException("The 'url' parameter must be a valid URL"); + } + } + } + } + } } diff --git a/src/main/java/com/voxeo/tropo/actions/MessageAction.java b/src/main/java/com/voxeo/tropo/actions/MessageAction.java index 5c9bca3..b00875e 100644 --- a/src/main/java/com/voxeo/tropo/actions/MessageAction.java +++ b/src/main/java/com/voxeo/tropo/actions/MessageAction.java @@ -4,11 +4,12 @@ import support.ActionSupportHandler; import com.voxeo.tropo.Key; +import com.voxeo.tropo.TropoException; import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; -@ValidKeys(keys={"say","to","answerOnMedia","channel","from","name","network","required","timeout","voice"}) -@RequiredKeys(keys={"to"}) +@ValidKeys(keys={"say","to","answerOnMedia","channel","from","name","network","required","timeout","voice","promptLogSecurity"}) +@RequiredKeys(keys={"to","say"}) public class MessageAction extends JsonAction { private ActionSupportHandler sayActionSupportHandler = new ActionSupportHandler(SayAction.class); @@ -25,6 +26,47 @@ public MessageAction(Key... keys) { setName("message"); } + public static class Say { + + public Say(String value) { + + if (value == null || value.trim().equals("")) { + throw new TropoException("Missing required property: value of message.say"); + } + + this.value = value; + } + + public Say(String value, String[] medias) { + + if (value == null || value.trim().equals("")) { + throw new TropoException("Missing required property: value of message.say"); + } + + this.value = value; + this.media = medias; + } + + private String value; + private String[] media; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String[] getMedia() { + return media; + } + + public void setMedia(String[] media) { + this.media = media; + } + + } public SayAction say(String text) { diff --git a/src/main/java/com/voxeo/tropo/actions/NestedOnAction.java b/src/main/java/com/voxeo/tropo/actions/NestedOnAction.java index 9282b2d..026f3cc 100644 --- a/src/main/java/com/voxeo/tropo/actions/NestedOnAction.java +++ b/src/main/java/com/voxeo/tropo/actions/NestedOnAction.java @@ -1,15 +1,15 @@ package com.voxeo.tropo.actions; -import static com.voxeo.tropo.Key.VALUE; -import support.ActionSupportHandler; - import com.voxeo.tropo.Key; import com.voxeo.tropo.annotations.ValidKeys; -@ValidKeys(keys={"next","value","event","name","required"}) +import support.ActionSupportHandler; + +@ValidKeys(keys={"next","value","event","name","required","post"}) public class NestedOnAction extends ArrayAction { private ActionSupportHandler sayActionSupportHandler = new ActionSupportHandler(SayAction.class); + private ActionSupportHandler askActionSupportHandler = new ActionSupportHandler(AskAction.class); public NestedOnAction() { @@ -23,13 +23,18 @@ public NestedOnAction(Key... keys) { setName("on"); } - public SayAction say(String text) { + public SayAction say(String text, String name) { - return say(VALUE(text)); + return say(Key.VALUE(text), Key.NAME(name)); } public SayAction say(Key... keys) { return sayActionSupportHandler.build(this, keys); - } + } + + public AskAction ask(Key... keys) { + + return askActionSupportHandler.build(this, keys); + } } diff --git a/src/main/java/com/voxeo/tropo/actions/OnAction.java b/src/main/java/com/voxeo/tropo/actions/OnAction.java index 1cf551b..9786c42 100644 --- a/src/main/java/com/voxeo/tropo/actions/OnAction.java +++ b/src/main/java/com/voxeo/tropo/actions/OnAction.java @@ -1,13 +1,16 @@ package com.voxeo.tropo.actions; import static com.voxeo.tropo.Key.VALUE; -import support.ActionSupportHandler; import com.voxeo.tropo.Key; +import com.voxeo.tropo.TropoException; import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; +import com.voxeo.tropo.enums.Voice; + +import support.ActionSupportHandler; -@ValidKeys(keys={"next","event","name","value","required"}) +@ValidKeys(keys={"next","event","say","post"}) @RequiredKeys(keys={"event"}) public class OnAction extends JsonAction { @@ -34,4 +37,40 @@ public SayAction say(Key... keys) { return sayActionSupportHandler.build(this, keys); } + + public static class Say { + + private String value; + + private Voice voice; + + public Say(String value) { + this(value, null); + } + + public Say(String value, Voice voice) { + + if (value == null || value.trim().equals("")) { + throw new TropoException("Missing required property: value of on.say"); + } + this.value = value; + this.voice = voice; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public Voice getVoice() { + return voice; + } + + public void setVoice(Voice voice) { + this.voice = voice; + } + } } diff --git a/src/main/java/com/voxeo/tropo/actions/RecordAction.java b/src/main/java/com/voxeo/tropo/actions/RecordAction.java index 15db1b1..608cf97 100644 --- a/src/main/java/com/voxeo/tropo/actions/RecordAction.java +++ b/src/main/java/com/voxeo/tropo/actions/RecordAction.java @@ -4,15 +4,18 @@ import static com.voxeo.tropo.Key.ID; import static com.voxeo.tropo.Key.URL; import static com.voxeo.tropo.Key.VALUE; -import support.ActionSupportHandler; import com.voxeo.tropo.Key; import com.voxeo.tropo.TropoException; import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; +import com.voxeo.tropo.enums.EmailFormat; + +import support.ActionSupportHandler; -@ValidKeys(keys={"name","send_tones","exit_tone","attempts","allowSignals","bargein","beep","choices","format","maxSilence","maxTime","method","minConfidence","required","transcription","url","password","username","timeout","voice","interdigitTimeout"}) -@RequiredKeys(keys={"url","name"}) +@ValidKeys(keys={"name","attempts","allowSignals","bargein","beep","choices","format","maxSilence","maxTime","method", + "required","transcription","url","password","username","timeout","voice","interdigitTimeout", "asyncUpload","say","promptLogSecurity","sensitivity"}) +@RequiredKeys(keys={"url"}) public class RecordAction extends JsonAction { private ActionSupportHandler sayActionSupportHandler = new ActionSupportHandler(SayAction.class); @@ -56,11 +59,156 @@ public TranscriptionAction transcription(Key... keys) { return transcriptionActionSupportHandler.build(this, keys); } - public TranscriptionAction transcription(String id, String url, String emailFormat) { + public TranscriptionAction transcription(String id, String url, String emailFormat, String language) { - return transcription(ID(id), URL(url), EMAIL_FORMAT(emailFormat)); + return transcription(ID(id), URL(url), EMAIL_FORMAT(emailFormat), Key.LANGUAGE(language)); } + public static class Say { + private String value; + + private String event; + + public Say(String value) { + if (value == null || value.trim().equals("")) + throw new TropoException("Missing required property: value of record.say"); + this.value = value; + } + + public Say(String value, String event) { + if (value == null || value.trim().equals("")) + throw new TropoException("Missing required property: value of record.say"); + if (!("timeout".equals(event))) + throw new TropoException("For record, the only possible event is 'timeout'."); + this.value = value; + this.event = "timeout"; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getEvent() { + return event; + } + + public void setEvent(String event) { + this.event = event; + } + } + + public static class Transcription { + private String id; + + private String url; + + private EmailFormat emailFormat; + + public Transcription(String url) { + super(); + this.url = url; + } + + public Transcription(String id, String url) { + super(); + this.id = id; + this.url = url; + } + + public Transcription(String id, String url, EmailFormat emailFormat) { + super(); + this.id = id; + this.url = url; + this.emailFormat = emailFormat; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public EmailFormat getEmailFormat() { + return emailFormat; + } + + public void setEmailFormat(EmailFormat emailFormat) { + this.emailFormat = emailFormat; + } + } + + public static class Url { + private String url; + + private String username; + + private String password; + + private String method; + + public Url(String url) { + super(); + this.url = url; + } + + public Url(String url, String username, String password, String method) { + super(); + if (url == null || url.trim().equals("")) { + throw new TropoException("Missing required property: url of Url"); + } + this.url = url; + this.username = username; + this.password = password; + this.method = method; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + 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 getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + } + @Override protected void validate() throws TropoException { diff --git a/src/main/java/com/voxeo/tropo/actions/RedirectAction.java b/src/main/java/com/voxeo/tropo/actions/RedirectAction.java index e768345..e7df3a5 100644 --- a/src/main/java/com/voxeo/tropo/actions/RedirectAction.java +++ b/src/main/java/com/voxeo/tropo/actions/RedirectAction.java @@ -6,7 +6,7 @@ import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; -@ValidKeys(keys={"to","from","name","required"}) +@ValidKeys(keys={"to","name","required"}) @RequiredKeys(keys={"to"}) public class RedirectAction extends JsonAction { diff --git a/src/main/java/com/voxeo/tropo/actions/SayAction.java b/src/main/java/com/voxeo/tropo/actions/SayAction.java index bfee82e..6478e16 100644 --- a/src/main/java/com/voxeo/tropo/actions/SayAction.java +++ b/src/main/java/com/voxeo/tropo/actions/SayAction.java @@ -1,21 +1,21 @@ package com.voxeo.tropo.actions; import static com.voxeo.tropo.Key.VALUE; -import net.sf.json.JSONObject; +import com.google.gson.JsonObject; import com.voxeo.tropo.Key; import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; -@ValidKeys(keys={"name","value","text","allowSignals","voice","event","as"}) +@ValidKeys(keys={"name","value","allowSignals","voice","as","required","promptLogSecurity","media"}) @RequiredKeys(keys={"value"}) public class SayAction extends ArrayAction { public SayAction(String text) { setName("say"); - JSONObject item = new JSONObject(); - item.put("value", text); + JsonObject item = new JsonObject(); + item.addProperty("value", text); add(item); } diff --git a/src/main/java/com/voxeo/tropo/actions/StartRecordingAction.java b/src/main/java/com/voxeo/tropo/actions/StartRecordingAction.java index b0e2d18..9914ba2 100644 --- a/src/main/java/com/voxeo/tropo/actions/StartRecordingAction.java +++ b/src/main/java/com/voxeo/tropo/actions/StartRecordingAction.java @@ -1,9 +1,23 @@ package com.voxeo.tropo.actions; import com.voxeo.tropo.Key; +import com.voxeo.tropo.TropoException; +import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; -@ValidKeys(keys={"format","method","url","username","password"}) +/** + *

+ * Allows Tropo applications to begin recording the current session. The + * resulting recording may then be sent via FTP or an HTTP POST/Multipart Form. + *

+ *

+ * The audio file can also be transcribed and the text returned to you via an + * email address or HTTP POST/Multipart Form - currently, transcription only + * supports US English. + *

+ */ +@ValidKeys(keys={"format","method","url","username","password","asyncUpload","transcriptionOutURI","transcriptionEmailFormat","transcriptionID","transcriptionLanguage"}) +@RequiredKeys(keys={"url"}) public class StartRecordingAction extends JsonAction { public StartRecordingAction() { @@ -16,5 +30,12 @@ public StartRecordingAction(Key... keys) { super(keys); setName("startRecording"); - } + } + + @Override + protected void validate() throws TropoException { + + super.validate(); + checkUrl("url"); + } } diff --git a/src/main/java/com/voxeo/tropo/actions/TranscriptionAction.java b/src/main/java/com/voxeo/tropo/actions/TranscriptionAction.java index ade459d..431e6dc 100644 --- a/src/main/java/com/voxeo/tropo/actions/TranscriptionAction.java +++ b/src/main/java/com/voxeo/tropo/actions/TranscriptionAction.java @@ -3,7 +3,7 @@ import com.voxeo.tropo.Key; import com.voxeo.tropo.annotations.ValidKeys; -@ValidKeys(keys={"id","url","emailFormat"}) +@ValidKeys(keys={"id","url","emailFormat","language"}) public class TranscriptionAction extends JsonAction { public TranscriptionAction() { diff --git a/src/main/java/com/voxeo/tropo/actions/TransferAction.java b/src/main/java/com/voxeo/tropo/actions/TransferAction.java index cebeb0c..2a4660a 100644 --- a/src/main/java/com/voxeo/tropo/actions/TransferAction.java +++ b/src/main/java/com/voxeo/tropo/actions/TransferAction.java @@ -10,46 +10,46 @@ import com.voxeo.tropo.annotations.RequiredKeys; import com.voxeo.tropo.annotations.ValidKeys; -@ValidKeys(keys={"to","allowSignals","choices","from","headers","name","on","required","ringRepeat","timeout","interdigitTimeout"}) +@ValidKeys(keys={"to","allowSignals","choices","from","headers","name","on","required","ringRepeat","timeout","answerOnMedia","interdigitTimeout","machineDetection","playTones","voice","callbackUrl","promptLogSecurity","label"}) @RequiredKeys(keys={"to"}) public class TransferAction extends JsonAction { - private ActionSupportHandler onRecordingActionSupportHandler = new ActionSupportHandler(NestedOnAction.class); - private ActionSupportHandler choicesRecordingActionSupportHandler = new ActionSupportHandler(ChoicesAction.class); + private ActionSupportHandler onRecordingActionSupportHandler = new ActionSupportHandler(NestedOnAction.class); + private ActionSupportHandler choicesRecordingActionSupportHandler = new ActionSupportHandler(ChoicesAction.class); private HeadersSupportHandler headersSupportHandler = new HeadersSupportHandler(); public TransferAction() { - + super(); setName("transfer"); } - + public TransferAction(Key... keys) { - + super(keys); setName("transfer"); - } - + } + public NestedOnAction on(Key... keys) { return onRecordingActionSupportHandler.build(this, keys); } - + public NestedOnAction on(String event, String next) { return on(EVENT(event), NEXT(next)); } - + public ChoicesAction choices(Key... keys) { return choicesRecordingActionSupportHandler.build(this, keys); - } - + } + public AskAction choices(String choice) { return (AskAction)and(choices(VALUE(choice))); } - + public HeadersAction headers(String[]... keys) { return headersSupportHandler.headers(this, keys); diff --git a/src/main/java/com/voxeo/tropo/actions/WaitAction.java b/src/main/java/com/voxeo/tropo/actions/WaitAction.java new file mode 100644 index 0000000..220abc7 --- /dev/null +++ b/src/main/java/com/voxeo/tropo/actions/WaitAction.java @@ -0,0 +1,20 @@ +package com.voxeo.tropo.actions; + +import com.voxeo.tropo.Key; +import com.voxeo.tropo.annotations.RequiredKeys; +import com.voxeo.tropo.annotations.ValidKeys; + +@ValidKeys(keys={"allowSignals", "milliseconds"}) +@RequiredKeys(keys={"milliseconds"}) +public class WaitAction extends JsonAction { + + public WaitAction() { + super(); + setName("wait"); + } + + public WaitAction(Key... keys) { + super(keys); + setName("wait"); + } +} diff --git a/src/main/java/com/voxeo/tropo/enums/AsrLogSecurity.java b/src/main/java/com/voxeo/tropo/enums/AsrLogSecurity.java new file mode 100644 index 0000000..48962c3 --- /dev/null +++ b/src/main/java/com/voxeo/tropo/enums/AsrLogSecurity.java @@ -0,0 +1,12 @@ +package com.voxeo.tropo.enums; + +public enum AsrLogSecurity { + + NONE, SUPPRESS, MASK; + + @Override + public String toString() { + + return super.toString().toLowerCase(); + } +} diff --git a/src/main/java/com/voxeo/tropo/enums/EmailFormat.java b/src/main/java/com/voxeo/tropo/enums/EmailFormat.java new file mode 100644 index 0000000..578589a --- /dev/null +++ b/src/main/java/com/voxeo/tropo/enums/EmailFormat.java @@ -0,0 +1,12 @@ +package com.voxeo.tropo.enums; + +public enum EmailFormat { + + PLAIN,ENCODED; + +@Override public String toString() { + + String s = super.toString(); + return s.toLowerCase(); + } +} diff --git a/src/main/java/com/voxeo/tropo/enums/Format.java b/src/main/java/com/voxeo/tropo/enums/Format.java index ff2337c..1ec9bae 100644 --- a/src/main/java/com/voxeo/tropo/enums/Format.java +++ b/src/main/java/com/voxeo/tropo/enums/Format.java @@ -2,7 +2,7 @@ public enum Format { - WAV, MP3; + WAV, MP3, AU; @Override public String toString() { diff --git a/src/main/java/com/voxeo/tropo/enums/LogSecurityState.java b/src/main/java/com/voxeo/tropo/enums/LogSecurityState.java new file mode 100644 index 0000000..94c9008 --- /dev/null +++ b/src/main/java/com/voxeo/tropo/enums/LogSecurityState.java @@ -0,0 +1,12 @@ +package com.voxeo.tropo.enums; + +public enum LogSecurityState { + + NONE, SUPPRESS; + + @Override + public String toString() { + + return super.toString().toLowerCase(); + } +} diff --git a/src/main/java/com/voxeo/tropo/enums/Method.java b/src/main/java/com/voxeo/tropo/enums/Method.java new file mode 100644 index 0000000..a990694 --- /dev/null +++ b/src/main/java/com/voxeo/tropo/enums/Method.java @@ -0,0 +1,6 @@ +package com.voxeo.tropo.enums; + +public enum Method { + + POST, PUT; +} diff --git a/src/main/java/com/voxeo/tropo/enums/Mode.java b/src/main/java/com/voxeo/tropo/enums/Mode.java index 5b9b514..ac1107d 100644 --- a/src/main/java/com/voxeo/tropo/enums/Mode.java +++ b/src/main/java/com/voxeo/tropo/enums/Mode.java @@ -1,7 +1,7 @@ package com.voxeo.tropo.enums; public enum Mode { - DTMF, SPEECH; + DTMF, SPEECH, ANY; @Override public String toString() { diff --git a/src/main/java/com/voxeo/tropo/enums/Network.java b/src/main/java/com/voxeo/tropo/enums/Network.java index 2447232..d9a7c0a 100644 --- a/src/main/java/com/voxeo/tropo/enums/Network.java +++ b/src/main/java/com/voxeo/tropo/enums/Network.java @@ -1,5 +1,5 @@ package com.voxeo.tropo.enums; public enum Network { - SMS, AIM, MSN, JABBER, YAHOO, GTALK, TWITTER + SMS, AIM, MSN, JABBER, YAHOO, GTALK, TWITTER, PSTN, SIP, MMS } diff --git a/src/main/java/com/voxeo/tropo/enums/Recognizer.java b/src/main/java/com/voxeo/tropo/enums/Recognizer.java index b1c8090..28eef18 100644 --- a/src/main/java/com/voxeo/tropo/enums/Recognizer.java +++ b/src/main/java/com/voxeo/tropo/enums/Recognizer.java @@ -1,7 +1,14 @@ package com.voxeo.tropo.enums; public enum Recognizer { - GERMAN, BRITISH_ENGLISH, US_ENGLISH, SPANISH, MEXICAN_SPANISH, FRENCH, FRENCH_CANADIAN, ITALIAN, POLISH, DUTCH; + GERMAN, BRITISH_ENGLISH, US_ENGLISH, SPANISH, @Deprecated MEXICAN_SPANISH, FRENCH, FRENCH_CANADIAN, ITALIAN, POLISH, DUTCH, + AFRIKAANS, ARABIC, ARABIC_JORDANIAN, ASSAMESE, BASQUE, BENGALI, BENGALI_INDIAN, BHOJPURI, BULGARIAN, CANTONESE, + CATALAN, CZECH, DANISH, DUTCH_BELGIAN, ENGLISH_AUSTRALIAN, ENGLISH_INDIAN, ENGLISH_SINGAPOREAN, ENGLISH_SOUTH_AFRICAN, + ENGLISH_UK, ENGLISH_US, FINNISH, FRENCH_BELGIAN, GALICIAN, GERMAN_AUSTRIAN, GERMAN_SWISS, GREEK, GUJARATI, HEBREW, + HINDI, HUNGARIAN, ICELANDIC, INDONESIAN, JAPANESE, KANNADA, KOREAN, MALAY, MALAYALAM, MANDARIN, MANDARIN_TAIWANESE, + MARATHI, NEPALI, NORWEGIAN, ORIYA, PORTUGUESE, PORTUGUESE_BRAZILIAN, PUNJABI, ROMANIAN, RUSSIAN, SERBIAN, SLOVAK, + SLOVENIAN, SPANISH_ARGENTINIAN, SPANISH_COLOMBIAN, SPANISH_US_MEXICAN, SWEDISH, TAMIL, TELUGU, THAI, TURKISH, UKRAINIAN, + URDU_INDIAN, URDU_PAKISTANI, VALENCIAN, VIETNAMESE, WELSH; @Override public String toString() { @@ -11,11 +18,76 @@ public enum Recognizer { case US_ENGLISH : return "en-us"; case SPANISH : return "es-es"; case MEXICAN_SPANISH : return "es-mx"; - case FRENCH : return "fr"; + case FRENCH : return "fr-fr"; case FRENCH_CANADIAN : return "fr-ca"; case ITALIAN : return "it-it"; case POLISH : return "pl-pl"; case DUTCH : return "nl-nl"; + case AFRIKAANS : return "af-za"; + case ARABIC : return "ar-ww"; + case ARABIC_JORDANIAN : return "ar-jo"; + case ASSAMESE : return "as-in"; + case BASQUE : return "eu-es"; + case BENGALI : return "bn-bd"; + case BENGALI_INDIAN : return "bn-in"; + case BHOJPURI : return "bh-in"; + case BULGARIAN : return "bg-bg"; + case CANTONESE : return "cn-hk"; + case CATALAN : return "ca-es"; + case CZECH : return "cs-cz"; + case DANISH : return "da-dk"; + case DUTCH_BELGIAN : return "nl-be"; + case ENGLISH_AUSTRALIAN : return "en-au"; + case ENGLISH_INDIAN : return "en-in"; + case ENGLISH_SINGAPOREAN : return "en-sg"; + case ENGLISH_SOUTH_AFRICAN : return "en-za"; + case ENGLISH_UK : return "en-gb"; + case ENGLISH_US : return "en-us"; + case FINNISH : return "fi-fi"; + case FRENCH_BELGIAN : return "fr-be"; + case GALICIAN : return "gl-es"; + case GERMAN_AUSTRIAN : return "de-at"; + case GERMAN_SWISS : return "de-ch"; + case GREEK : return "el-gr"; + case GUJARATI : return "gu-in"; + case HEBREW : return "he-il"; + case HINDI : return "hi-in"; + case HUNGARIAN : return "hu-hu"; + case ICELANDIC : return "is-is"; + case INDONESIAN : return "id-id"; + case JAPANESE : return "ja-jp"; + case KANNADA : return "kn-in"; + case KOREAN : return "ko-kr"; + case MALAY : return "ms-my"; + case MALAYALAM : return "ml-in"; + case MANDARIN : return "zh-cn"; + case MANDARIN_TAIWANESE : return "zh-tw"; + case MARATHI : return "mr-in"; + case NEPALI : return "ne-np"; + case NORWEGIAN : return "no-no"; + case ORIYA : return "or-in"; + case PORTUGUESE : return "pt-pt"; + case PORTUGUESE_BRAZILIAN : return "pt-br"; + case PUNJABI : return "pa-in"; + case ROMANIAN : return "ro-ro"; + case RUSSIAN : return "ru-ru"; + case SERBIAN : return "sr-rs"; + case SLOVAK : return "sk-sk"; + case SLOVENIAN : return "sl-si"; + case SPANISH_ARGENTINIAN : return "es-ar"; + case SPANISH_COLOMBIAN : return "es-co"; + case SPANISH_US_MEXICAN : return "es-us"; + case SWEDISH : return "sv-se"; + case TAMIL : return "ta-in"; + case TELUGU : return "te-in"; + case THAI : return "th-th"; + case TURKISH : return "tr-tr"; + case UKRAINIAN : return "uk-ua"; + case URDU_INDIAN : return "ur-in"; + case URDU_PAKISTANI : return "ur-pk"; + case VALENCIAN : return "va-es"; + case VIETNAMESE : return "vi-vn"; + case WELSH : return "cy-gb"; } return super.toString(); } diff --git a/src/main/java/com/voxeo/tropo/enums/Terminator.java b/src/main/java/com/voxeo/tropo/enums/Terminator.java new file mode 100644 index 0000000..ac1b005 --- /dev/null +++ b/src/main/java/com/voxeo/tropo/enums/Terminator.java @@ -0,0 +1,39 @@ +package com.voxeo.tropo.enums; + +public enum Terminator { + + ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, STAR, POUND; + + @Override + public String toString() { + + switch (this) { + case ZERO: + return "0"; + case ONE: + return "1"; + case TWO: + return "2"; + case THREE: + return "3"; + case FOUR: + return "4"; + case FIVE: + return "5"; + case SIX: + return "6"; + case SEVEN: + return "7"; + case EIGHT: + return "8"; + case NINE: + return "9"; + case STAR: + return "*"; + case POUND: + return "#"; + default: + return null; + } + } +} diff --git a/src/main/java/com/voxeo/tropo/enums/Voice.java b/src/main/java/com/voxeo/tropo/enums/Voice.java index 0eea668..afa5a31 100644 --- a/src/main/java/com/voxeo/tropo/enums/Voice.java +++ b/src/main/java/com/voxeo/tropo/enums/Voice.java @@ -1,10 +1,26 @@ package com.voxeo.tropo.enums; public enum Voice { - CARMEN, JORGE, FLORENCE, BERNARD, ALLISON, DAVE, KATE, SIMON, KATRIN, STEFAN, PAOLA, LUCA, SASKIA, WILLEM, SOLEDAD, CARLOS, ZOSIA, KRZYSZTOF; + @Deprecated CARMEN,JORGE, @Deprecated FLORENCE, @Deprecated BERNARD, ALLISON, @Deprecated DAVE, KATE, @Deprecated SIMON, @Deprecated KATRIN, @Deprecated STEFAN, PAOLA, LUCA, @Deprecated SASKIA, @Deprecated WILLEM, SOLEDAD, CARLOS, ZOSIA, KRZYSZTOF, + LAILA, MAGED, TARIK, DAMAYANTI, MIREN, DARIA, SINJI, MONTSERRAT, JORDI, IVETA, ZUZANA, SARA, MAGNUS, CLAIRE, XANDER, ELLEN, KAREN, LEE, VEENA, + MOIRA, FIONA, TESSA, SERENA, DANIEL, OLIVER, AVA, SAMANTHA, TOM, VICTOR, SATU, ONNI, AUDREY, AURELIE, THOMAS, AMELIE, CHANTAL, NICOLAS, CARMELA, + ANNA, PETRA, MARKUS, YANNICK, MELINA, NIKOS, CARMIT, LEKHA, MARISKA, ALICE, FEDERICA, KYOKO, OTOYA, SORA, TIANTIAN, MEIJIA, NORA, HENRIK, EWA, + CATARINA, JOANA, JOAQUIM, LUCIANA, FELIPE, KATYA, MILENA, YURI, LAURA, DIEGO, MONICA, ANGELICA, PAULINA, JUAN, ALVA, KLARA, OSKAR, KANYA, YELDA, + CEM, EMPAR; @Override public String toString() { + switch(this) { + case SINJI: + return "sin-ji"; + case TIANTIAN: + return "tian-tian"; + case MEIJIA: + return "mei-jia"; + default: + break; + } + String s = super.toString(); return s.toLowerCase(); } diff --git a/src/test/java/com/voxeo/tropo/AnswerActionTest.java b/src/test/java/com/voxeo/tropo/AnswerActionTest.java new file mode 100644 index 0000000..e1b5e00 --- /dev/null +++ b/src/test/java/com/voxeo/tropo/AnswerActionTest.java @@ -0,0 +1,67 @@ +package com.voxeo.tropo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.junit.Test; + +import com.voxeo.tropo.actions.AnswerAction; + +public class AnswerActionTest { + + @Test + public void testAnswer() { + + Tropo tropo = new Tropo(); + tropo.answer(); + tropo.say("Hello, you were the first to answer.", "say"); + + assertEquals(tropo.text(), + "{\"tropo\":[{\"answer\":{}},{\"say\":[{\"value\":\"Hello, you were the first to answer.\",\"name\":\"say\"}]}]}"); + } + + @Test + public void testAnswerFailsWithInvalidElement() { + + Tropo tropo = new Tropo(); + try { + tropo.answer(Key.NAME("foo")); + fail("Expected exception in test"); + } + catch (TropoException te) { + assertEquals(te.getMessage(), "Invalid key 'name' for action"); + } + } + + @Test + public void testAnswerWithHeadersTraditional() { + + Tropo tropo = new Tropo(); + AnswerAction answer = tropo.answer(); + answer.headers(new String[] {"P-Header", "value goes here"}, new String[] {"Remote-Party-ID", + "\"John Doe\";party=calling;id-type=subscriber;privacy=full;screen=yes"}); + tropo.say("Hello, you were the first to answer.", "say"); + + assertEquals(tropo.text(), + "{\"tropo\":[{\"answer\":{\"headers\":{\"P-Header\":\"value goes here\",\"Remote-Party-ID\":\"\\\"John Doe\\\";party=calling;id-type=subscriber;privacy=full;screen=yes\"}}},{\"say\":[{\"value\":\"Hello, you were the first to answer.\",\"name\":\"say\"}]}]}"); + } + + @Test + public void testNewAnswerWithHeadersTraditional() { + + Tropo tropo = new Tropo(); + Map map = new LinkedHashMap(); + map.put("P-Header", "value goes here"); + map.put("Remote-Party-ID", + "\"John Doe\";party=calling;id-type=subscriber;privacy=full;screen=yes"); + tropo.answer(Key.HEADERS(map)); + tropo.say("Hello, you were the first to answer.", "say"); + + assertEquals(tropo.text(), + "{\"tropo\":[{\"answer\":{\"headers\":{\"P-Header\":\"value goes here\",\"Remote-Party-ID\":\"\\\"John Doe\\\";party=calling;id-type=subscriber;privacy=full;screen=yes\"}}},{\"say\":[{\"value\":\"Hello, you were the first to answer.\",\"name\":\"say\"}]}]}"); + } + +} diff --git a/src/test/java/com/voxeo/tropo/AskActionTest.java b/src/test/java/com/voxeo/tropo/AskActionTest.java index bc0ae6b..1251400 100644 --- a/src/test/java/com/voxeo/tropo/AskActionTest.java +++ b/src/test/java/com/voxeo/tropo/AskActionTest.java @@ -1,140 +1,185 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.*; -import static com.voxeo.tropo.enums.Mode.DTMF; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; -import com.voxeo.tropo.actions.Do; +import com.voxeo.tropo.actions.AskAction.Choices; +import com.voxeo.tropo.actions.AskAction.Say; +import com.voxeo.tropo.enums.AsrLogSecurity; +import com.voxeo.tropo.enums.Mode; import com.voxeo.tropo.enums.Recognizer; import com.voxeo.tropo.enums.Voice; public class AskActionTest { + + @Before + public void setUp() throws Exception { + + } + + @Test + public void testAsk() { + + Tropo tropo = new Tropo(); + tropo.ask(Key.CHOICES_OF_ASK("[1 DIGIT]"), Key.SAY_OF_ASK(new Say("Please say a digit")), Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"ask\":{\"choices\":{\"value\":\"[1 DIGIT]\"},\"say\":[{\"value\":\"Please say a digit\"}],\"bargein\":true,\"timeout\":30.0,\"required\":true}}]}"); + } + + @Test + public void testAskWithSensitivity() { + + Tropo tropo = new Tropo(); + tropo.ask(Key.CHOICES_OF_ASK("[1 DIGIT]"), Key.SAY_OF_ASK(new Say("Please say a digit")), Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.SENSITIVITY(30.1f), Key.REQUIRED(true)); + + assertEquals(tropo.text(), + "{\"tropo\":[{\"ask\":{\"choices\":{\"value\":\"[1 DIGIT]\"},\"say\":[{\"value\":\"Please say a digit\"}],\"bargein\":true,\"timeout\":30.0,\"sensitivity\":30.1,\"required\":true}}]}"); + } - @Before - public void setUp() throws Exception { - } + @Test + public void testNewAskWithSayAndOnBlocks() { - @Test - public void testAsk() { - - Tropo tropo = new Tropo(); - tropo - .ask(NAME("foo"),BARGEIN(true),TIMEOUT(30.0f),REQUIRED(true)); - - assertEquals(tropo.text(),"{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"bargein\":true,\"timeout\":30,\"required\":true}}]}"); - } - - @Test - public void testAskWithSayBlock() { - - Tropo tropo = new Tropo(); - tropo - .ask(NAME("foo"),BARGEIN(true),TIMEOUT(30.0f),REQUIRED(true),CHOICES("[5 DIGITS]")) - .say("Please say your account number"); - - assertEquals(tropo.text(),"{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"bargein\":true,\"timeout\":30,\"required\":true,\"choices\":\"[5 DIGITS]\",\"say\":[{\"value\":\"Please say your account number\"}]}}]}"); - } - - @Test - public void testAskWithSayAndOnBlocks() { - - Tropo tropo = new Tropo(); - tropo - .ask(NAME("foo"),BARGEIN(true),TIMEOUT(30.0f),REQUIRED(true)).and( - Do.say("Please say your account number"), - Do.on(EVENT("success"),NEXT("/result.json")), - Do.choices(VALUE("[5 DIGITS]"))); + Tropo tropo = new Tropo(); + tropo.ask(Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true), Key.SAY_OF_ASK(new Say("Please say your account number")), Key.CHOICES_OF_ASK("[5 DIGITS]")); + tropo.on(Key.SAY_OF_ON("Nice answer!"),Key.EVENT("continue"), Key.NEXT("/result.json")); - assertEquals(tropo.text(),"{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"bargein\":true,\"timeout\":30,\"required\":true,\"say\":[{\"value\":\"Please say your account number\"}],\"on\":[{\"event\":\"success\",\"next\":\"/result.json\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); - } - - @Test - public void testFailsAskWithNoNameParameter() { + assertEquals( + tropo.text(), + "{\"tropo\":[{\"ask\":{\"bargein\":true,\"timeout\":30.0,\"required\":true,\"say\":[{\"value\":\"Please say your account number\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}},{\"on\":{\"say\":[{\"value\":\"Nice answer!\"}],\"event\":\"continue\",\"next\":\"/result.json\"}}]}"); + } + + @Deprecated + public void testFailsAskWithNoNameParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.ask(Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true)); + fail("Expected exception in test"); + } + catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'name'"); + } + } - Tropo tropo = new Tropo(); - try { - tropo.ask(BARGEIN(true),TIMEOUT(30.0f),REQUIRED(true)); - fail("Expected exception in test"); - } catch (TropoException te) { - assertEquals(te.getMessage(), "Missing required property: 'name'"); - } - } - - @Test - public void testAskFailsWithInvalidElement() { + @Test + public void testFailsAskWithNoChoicesParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.ask(Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true)); + fail("Expected exception in test"); + } + catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'choices'"); + } + } - Tropo tropo = new Tropo(); - try { - tropo.ask(TO("foo"),BARGEIN(true),TIMEOUT(30.0f),REQUIRED(true)); - fail("Expected exception in test"); - } catch (TropoException te) { - assertEquals(te.getMessage(), "Invalid key 'to' for action"); - } - } - - @Test - public void testAllowSignals() { - - Tropo tropo = new Tropo(); - tropo.ask(NAME("foo"),BARGEIN(true),TIMEOUT(30.0f),REQUIRED(true),ALLOW_SIGNALS("exit","stopHold")); - - assertEquals(tropo.text(),"{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"bargein\":true,\"timeout\":30,\"required\":true,\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); - } - - @Test - public void testAskAllParameters() { - - Tropo tropo = new Tropo(); - tropo.ask(NAME("foo"),BARGEIN(true),TIMEOUT(30.0f),INTERDIGIT_TIMEOUT(5),REQUIRED(true),ALLOW_SIGNALS("exit","stopHold"),ATTEMPTS(5),MIN_CONFIDENCE(3),RECOGNIZER(Recognizer.SPANISH),VOICE(Voice.ALLISON)); - - assertEquals(tropo.text(),"{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"bargein\":true,\"timeout\":30,\"interdigitTimeout\":5,\"required\":true,\"allowSignals\":[\"exit\",\"stopHold\"],\"attempts\":5,\"minConfidence\":3,\"recognizer\":\"es-es\",\"voice\":\"allison\"}}]}"); - } + @Test + public void testFailsAskWithNoSayParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.ask(Key.CHOICES_OF_ASK("Please say a digit"), Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true)); + fail("Expected exception in test"); + } + catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'say'"); + } + } - @Test - public void testAskModeIsSupportedParameters() { - - Tropo tropo = new Tropo(); - tropo.ask(NAME("foo"),MODE(DTMF),TIMEOUT(30.0f),REQUIRED(true),ALLOW_SIGNALS("exit","stopHold"),ATTEMPTS(5),MIN_CONFIDENCE(3),RECOGNIZER(Recognizer.SPANISH),VOICE(Voice.ALLISON)); - - assertEquals(tropo.text(),"{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"mode\":\"dtmf\",\"timeout\":30,\"required\":true,\"allowSignals\":[\"exit\",\"stopHold\"],\"attempts\":5,\"minConfidence\":3,\"recognizer\":\"es-es\",\"voice\":\"allison\"}}]}"); - } - - @Test - public void testAskTraditionalWay() { - - Tropo tropo = new Tropo(); - tropo.ask("foo",true,30.0f,true); - - assertEquals(tropo.text(),"{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"bargein\":true,\"timeout\":30,\"required\":true}}]}"); - } - - @Test - public void testAskAndChoicesTraditionalWay() { - - Tropo tropo = new Tropo(); - tropo.ask("foo",true,30.0f,true).choices(VALUE("[5 DIGITS]")); - - assertEquals(tropo.text(),"{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"bargein\":true,\"timeout\":30,\"required\":true,\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); - } - - @Test - public void testChoicesMethods() { - - String output = "{\"tropo\":[{\"ask\":{\"attempts\":3,\"name\":\"question\",\"bargein\":true,\"timeout\":20,\"required\":true,\"choices\":{\"value\":\"red,green,blue\"}}}]}"; - // From evolution bug - Tropo tropo = new Tropo(); - tropo.ask(ATTEMPTS(3), NAME("question"), BARGEIN(true), TIMEOUT(20f), REQUIRED(true)) - .choices("red,green,blue"); - assertEquals(tropo.text(),output); - - tropo.reset(); - tropo.ask(ATTEMPTS(3), NAME("question"), BARGEIN(true), TIMEOUT(20f), REQUIRED(true)) - .choices(VALUE("red,green,blue")); - assertEquals(tropo.text(),output); - tropo.reset(); - } + @Test + public void testFailsAskWithNoChoicesValue() { + + Tropo tropo = new Tropo(); + try { + tropo.ask(Key.CHOICES_OF_ASK(new Choices(null)), Key.SAY_OF_ASK(new Say("[1 DIGIT]")), Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true)); + fail("Expected exception in test"); + } + catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of Choices"); + } + } + + @Test + public void testFailsAskWithNoChoicesValue1() { + + Tropo tropo = new Tropo(); + try { + tropo.ask(Key.CHOICES_OF_ASK(new Choices("")), Key.SAY_OF_ASK(new Say("[1 DIGIT]")), Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true)); + fail("Expected exception in test"); + } + catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of Choices"); + } + } + + @Test + public void testFailsAskWithNoSayValue() { + + Tropo tropo = new Tropo(); + try { + tropo.ask(Key.CHOICES_OF_ASK("Please say a digit"), Key.SAY_OF_ASK(new Say(null)), Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true)); + fail("Expected exception in test"); + } + catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of ask.say"); + } + } + + @Test + public void testFailsAskWithNoSayValue1() { + + Tropo tropo = new Tropo(); + try { + tropo.ask(Key.CHOICES_OF_ASK("Please say a digit"), Key.SAY_OF_ASK(new Say("")), Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true)); + fail("Expected exception in test"); + } + catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of ask.say"); + } + } + + @Test + public void testAskFailsWithInvalidElement() { + + Tropo tropo = new Tropo(); + try { + tropo.ask(Key.TO("foo"), Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true)); + fail("Expected exception in test"); + } + catch (TropoException te) { + assertEquals(te.getMessage(), "Invalid key 'to' for action"); + } + } + + @Test + public void testAllowSignals() { + + Tropo tropo = new Tropo(); + tropo.ask(Key.CHOICES_OF_ASK("[1 DIGIT]"), Key.SAY_OF_ASK(new Say("Please say a digit")), Key.BARGEIN(true), Key.TIMEOUT(30.0f), Key.REQUIRED(true), Key.ALLOW_SIGNALS("exit", "stopHold")); + + assertEquals(tropo.text(), + "{\"tropo\":[{\"ask\":{\"choices\":{\"value\":\"[1 DIGIT]\"},\"say\":[{\"value\":\"Please say a digit\"}],\"bargein\":true,\"timeout\":30.0,\"required\":true,\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); + } + + @Test + public void testNewAllParameters() { + + Tropo tropo = new Tropo(); + tropo.ask(Key.CHOICES_OF_ASK(new Choices("[4 DIGITS]", Mode.DTMF, "*")), Key.ALLOW_SIGNALS("exit", "quit"), + Key.ATTEMPTS(3), Key.BARGEIN(true), Key.INTERDIGIT_TIMEOUT(3.5f), Key.MIN_CONFIDENCE(30), + Key.RECOGNIZER(Recognizer.ENGLISH_US), Key.REQUIRED(true), + Key.SAY_OF_ASK(new Say("Sorry, I did not hear anything.", "timeout"), + new Say("Don't think that was a year.", "nomatch:1"), new Say("Nope, still not a year.", "nomatch:2"), + new Say("What is your birth year?")), + Key.SENSITIVITY(0.5f), Key.SPEECH_COMPLETE_TIMEOUT(0.5f), Key.SPEECH_INCOMPLETE_TIMEOUT(0.5f), + Key.TIMEOUT(30.1f), Key.VOICE(Voice.ALLISON), Key.PROMPT_LOG_SECURITY(), + Key.ASR_LOG_SECURITY(AsrLogSecurity.MASK), Key.MASK_TEMPLATE("XXD-")); + + assertEquals(tropo.text(), + "{\"tropo\":[{\"ask\":{\"choices\":{\"value\":\"[4 DIGITS]\",\"mode\":\"DTMF\",\"terminator\":\"*\"},\"allowSignals\":[\"exit\",\"quit\"],\"attempts\":3,\"bargein\":true,\"interdigitTimeout\":3.5,\"minConfidence\":30,\"recognizer\":\"en-us\",\"required\":true,\"say\":[{\"value\":\"Sorry, I did not hear anything.\",\"event\":\"timeout\"},{\"value\":\"Don't think that was a year.\",\"event\":\"nomatch:1\"},{\"value\":\"Nope, still not a year.\",\"event\":\"nomatch:2\"},{\"value\":\"What is your birth year?\"}],\"sensitivity\":0.5,\"speechCompleteTimeout\":0.5,\"speechIncompleteTimeout\":0.5,\"timeout\":30.1,\"voice\":\"allison\",\"promptLogSecurity\":\"suppress\",\"asrLogSecurity\":\"mask\",\"maskTemplate\":\"XXD-\"}}]}"); + } } diff --git a/src/test/java/com/voxeo/tropo/CallActionTest.java b/src/test/java/com/voxeo/tropo/CallActionTest.java index dc6f79a..fa8c14e 100644 --- a/src/test/java/com/voxeo/tropo/CallActionTest.java +++ b/src/test/java/com/voxeo/tropo/CallActionTest.java @@ -1,16 +1,17 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import java.util.LinkedHashMap; +import java.util.Map; + import org.junit.Test; import com.voxeo.tropo.actions.CallAction; -import com.voxeo.tropo.actions.Do; import com.voxeo.tropo.enums.Channel; -import com.voxeo.tropo.enums.Format; import com.voxeo.tropo.enums.Network; +import com.voxeo.tropo.enums.Voice; public class CallActionTest { @@ -18,11 +19,9 @@ public class CallActionTest { public void testCall() { Tropo tropo = new Tropo(); - tropo.call(TO("foo"), FROM("bar"), NETWORK(Network.SMS), CHANNEL(Channel.TEXT), TIMEOUT(10.0f), ANSWER_ON_MEDIA(false)).and( - Do.headers(new String[]{"fooKey","fooValue"}, new String[]{"barKey","barValue"}), - Do.startRecording(URL("http://foobar"), METHOD("POST"), FORMAT(Format.MP3), USERNAME("jose"), PASSWORD("passwd"))); + tropo.call(Key.TO("foo"), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false), Key.VOICE(Voice.TOM), Key.CALLBACK_URL("http://requestb.in/11fu6h91"), Key.PROMPT_LOG_SECURITY(), Key.LABEL("callLabel")); - assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10,\"answerOnMedia\":false,\"headers\":{\"fooKey\":\"fooValue\",\"barKey\":\"barValue\"},\"startRecording\":{\"url\":\"http://foobar\",\"method\":\"POST\",\"format\":\"audio/mp3\",\"username\":\"jose\",\"password\":\"passwd\"}}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10.0,\"answerOnMedia\":false,\"voice\":\"tom\",\"callbackUrl\":\"http://requestb.in/11fu6h91\",\"promptLogSecurity\":\"suppress\",\"label\":\"callLabel\"}}]}"); } @Test @@ -30,7 +29,7 @@ public void testCallFailsWithInvalidElement() { Tropo tropo = new Tropo(); try { - tropo.call(BARGEIN(true), FROM("bar"), NETWORK(Network.SMS), CHANNEL(Channel.TEXT), TIMEOUT(10.0f), ANSWER_ON_MEDIA(false)); + tropo.call(Key.BARGEIN(true), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false)); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'bargein' for action"); @@ -41,18 +40,18 @@ public void testCallFailsWithInvalidElement() { public void testAllowSignals() { Tropo tropo = new Tropo(); - tropo.call(TO("foo"), FROM("bar"), NETWORK(Network.SMS), CHANNEL(Channel.TEXT), TIMEOUT(10.0f), ANSWER_ON_MEDIA(false),ALLOW_SIGNALS("exit","stopHold")); + tropo.call(Key.TO("foo"), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false), Key.ALLOW_SIGNALS("exit","stopHold")); - assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10,\"answerOnMedia\":false,\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10.0,\"answerOnMedia\":false,\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); } @Test - public void testCalwithToArray() { + public void testCallwithToArray() { Tropo tropo = new Tropo(); - tropo.call(TO("+14155551212","+15105551212"), FROM("bar"), NETWORK(Network.SMS), CHANNEL(Channel.TEXT), TIMEOUT(10.0f), ANSWER_ON_MEDIA(false),ALLOW_SIGNALS("exit","stopHold")); + tropo.call(Key.TO("+14155551212","+15105551212"), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false),Key.ALLOW_SIGNALS("exit","stopHold")); - assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":[\"+14155551212\",\"+15105551212\"],\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10,\"answerOnMedia\":false,\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":[\"+14155551212\",\"+15105551212\"],\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10.0,\"answerOnMedia\":false,\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); } @Test @@ -96,30 +95,63 @@ public void testFailsCallWithNoToParameter() { Tropo tropo = new Tropo(); try { - tropo.call(NETWORK(Network.SMS)); + tropo.call(Key.NETWORK(Network.SMS)); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Missing required property: 'to'"); } } + @Deprecated + public void testFailsCallWithNoNameParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.call(Key.TO("+13055551212")); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'name'"); + } + } + @Test public void testCallWithHeadersTraditional() { Tropo tropo = new Tropo(); - CallAction call = tropo.call(TO("foo"), FROM("bar"), NETWORK(Network.SMS), CHANNEL(Channel.TEXT), TIMEOUT(10.0f), ANSWER_ON_MEDIA(false)); + CallAction call = tropo.call(Key.TO("foo"), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false)); call.headers(new String[]{"fooKey","fooValue"}, new String[]{"barKey","barValue"}); - assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10,\"answerOnMedia\":false,\"headers\":{\"fooKey\":\"fooValue\",\"barKey\":\"barValue\"}}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10.0,\"answerOnMedia\":false,\"headers\":{\"fooKey\":\"fooValue\",\"barKey\":\"barValue\"}}}]}"); } @Test - public void testCallWithStartRecordingTraditional() { + public void testNewCallWithHeadersTraditional() { + + Tropo tropo = new Tropo(); + Map map = new LinkedHashMap(); + map.put("fooKey", "fooValue"); + map.put("barKey", "barValue"); + tropo.call(Key.TO("foo"), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false), Key.HEADERS(map)); + + assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10.0,\"answerOnMedia\":false,\"headers\":{\"fooKey\":\"fooValue\",\"barKey\":\"barValue\"}}}]}"); + } + + @Test + public void testMachineDetectionIsBoolean() { + + Tropo tropo = new Tropo(); + tropo.call(Key.TO("foo"), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false), Key.MACHINE_DETECTION(true)); + + assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10.0,\"answerOnMedia\":false,\"machineDetection\":true}}]}"); + } + + @Test + public void testMachineDetection() { + + Tropo tropo = new Tropo(); + tropo.call(Key.TO("foo"), Key.FROM("bar"), Key.NETWORK(Network.SMS), Key.CHANNEL(Channel.TEXT), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false), Key.MACHINE_DETECTION("If set to true, two parameters are available -- introduction and voice, and the field will be a Hash.", Voice.TOM)); + + assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10.0,\"answerOnMedia\":false,\"machineDetection\":{\"introduction\":\"If set to true, two parameters are available -- introduction and voice, and the field will be a Hash.\",\"voice\":\"tom\"}}}]}"); + } - Tropo tropo = new Tropo(); - CallAction call = tropo.call(TO("foo"), FROM("bar"), NETWORK(Network.SMS), CHANNEL(Channel.TEXT), TIMEOUT(10.0f), ANSWER_ON_MEDIA(false)); - call.startRecording(URL("http://foobar"), METHOD("POST"), FORMAT(Format.MP3), USERNAME("jose"), PASSWORD("passwd")); - - assertEquals(tropo.text(),"{\"tropo\":[{\"call\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10,\"answerOnMedia\":false,\"startRecording\":{\"url\":\"http://foobar\",\"method\":\"POST\",\"format\":\"audio/mp3\",\"username\":\"jose\",\"password\":\"passwd\"}}}]}"); - } } diff --git a/src/test/java/com/voxeo/tropo/ChoicesTest.java b/src/test/java/com/voxeo/tropo/ChoicesTest.java index 19367c5..c156e30 100644 --- a/src/test/java/com/voxeo/tropo/ChoicesTest.java +++ b/src/test/java/com/voxeo/tropo/ChoicesTest.java @@ -1,6 +1,7 @@ package com.voxeo.tropo; import static com.voxeo.tropo.Key.MODE; +import static com.voxeo.tropo.Key.TERMINATOR; import static com.voxeo.tropo.Key.TO; import static com.voxeo.tropo.Key.VALUE; import static org.junit.Assert.assertEquals; @@ -39,5 +40,23 @@ public void testChoicesFailsWithInvalidElement() { } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'to' for action"); } - } + } + + @Test + public void testChoiceWithTerminator() { + + Tropo tropo = new Tropo(); + tropo.choices(TERMINATOR("#")); + + assertEquals(tropo.text(),"{\"tropo\":[{\"choices\":{\"terminator\":\"#\"}}]}"); + } + + @Test + public void testChoiceWithModeAny() { + + Tropo tropo = new Tropo(); + tropo.choices(VALUE("[5 DIGITS]"), MODE(Mode.ANY)); + + assertEquals(tropo.text(),"{\"tropo\":[{\"choices\":{\"value\":\"[5 DIGITS]\",\"mode\":\"any\"}}]}"); + } } diff --git a/src/test/java/com/voxeo/tropo/ConferenceActionTest.java b/src/test/java/com/voxeo/tropo/ConferenceActionTest.java index 4c00e3a..be1cd25 100644 --- a/src/test/java/com/voxeo/tropo/ConferenceActionTest.java +++ b/src/test/java/com/voxeo/tropo/ConferenceActionTest.java @@ -1,12 +1,11 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; -import com.voxeo.tropo.actions.Do; +import com.voxeo.tropo.enums.Voice; public class ConferenceActionTest { @@ -14,48 +13,36 @@ public class ConferenceActionTest { public void testConference() { Tropo tropo = new Tropo(); - tropo.conference(NAME("foo"),ID("1234"),MUTE(false),SEND_TONES(false),EXIT_TONE("#"),INTERDIGIT_TIMEOUT(5)); + tropo.conference(Key.ID("1234"),Key.MUTE(false),Key.PLAY_TONES(false),Key.INTERDIGIT_TIMEOUT(3.5F),Key.REQUIRED(true),Key.TERMINATOR("#")); - assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"name\":\"foo\",\"id\":\"1234\",\"mute\":false,\"send_tones\":false,\"exit_tone\":\"#\",\"interdigitTimeout\":5}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"id\":\"1234\",\"mute\":false,\"playTones\":false,\"interdigitTimeout\":3.5,\"required\":true,\"terminator\":\"#\"}}]}"); } @Test - public void testConferenceWithSingleOnAndSayBlocks() { + public void testConferenceWithBooleanValueOnJoinAndLeavePrompt() { Tropo tropo = new Tropo(); - tropo - .conference(NAME("foo"),ID("1234"),MUTE(false),SEND_TONES(false),EXIT_TONE("#")).and( - Do.on(EVENT("join")).and( - Do.say("Welcome to the conference") - ) - ); + tropo.conference(Key.ID("1234"),Key.MUTE(false),Key.PLAY_TONES(false),Key.JOIN_PROMPT(true),Key.LEAVE_PROMPT(true)); - assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"name\":\"foo\",\"id\":\"1234\",\"mute\":false,\"send_tones\":false,\"exit_tone\":\"#\",\"on\":[{\"event\":\"join\",\"say\":[{\"value\":\"Welcome to the conference\"}]}]}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"id\":\"1234\",\"mute\":false,\"playTones\":false,\"joinPrompt\":true,\"leavePrompt\":true}}]}"); } @Test - public void testConferenceWithSingleOnAndSayMethods() { + public void testConferenceWithDefaultVoiceOnJoinAndLeavePrompt() { Tropo tropo = new Tropo(); - tropo - .conference(NAME("foo"),ID("1234"),MUTE(false),SEND_TONES(false),EXIT_TONE("#")).and( - Do.on(EVENT("join")).say("Welcome to the conference") - ); + tropo.conference(Key.ID("1234"),Key.MUTE(false),Key.PLAY_TONES(false),Key.JOIN_PROMPT("Welcome to the conference"),Key.LEAVE_PROMPT("Someone leaves the conference")); - assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"name\":\"foo\",\"id\":\"1234\",\"mute\":false,\"send_tones\":false,\"exit_tone\":\"#\",\"on\":[{\"event\":\"join\",\"say\":[{\"value\":\"Welcome to the conference\"}]}]}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"id\":\"1234\",\"mute\":false,\"playTones\":false,\"joinPrompt\":{\"value\":\"Welcome to the conference\"},\"leavePrompt\":{\"value\":\"Someone leaves the conference\"}}}]}"); } @Test - public void testConferenceWithSeveralOnAndSayBlocks() { + public void testConferenceWithSpecificVoiceOnJoinAndLeavePrompt() { Tropo tropo = new Tropo(); - tropo - .conference(NAME("foo"),ID("1234"),MUTE(false),SEND_TONES(false),EXIT_TONE("#")).and( - Do.on(EVENT("join")).say("Welcome to the conference"), - Do.on(EVENT("leave")).say("Someone has left the conference") - ); + tropo.conference(Key.ID("1234"),Key.MUTE(false),Key.PLAY_TONES(false),Key.JOIN_PROMPT("Welcome to the conference",Voice.KATE),Key.LEAVE_PROMPT("Someone leaves the conference",Voice.KATE)); - assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"name\":\"foo\",\"id\":\"1234\",\"mute\":false,\"send_tones\":false,\"exit_tone\":\"#\",\"on\":[{\"event\":\"join\",\"say\":[{\"value\":\"Welcome to the conference\"}]},{\"event\":\"leave\",\"say\":[{\"value\":\"Someone has left the conference\"}]}]}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"id\":\"1234\",\"mute\":false,\"playTones\":false,\"joinPrompt\":{\"voice\":\"kate\",\"value\":\"Welcome to the conference\"},\"leavePrompt\":{\"voice\":\"kate\",\"value\":\"Someone leaves the conference\"}}}]}"); } @Test @@ -63,19 +50,31 @@ public void testFailsConferenceWithNoIdParameter() { Tropo tropo = new Tropo(); try { - tropo.conference(NAME("bar")); + tropo.conference(Key.NAME("bar")); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Missing required property: 'id'"); } } + @Deprecated + public void testFailsConferenceWithNoNameParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.conference(Key.ID("1234")); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'name'"); + } + } + @Test public void testConferenceFailsWithInvalidElement() { Tropo tropo = new Tropo(); try { - tropo.conference(TO("foo"),ID("1234"),MUTE(false),SEND_TONES(false),EXIT_TONE("#")); + tropo.conference(Key.TO("foo"),Key.ID("1234"),Key.NAME("foo")); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'to' for action"); @@ -86,8 +85,17 @@ public void testConferenceFailsWithInvalidElement() { public void testAllowSignals() { Tropo tropo = new Tropo(); - tropo.conference(NAME("foo"),ID("1234"),MUTE(false),SEND_TONES(false),EXIT_TONE("#"),ALLOW_SIGNALS("exit","stopHold")); + tropo.conference(Key.ID("1234"),Key.MUTE(false),Key.PLAY_TONES(false),Key.TERMINATOR("#"),Key.ALLOW_SIGNALS("exit","quit","bye")); + + assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"id\":\"1234\",\"mute\":false,\"playTones\":false,\"terminator\":\"#\",\"allowSignals\":[\"exit\",\"quit\",\"bye\"]}}]}"); + } + + @Test + public void testPromptLogSecurity() { + + Tropo tropo = new Tropo(); + tropo.conference(Key.ID("1234"),Key.MUTE(false),Key.PLAY_TONES(false),Key.TERMINATOR("#"),Key.PROMPT_LOG_SECURITY()); - assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"name\":\"foo\",\"id\":\"1234\",\"mute\":false,\"send_tones\":false,\"exit_tone\":\"#\",\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"conference\":{\"id\":\"1234\",\"mute\":false,\"playTones\":false,\"terminator\":\"#\",\"promptLogSecurity\":\"suppress\"}}]}"); } } diff --git a/src/test/java/com/voxeo/tropo/GeneralLogSecurityActionTest.java b/src/test/java/com/voxeo/tropo/GeneralLogSecurityActionTest.java new file mode 100644 index 0000000..f4b1281 --- /dev/null +++ b/src/test/java/com/voxeo/tropo/GeneralLogSecurityActionTest.java @@ -0,0 +1,23 @@ +package com.voxeo.tropo; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.voxeo.tropo.enums.LogSecurityState; + +public class GeneralLogSecurityActionTest { + + @Test + public void testGeneralLogSecurity() { + + Tropo tropo = new Tropo(); + tropo.generalLogSecurity(LogSecurityState.SUPPRESS); + tropo.say("this is not logged", "nolog"); + tropo.generalLogSecurity(LogSecurityState.NONE); + tropo.say("this will be logged", "log"); + + assertEquals(tropo.text(), + "{\"tropo\":[{\"generalLogSecurity\":\"suppress\"},{\"say\":[{\"value\":\"this is not logged\",\"name\":\"nolog\"}]},{\"generalLogSecurity\":\"none\"},{\"say\":[{\"value\":\"this will be logged\",\"name\":\"log\"}]}]}"); + } +} diff --git a/src/test/java/com/voxeo/tropo/HangupTest.java b/src/test/java/com/voxeo/tropo/HangupTest.java new file mode 100644 index 0000000..0a48a6e --- /dev/null +++ b/src/test/java/com/voxeo/tropo/HangupTest.java @@ -0,0 +1,43 @@ +package com.voxeo.tropo; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class HangupTest { + + @Test + public void testHangup() { + + Tropo tropo = new Tropo(); + tropo.hangup(); + + assertEquals(tropo.text(), "{\"tropo\":[{\"hangup\":null}]}"); + } + + @Test + public void testHangupWithSay() { + + Tropo tropo = new Tropo(); + tropo.say(Key.NAME("say1"), Key.VALUE("Hello,this is tropo.com")); + tropo.hangup(); + tropo.say(Key.NAME("say2"), Key.VALUE( + "Tropo makes it easy to add capabilities like calls, text messages, and conferences into any application or business process.")); + + assertEquals(tropo.text(), + "{\"tropo\":[{\"say\":[{\"name\":\"say1\",\"value\":\"Hello,this is tropo.com\"}]},{\"hangup\":null},{\"say\":[{\"name\":\"say2\",\"value\":\"Tropo makes it easy to add capabilities like calls, text messages, and conferences into any application or business process.\"}]}]}"); + } + + @Test + public void testHangupWithCall() { + Tropo tropo = new Tropo(); + tropo.call("call", "+14155551212"); + tropo.say(Key.NAME("say1"), Key.VALUE("Hello,this is tropo.com")); + tropo.hangup(); + tropo.say(Key.NAME("say2"), Key.VALUE( + "Tropo makes it easy to add capabilities like calls, text messages, and conferences into any application or business process.")); + + assertEquals(tropo.text(), + "{\"tropo\":[{\"call\":{\"name\":\"call\",\"to\":\"+14155551212\"}},{\"say\":[{\"name\":\"say1\",\"value\":\"Hello,this is tropo.com\"}]},{\"hangup\":null},{\"say\":[{\"name\":\"say2\",\"value\":\"Tropo makes it easy to add capabilities like calls, text messages, and conferences into any application or business process.\"}]}]}"); + } +} diff --git a/src/test/java/com/voxeo/tropo/MessageActionTest.java b/src/test/java/com/voxeo/tropo/MessageActionTest.java index 22f10ec..3f8cab1 100644 --- a/src/test/java/com/voxeo/tropo/MessageActionTest.java +++ b/src/test/java/com/voxeo/tropo/MessageActionTest.java @@ -3,24 +3,18 @@ import static com.voxeo.tropo.Key.ANSWER_ON_MEDIA; import static com.voxeo.tropo.Key.BARGEIN; import static com.voxeo.tropo.Key.CHANNEL; -import static com.voxeo.tropo.Key.FORMAT; import static com.voxeo.tropo.Key.FROM; -import static com.voxeo.tropo.Key.METHOD; import static com.voxeo.tropo.Key.NETWORK; -import static com.voxeo.tropo.Key.PASSWORD; import static com.voxeo.tropo.Key.TIMEOUT; -import static com.voxeo.tropo.Key.TO; -import static com.voxeo.tropo.Key.URL; -import static com.voxeo.tropo.Key.USERNAME; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; -import com.voxeo.tropo.actions.Do; +import com.voxeo.tropo.actions.MessageAction.Say; import com.voxeo.tropo.enums.Channel; -import com.voxeo.tropo.enums.Format; import com.voxeo.tropo.enums.Network; +import com.voxeo.tropo.enums.Voice; public class MessageActionTest { @@ -28,12 +22,9 @@ public class MessageActionTest { public void testMessage() { Tropo tropo = new Tropo(); - tropo.message(TO("foo"), FROM("bar"), NETWORK(Network.SMS), CHANNEL(Channel.TEXT), TIMEOUT(10.0f), ANSWER_ON_MEDIA(false)).and( - Do.headers(new String[]{"fooKey","fooValue"}, new String[]{"barKey","barValue"}), - Do.startRecording(URL("http://foobar"), METHOD("POST"), FORMAT(Format.MP3), USERNAME("jose"), PASSWORD("passwd")), - Do.say("Please say your account number")); + tropo.message(Key.SAY_OF_MESSAGE(new Say("This is an announcement"), new Say("Remember, you have a meeting at 2 PM")), Key.TO("305551212"), Key.ANSWER_ON_MEDIA(false), Key.CHANNEL(Channel.VOICE), Key.FROM("3055551000"),Key.NETWORK(Network.PSTN), Key.REQUIRED(true), Key.TIMEOUT(10.1f), Key.VOICE(Voice.TOM), Key.PROMPT_LOG_SECURITY()); - assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"to\":\"foo\",\"from\":\"bar\",\"network\":\"SMS\",\"channel\":\"TEXT\",\"timeout\":10,\"answerOnMedia\":false,\"headers\":{\"fooKey\":\"fooValue\",\"barKey\":\"barValue\"},\"startRecording\":{\"url\":\"http://foobar\",\"method\":\"POST\",\"format\":\"audio/mp3\",\"username\":\"jose\",\"password\":\"passwd\"},\"say\":[{\"value\":\"Please say your account number\"}]}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"say\":[{\"value\":\"This is an announcement\"},{\"value\":\"Remember, you have a meeting at 2 PM\"}],\"to\":\"305551212\",\"answerOnMedia\":false,\"channel\":\"VOICE\",\"from\":\"3055551000\",\"network\":\"PSTN\",\"required\":true,\"timeout\":10.1,\"voice\":\"tom\",\"promptLogSecurity\":\"suppress\"}}]}"); } @Test @@ -48,59 +39,89 @@ public void testMessageFailsWithInvalidElement() { } @Test - public void testMessageAndSay() { + public void testMessageShowSMS() { Tropo tropo = new Tropo(); - tropo.message(TO("+13055551212"), NETWORK(Network.SMS)).say("This is an announcement"); + tropo.message(Key.SAY_OF_MESSAGE(new Say("This is an announcement")), Key.TO("+13055551212"), Key.NETWORK(Network.SMS)); - assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"to\":\"+13055551212\",\"network\":\"SMS\",\"say\":[{\"value\":\"This is an announcement\"}]}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"say\":[{\"value\":\"This is an announcement\"}],\"to\":\"+13055551212\",\"network\":\"SMS\"}}]}"); } @Test - public void testMessageTraditionalWithTo() { + public void testMessageWithVoice() { - Tropo tropo = new Tropo(); - tropo.message("+13055551212"); - - assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"to\":\"+13055551212\"}}]}"); - } + Tropo tropo = new Tropo(); + tropo.message(Key.SAY_OF_MESSAGE(new Say("This is an announcement")), Key.TO("+13055551212"), Key.FROM("3055551000"), Key.VOICE(Voice.KATE), Key.TIMEOUT(10.0f), Key.ANSWER_ON_MEDIA(false)); + + assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"say\":[{\"value\":\"This is an announcement\"}],\"to\":\"+13055551212\",\"from\":\"3055551000\",\"voice\":\"kate\",\"timeout\":10.0,\"answerOnMedia\":false}}]}"); + } @Test - public void testMessageTraditionalWithToAndNetwork() { + public void testFailsMessageWithNoToParameter() { Tropo tropo = new Tropo(); - tropo.message("+13055551212",Network.SMS); - - assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"to\":\"+13055551212\",\"network\":\"SMS\"}}]}"); + try { + tropo.message(Key.NETWORK(Network.SMS)); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'to'"); + } } @Test - public void testMessageTraditionalWithToAndNetworkAndFrom() { + public void testFailsMessageWithNoSayParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.message(Key.TO("+13055551212")); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'say'"); + } + } + + @Deprecated + public void testFailsMessageWithNoNameParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.message(Key.TO("+13055551212"), Key.SAY_OF_MESSAGE(new Say("This is an announcement"))); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'name'"); + } + } - Tropo tropo = new Tropo(); - tropo.message("+13055551212",Network.SMS,"+13055551234"); - - assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"to\":\"+13055551212\",\"network\":\"SMS\",\"from\":\"+13055551234\"}}]}"); - } + @Test + public void testFailsMessageWithNoSayValue() { + + Tropo tropo = new Tropo(); + try { + tropo.message(Key.SAY_OF_MESSAGE(new Say(null)), Key.TO("+13055551212"), Key.NAME("message")); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of message.say"); + } + } @Test - public void testMessageTraditionalWithToAndNetworkAndFromAndChannel() { + public void testFailsMessageWithNoSayValue1() { + + Tropo tropo = new Tropo(); + try { + tropo.message(Key.SAY_OF_MESSAGE(new Say("")), Key.TO("+13055551212"), Key.NAME("message")); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of message.say"); + } + } - Tropo tropo = new Tropo(); - tropo.message("+13055551212",Network.SMS,"+13055551234",Channel.TEXT); - - assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"to\":\"+13055551212\",\"network\":\"SMS\",\"from\":\"+13055551234\",\"channel\":\"TEXT\"}}]}"); - } - @Test - public void testFailsMessageWithNoToParameter() { + public void testMessageShowMMS() { - Tropo tropo = new Tropo(); - try { - tropo.message(NETWORK(Network.SMS)).say("This is an announcement"); - fail("Expected exception in test"); - } catch (TropoException te) { - assertEquals(te.getMessage(), "Missing required property: 'to'"); - } - } + Tropo tropo = new Tropo(); + tropo.message(Key.SAY_OF_MESSAGE(new Say("This is the subject", new String[]{"http://server.com/1.jpg","this is a inline text content","http://filehosting.tropo.com/account/1/2.text"})), Key.TO("+13055551212"), Key.NETWORK(Network.MMS)); + + assertEquals(tropo.text(),"{\"tropo\":[{\"message\":{\"say\":[{\"value\":\"This is the subject\",\"media\":[\"http://server.com/1.jpg\",\"this is a inline text content\",\"http://filehosting.tropo.com/account/1/2.text\"]}],\"to\":\"+13055551212\",\"network\":\"MMS\"}}]}"); + } } diff --git a/src/test/java/com/voxeo/tropo/OnActionTest.java b/src/test/java/com/voxeo/tropo/OnActionTest.java index 017c3ad..0d4a118 100644 --- a/src/test/java/com/voxeo/tropo/OnActionTest.java +++ b/src/test/java/com/voxeo/tropo/OnActionTest.java @@ -1,86 +1,65 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; -import com.voxeo.tropo.actions.Do; - public class OnActionTest { @Test public void testOn() { Tropo tropo = new Tropo(); - tropo.on(EVENT("hangup"),NEXT("myresource")); + tropo.on(Key.EVENT("connect"),Key.NEXT("myresource"),Key.SAY_OF_ON("Nice answer!"),Key.POST("http://example.com/tropo")); - assertEquals(tropo.text(), "{\"tropo\":[{\"on\":{\"event\":\"hangup\",\"next\":\"myresource\"}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"on\":{\"event\":\"connect\",\"next\":\"myresource\",\"say\":[{\"value\":\"Nice answer!\"}],\"post\":\"http://example.com/tropo\"}}]}"); } - @Test - public void testOnWithValue() { - - Tropo tropo = new Tropo(); - tropo.on(EVENT("hangup"),VALUE("Sorry. We are hanging up.")); - - assertEquals(tropo.text(), "{\"tropo\":[{\"on\":{\"event\":\"hangup\",\"value\":\"Sorry. We are hanging up.\"}}]}"); - } - @Test public void testFailsOnWithNoEventParameter() { Tropo tropo = new Tropo(); try { - tropo.on(NEXT("myresource")); + tropo.on(Key.NEXT("myresource")); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Missing required property: 'event'"); } } + + @Test + public void testFailsOnWithNoSayvalue() { + + Tropo tropo = new Tropo(); + try { + tropo.on(Key.EVENT("hangup"),Key.NEXT("myresource"),Key.SAY_OF_ON(new com.voxeo.tropo.actions.OnAction.Say(null))); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of on.say"); + } + } + + @Test + public void testFailsOnWithNoSayvalue1() { + + Tropo tropo = new Tropo(); + try { + tropo.on(Key.EVENT("hangup"),Key.NEXT("myresource"),Key.SAY_OF_ON(new com.voxeo.tropo.actions.OnAction.Say(""))); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of on.say"); + } + } @Test public void testOnFailsWithInvalidElement() { Tropo tropo = new Tropo(); try { - tropo.on(TO("hangup"),NEXT("myresource")); + tropo.on(Key.TO("hangup"),Key.NEXT("myresource")); } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'to' for action"); } } - - @Test - public void testOnTraditionalWay() { - - Tropo tropo = new Tropo(); - tropo.on("hangup","myresource"); - - assertEquals(tropo.text(), "{\"tropo\":[{\"on\":{\"event\":\"hangup\",\"next\":\"myresource\"}}]}"); - } - - @Test - public void testOnAndSay() { - - Tropo tropo = new Tropo(); - tropo.and( - Do.on(EVENT("error"),NEXT("error.json")), - Do.say(VALUE("blah"))); - - assertEquals(tropo.text(), "{\"tropo\":[{\"on\":[{\"event\":\"error\",\"next\":\"error.json\"}]},{\"say\":[{\"value\":\"blah\"}]}]}"); - } - - - @Test - public void testOnNestedSay() { - - Tropo tropo = new Tropo(); - tropo.ask(NAME("foo"),BARGEIN(true),TIMEOUT(30.0f),REQUIRED(true)).and( - Do.say("Log in as voice, text, or log out"), - Do.on(EVENT("success"),NEXT("/tropoResultIn")).say("Oh Kay") - ); - - assertEquals(tropo.text(), "{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"bargein\":true,\"timeout\":30,\"required\":true,\"say\":[{\"value\":\"Log in as voice, text, or log out\"}],\"on\":[{\"event\":\"success\",\"next\":\"/tropoResultIn\",\"say\":[{\"value\":\"Oh Kay\"}]}]}}]}"); - } } diff --git a/src/test/java/com/voxeo/tropo/RecordActionTest.java b/src/test/java/com/voxeo/tropo/RecordActionTest.java index 519295b..935bb42 100644 --- a/src/test/java/com/voxeo/tropo/RecordActionTest.java +++ b/src/test/java/com/voxeo/tropo/RecordActionTest.java @@ -1,6 +1,5 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -8,6 +7,8 @@ import com.voxeo.tropo.actions.Do; import com.voxeo.tropo.actions.RecordAction; +import com.voxeo.tropo.actions.RecordAction.Say; +import com.voxeo.tropo.actions.RecordAction.Url; import com.voxeo.tropo.enums.Voice; public class RecordActionTest { @@ -16,17 +17,17 @@ public class RecordActionTest { public void testRecord() { Tropo tropo = new Tropo(); - tropo.record(NAME("foo"),URL("http://sendme.com/tropo"),BEEP(true),SEND_TONES(false),EXIT_TONE("#"),INTERDIGIT_TIMEOUT(5)); + tropo.record(Key.URL("http://sendme.com/tropo"),Key.BEEP(true),Key.INTERDIGIT_TIMEOUT(5f), Key.MAX_TIME(300.0f), Key.ASYNC_UPLOAD(true)); - assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"name\":\"foo\",\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"send_tones\":false,\"exit_tone\":\"#\",\"interdigitTimeout\":5}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"interdigitTimeout\":5.0,\"maxTime\":300.0,\"asyncUpload\":true}}]}"); } - @Test + @Deprecated public void testFailsRecordWithNoNameParameter() { Tropo tropo = new Tropo(); try { - tropo.record(URL("http://sendme.com/tropo"),BEEP(true),SEND_TONES(false),EXIT_TONE("#")); + tropo.record(Key.URL("http://sendme.com/tropo"),Key.BEEP(true)); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Missing required property: 'name'"); @@ -38,7 +39,7 @@ public void testFailsRecordWithNoUrlParameter() { Tropo tropo = new Tropo(); try { - tropo.record(NAME("foo"),BEEP(true),SEND_TONES(false),EXIT_TONE("#")); + tropo.record(Key.NAME("foo"),Key.BEEP(true)); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Missing required property: 'url'"); @@ -51,32 +52,59 @@ public void testFailsRecordWithInvalidUrls() { Tropo tropo = new Tropo(); try { - tropo.record(NAME("foo"),URL("invalid"), BEEP(true),SEND_TONES(false),EXIT_TONE("#")); + tropo.record(Key.NAME("foo"),Key.URL("invalid")); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "The 'url' parameter must be a valid URL"); } } - + @Test - public void testRecordAcceptsEmailAddress() { - - Tropo tropo = new Tropo(); - tropo.record(NAME("foo"),URL("mailto:foo@bar.com"),BEEP(true),SEND_TONES(false),EXIT_TONE("#")); - - assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"name\":\"foo\",\"url\":\"mailto:foo@bar.com\",\"beep\":true,\"send_tones\":false,\"exit_tone\":\"#\"}}]}"); - } + public void testFailsRecordWithInvalidSay() { + + Tropo tropo = new Tropo(); + try { + tropo.record(Key.NAME("foo"),Key.URL("http://sendme.com/tropo"),Key.SAY_OF_RECORD(new Say(null))); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of record.say"); + } + } + + @Test + public void testFailsRecordWithInvalidSay1() { + + Tropo tropo = new Tropo(); + try { + tropo.record(Key.NAME("foo"),Key.URL("http://sendme.com/tropo"),Key.SAY_OF_RECORD(new Say(""))); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: value of record.say"); + } + } + @Test + public void testFailsRecordWithInvalidSay2() { + + Tropo tropo = new Tropo(); + try { + tropo.record(Key.NAME("foo"),Key.URL("http://sendme.com/tropo"),Key.SAY_OF_RECORD(new Say("Sorry, I did not hear anything. Please call back.","nomatch:1"))); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "For record, the only possible event is 'timeout'."); + } + } + @Test public void testRecordWithTranscriptionRequest() { Tropo tropo = new Tropo(); - tropo.record(NAME("foo"), URL("http://sendme.com/tropo"), BEEP(true), SEND_TONES(true), EXIT_TONE("#")).and( - Do.transcription(ID("bling"), URL("mailto:jose@voxeo.com"), EMAIL_FORMAT("encoded")), - Do.say("Please say your account number"), - Do.choices(VALUE("[5 DIGITS]"))); + tropo.record(Key.URL("http://sendme.com/tropo"), Key.BEEP(true)).and( + Do.transcription(Key.ID("bling"), Key.URL("mailto:jose@voxeo.com"), Key.EMAIL_FORMAT("encoded"), Key.LANGUAGE("en-uk")), + Do.say("Please say your account number","say"), + Do.choices(Key.VALUE("[5 DIGITS]"))); - assertEquals(tropo.text(),"{\"tropo\":[{\"record\":{\"name\":\"foo\",\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"send_tones\":true,\"exit_tone\":\"#\",\"transcription\":{\"id\":\"bling\",\"url\":\"mailto:jose@voxeo.com\",\"emailFormat\":\"encoded\"},\"say\":[{\"value\":\"Please say your account number\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"record\":{\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"transcription\":{\"id\":\"bling\",\"url\":\"mailto:jose@voxeo.com\",\"emailFormat\":\"encoded\",\"language\":\"en-uk\"},\"say\":[{\"value\":\"Please say your account number\",\"name\":\"say\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); } @Test @@ -84,7 +112,7 @@ public void testRecordFailsWithInvalidElement() { Tropo tropo = new Tropo(); try { - tropo.record(TO("foo"),URL("http://sendme.com/tropo"),BEEP(true),SEND_TONES(false),EXIT_TONE("#")); + tropo.record(Key.TO("foo"),Key.URL("http://sendme.com/tropo"),Key.BEEP(true)); } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'to' for action"); } @@ -94,42 +122,42 @@ public void testRecordFailsWithInvalidElement() { public void testAllowSignals() { Tropo tropo = new Tropo(); - tropo.record(NAME("foo"),URL("http://sendme.com/tropo"),BEEP(true),SEND_TONES(false),EXIT_TONE("#"),ALLOW_SIGNALS("exit","stopHold")); + tropo.record(Key.URL("http://sendme.com/tropo"),Key.BEEP(true),Key.ALLOW_SIGNALS("exit","stopHold")); - assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"name\":\"foo\",\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"send_tones\":false,\"exit_tone\":\"#\",\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); } @Test public void testRecordTraditionalWay() { Tropo tropo = new Tropo(); - tropo.record("foo","http://sendme.com/tropo",true,false,"#"); + tropo.record("http://sendme.com/tropo",true); - assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"name\":\"foo\",\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"send_tones\":false,\"exit_tone\":\"#\"}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"url\":\"http://sendme.com/tropo\",\"beep\":true}}]}"); } @Test public void testRecordWithSayTranscriptionChoicesSplitted() { Tropo tropo = new Tropo(); - RecordAction record = tropo.record("foo","http://sendme.com/tropo",true,true,"#"); - record.transcription(ID("bling"), URL("mailto:jose@voxeo.com"), EMAIL_FORMAT("encoded")); - record.say(VALUE("Please say your account number")); - record.choices(VALUE("[5 DIGITS]")); + RecordAction record = tropo.record("http://sendme.com/tropo",true); + record.transcription(Key.ID("bling"), Key.URL("mailto:jose@voxeo.com"), Key.EMAIL_FORMAT("encoded"), Key.LANGUAGE("en-uk")); + record.say(Key.VALUE("Please say your account number")); + record.choices(Key.VALUE("[5 DIGITS]")); - assertEquals(tropo.text(),"{\"tropo\":[{\"record\":{\"name\":\"foo\",\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"send_tones\":true,\"exit_tone\":\"#\",\"transcription\":{\"id\":\"bling\",\"url\":\"mailto:jose@voxeo.com\",\"emailFormat\":\"encoded\"},\"say\":[{\"value\":\"Please say your account number\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"record\":{\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"transcription\":{\"id\":\"bling\",\"url\":\"mailto:jose@voxeo.com\",\"emailFormat\":\"encoded\",\"language\":\"en-uk\"},\"say\":[{\"value\":\"Please say your account number\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); } @Test public void testRecordWithSayTranscriptionChoicesEvenMoreTraditionalWay() { Tropo tropo = new Tropo(); - RecordAction record = tropo.record("foo","http://sendme.com/tropo",true,true,"#"); - record.transcription("bling", "mailto:jose@voxeo.com", "encoded"); + RecordAction record = tropo.record("http://sendme.com/tropo",true); + record.transcription("bling", "mailto:jose@voxeo.com", "encoded", "en-uk"); record.say("Please say your account number"); record.choices("[5 DIGITS]"); - assertEquals(tropo.text(),"{\"tropo\":[{\"record\":{\"name\":\"foo\",\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"send_tones\":true,\"exit_tone\":\"#\",\"transcription\":{\"id\":\"bling\",\"url\":\"mailto:jose@voxeo.com\",\"emailFormat\":\"encoded\"},\"say\":[{\"value\":\"Please say your account number\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); + assertEquals(tropo.text(),"{\"tropo\":[{\"record\":{\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"transcription\":{\"id\":\"bling\",\"url\":\"mailto:jose@voxeo.com\",\"emailFormat\":\"encoded\",\"language\":\"en-uk\"},\"say\":[{\"value\":\"Please say your account number\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); } @@ -137,8 +165,44 @@ public void testRecordWithSayTranscriptionChoicesEvenMoreTraditionalWay() { public void testRecordAcceptsVoice() { Tropo tropo = new Tropo(); - tropo.record(NAME("foo"),URL("http://sendme.com/tropo"),BEEP(true),SEND_TONES(false),EXIT_TONE("#"),VOICE(Voice.ALLISON)); + tropo.record(Key.URL("http://sendme.com/tropo"),Key.BEEP(true),Key.VOICE(Voice.ALLISON)); - assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"name\":\"foo\",\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"send_tones\":false,\"exit_tone\":\"#\",\"voice\":\"allison\"}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"url\":\"http://sendme.com/tropo\",\"beep\":true,\"voice\":\"allison\"}}]}"); } + + @Test + public void testRecordWithSensitivity() { + + Tropo tropo = new Tropo(); + tropo.record(Key.URL("http://sendme.com/tropo"),Key.SENSITIVITY(0.5F)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"url\":\"http://sendme.com/tropo\",\"sensitivity\":0.5}}]}"); + } + + @Test + public void testRecordUrl() { + + Tropo tropo = new Tropo(); + tropo.record(Key.URL(new Url("http://sendme.com/tropo")),Key.BEEP(true),Key.INTERDIGIT_TIMEOUT(5f), Key.MAX_TIME(300.0f), Key.ASYNC_UPLOAD(true)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"url\":{\"url\":\"http://sendme.com/tropo\"},\"beep\":true,\"interdigitTimeout\":5.0,\"maxTime\":300.0,\"asyncUpload\":true}}]}"); + } + + @Test + public void testRecordUrl1() { + + Tropo tropo = new Tropo(); + tropo.record(Key.URL(new Url("http://sendme.com/tropo"), new Url("http://sendme1.com/tropo")),Key.BEEP(true),Key.INTERDIGIT_TIMEOUT(5f), Key.MAX_TIME(300.0f), Key.ASYNC_UPLOAD(true)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"url\":[{\"url\":\"http://sendme.com/tropo\"},{\"url\":\"http://sendme1.com/tropo\"}],\"beep\":true,\"interdigitTimeout\":5.0,\"maxTime\":300.0,\"asyncUpload\":true}}]}"); + } + + @Test + public void testRecordUrl2() { + + Tropo tropo = new Tropo(); + tropo.record(Key.URL("http://sendme.com/tropo", "http://sendme1.com/tropo"),Key.BEEP(true),Key.INTERDIGIT_TIMEOUT(5f), Key.MAX_TIME(300.0f), Key.ASYNC_UPLOAD(true)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"record\":{\"url\":[{\"url\":\"http://sendme.com/tropo\"},{\"url\":\"http://sendme1.com/tropo\"}],\"beep\":true,\"interdigitTimeout\":5.0,\"maxTime\":300.0,\"asyncUpload\":true}}]}"); + } } diff --git a/src/test/java/com/voxeo/tropo/RedirectActionTest.java b/src/test/java/com/voxeo/tropo/RedirectActionTest.java index 4869998..2ed8e83 100644 --- a/src/test/java/com/voxeo/tropo/RedirectActionTest.java +++ b/src/test/java/com/voxeo/tropo/RedirectActionTest.java @@ -1,10 +1,5 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.BARGEIN; -import static com.voxeo.tropo.Key.FROM; -import static com.voxeo.tropo.Key.ID; -import static com.voxeo.tropo.Key.NAME; -import static com.voxeo.tropo.Key.TO; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -19,9 +14,9 @@ public class RedirectActionTest { public void testRedirect() { Tropo tropo = new Tropo(); - tropo.redirect(TO("sip:1234"),FROM("4155551212")); + tropo.redirect(Key.TO("sip:1234"),Key.REQUIRED(true)); - assertEquals(tropo.text(), "{\"tropo\":[{\"redirect\":{\"to\":\"sip:1234\",\"from\":\"4155551212\"}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"redirect\":{\"to\":\"sip:1234\",\"required\":true}}]}"); } @Test @@ -29,8 +24,8 @@ public void testFailsNestedRedirect() { Tropo tropo = new Tropo(); try { - tropo.conference(NAME("foo"),ID("1234")).and( - Do.redirect(TO("sip:1234"),FROM("4155551212"))); + tropo.conference(Key.NAME("foo"),Key.ID("1234")).and( + Do.redirect(Key.TO("sip:1234"),Key.NAME("redirect"))); fail("Expected exception in test"); } catch (TropoException te) { @@ -43,39 +38,34 @@ public void testFailsRedirectWithNoToParameter() { Tropo tropo = new Tropo(); try { - tropo.redirect(FROM("4155551212")); + tropo.redirect(Key.NAME("redirect")); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Missing required property: 'to'"); } } + @Deprecated + public void testFailsRedirectWithNoNameParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.redirect(Key.TO("sip:1234")); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'name'"); + } + } + @Test public void testRedirectFailsWithInvalidElement() { Tropo tropo = new Tropo(); try { - tropo.redirect(BARGEIN(true),FROM("4155551212")); + tropo.redirect(Key.BARGEIN(true)); } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'bargein' for action"); } } - @Test - public void testRedirectTraditional() { - - Tropo tropo = new Tropo(); - tropo.redirect("sip:1234","4155551212"); - - assertEquals(tropo.text(), "{\"tropo\":[{\"redirect\":{\"to\":\"sip:1234\",\"from\":\"4155551212\"}}]}"); - } - - @Test - public void testRedirectTraditional2() { - - Tropo tropo = new Tropo(); - tropo.redirect("sip:1234"); - - assertEquals(tropo.text(), "{\"tropo\":[{\"redirect\":{\"to\":\"sip:1234\"}}]}"); - } } diff --git a/src/test/java/com/voxeo/tropo/SayActionTest.java b/src/test/java/com/voxeo/tropo/SayActionTest.java index 03957e5..d2c1692 100644 --- a/src/test/java/com/voxeo/tropo/SayActionTest.java +++ b/src/test/java/com/voxeo/tropo/SayActionTest.java @@ -1,7 +1,7 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; @@ -29,37 +29,19 @@ public void testSay() { public void testSayWithKeyArgument() { Tropo tropo = new Tropo(); - tropo.say(VALUE("1234")); + tropo.say(Key.VALUE("1234")); assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"1234\"}]}]}"); } - @Test - public void testSayWithArrayArgument() { - - Tropo tropo = new Tropo(); - tropo.say(VALUE("1234")).say(VALUE("abcd"),EVENT("nomatch:1")); - - assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"1234\"},{\"value\":\"abcd\",\"event\":\"nomatch:1\"}]}]}"); - } - - @Test - public void testSayWithMoreThanTwoArrayArguments() { - - Tropo tropo = new Tropo(); - tropo.say(VALUE("1234")).say(VALUE("abcd"),EVENT("nomatch:1")).say(VALUE("zywx"),EVENT("nomatch:2")); - - assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"1234\"},{\"value\":\"abcd\",\"event\":\"nomatch:1\"},{\"value\":\"zywx\",\"event\":\"nomatch:2\"}]}]}"); - } - @Test public void testSayAndOn() { Tropo tropo = new Tropo(); - tropo.say(VALUE("blah")); - tropo.on(EVENT("error"),NEXT("error.json")); + tropo.say(Key.VALUE("blah")); + tropo.on(Key.EVENT("error"),Key.NEXT("error.json"),Key.SAY_OF_ON("say of on")); - assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"blah\"}]},{\"on\":{\"event\":\"error\",\"next\":\"error.json\"}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"blah\"}]},{\"on\":{\"event\":\"error\",\"next\":\"error.json\",\"say\":[{\"value\":\"say of on\"}]}}]}"); } @Test @@ -67,36 +49,36 @@ public void testFailsSayWithNoValueParameter() { Tropo tropo = new Tropo(); try { - tropo.say(VOICE(Voice.ALLISON)); + tropo.say(Key.VOICE(Voice.ALLISON)); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Missing required property: 'value'"); } } + + @Deprecated + public void testFailsSayWithNoNameParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.say(Key.VALUE("Hello")); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'name'"); + } + } @Test public void testSayAndOnWithAndSyntax() { Tropo tropo = new Tropo(); tropo.and( - Do.say(VALUE("blah")), - Do.on(EVENT("error"),NEXT("error.json"))); + Do.say(Key.VALUE("blah")), + Do.on(Key.EVENT("error"),Key.NEXT("error.json"))); assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"blah\"}]},{\"on\":[{\"event\":\"error\",\"next\":\"error.json\"}]}]}"); } - @Test - public void testTwoSaysWithArrays() { - - Tropo tropo = new Tropo(); - tropo.and( - Do.say(VALUE("1234")).say(VALUE("abcd"),EVENT("nomatch:1")), - Do.say(VALUE("0987")).say(VALUE("zyxw"),EVENT("nomatch:2")) - ); - - assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"1234\"},{\"value\":\"abcd\",\"event\":\"nomatch:1\"}]},{\"say\":[{\"value\":\"0987\"},{\"value\":\"zyxw\",\"event\":\"nomatch:2\"}]}]}"); - } - @Test public void testSeveralSayCallsTraditionalWay() { @@ -113,7 +95,7 @@ public void testSayFailsWithInvalidElement() { Tropo tropo = new Tropo(); try { - tropo.say(TO("test")); + tropo.say(Key.TO("test")); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'to' for action"); @@ -124,7 +106,7 @@ public void testSayFailsWithInvalidElement() { public void testAllowUnnamedSignals() { Tropo tropo = new Tropo(); - tropo.say(VALUE("blah"),ALLOW_SIGNALS()); + tropo.say(Key.VALUE("blah"),Key.ALLOW_SIGNALS()); assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"blah\",\"allowSignals\":\"\"}]}]}"); } @@ -133,7 +115,7 @@ public void testAllowUnnamedSignals() { public void testAllowSignals() { Tropo tropo = new Tropo(); - tropo.say(VALUE("blah"),ALLOW_SIGNALS("exit","stopHold")); + tropo.say(Key.VALUE("blah"),Key.ALLOW_SIGNALS("exit","stopHold")); assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"blah\",\"allowSignals\":[\"exit\",\"stopHold\"]}]}]}"); } @@ -142,7 +124,7 @@ public void testAllowSignals() { public void testVoicesInLowercases() { Tropo tropo = new Tropo(); - tropo.say(VALUE("blah"), VOICE(Voice.ALLISON)); + tropo.say(Key.VALUE("blah"), Key.VOICE(Voice.ALLISON)); assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"blah\",\"voice\":\"allison\"}]}]}"); } @@ -151,8 +133,17 @@ public void testVoicesInLowercases() { public void testAsParameter() { Tropo tropo = new Tropo(); - tropo.say(VALUE("blah"), AS(As.DATE)); + tropo.say(Key.VALUE("blah"), Key.AS(As.DATE)); assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"blah\",\"as\":\"DATE\"}]}]}"); } + + @Test + public void testSayWithMedias() { + + Tropo tropo = new Tropo(); + tropo.say(Key.VALUE("This is the subject"), Key.MEDIA("http://server.com/1.jpg", "this is a inline text content", "http://filehosting.tropo.com/account/1/2.text")); + + assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"This is the subject\",\"media\":[\"http://server.com/1.jpg\",\"this is a inline text content\",\"http://filehosting.tropo.com/account/1/2.text\"]}]}]}"); + } } diff --git a/src/test/java/com/voxeo/tropo/StartRecordingActionTest.java b/src/test/java/com/voxeo/tropo/StartRecordingActionTest.java index 043d3a7..a4f88ec 100644 --- a/src/test/java/com/voxeo/tropo/StartRecordingActionTest.java +++ b/src/test/java/com/voxeo/tropo/StartRecordingActionTest.java @@ -1,14 +1,14 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.EVENT; -import static com.voxeo.tropo.Key.NEXT; -import static com.voxeo.tropo.Key.TO; -import static com.voxeo.tropo.Key.URL; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import org.junit.Test; +import com.voxeo.tropo.actions.RecordAction.Url; +import com.voxeo.tropo.enums.EmailFormat; import com.voxeo.tropo.enums.Format; +import com.voxeo.tropo.enums.Method; public class StartRecordingActionTest { @@ -17,40 +17,47 @@ public class StartRecordingActionTest { public void testStartRecording() { Tropo tropo = new Tropo(); - tropo.startRecording(URL("http://postrecording.com/tropo")); + tropo.startRecording(Key.URL("http://postrecording.com/tropo"), Key.METHOD(Method.POST)); - assertEquals(tropo.text(), "{\"tropo\":[{\"startRecording\":{\"url\":\"http://postrecording.com/tropo\"}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"startRecording\":{\"url\":\"http://postrecording.com/tropo\",\"method\":\"POST\"}}]}"); } @Test - public void testStartRecordingLargeExample() { - + public void testStartRecordingWithTranscription() { + Tropo tropo = new Tropo(); - tropo.on(EVENT("error"), NEXT("/error.json")); // For fatal programming errors. Log some details so we can fix it - tropo.on(EVENT("hangup"), NEXT("/hangup.json")); // When a user hangs or call is done. We will want to log some details. - tropo.on(EVENT("continue"), NEXT("/next.json")); - tropo.say("Hello"); - tropo.startRecording(URL("http://heroku-voip.marksilver.net/post_audio_to_s3?filename=foo.wav&unique_id=bar")); - // [From this point, until stop_recording(), we will record what the caller *and* the IVR say] - tropo.say("You are now on the record."); - // Prompt the user to incriminate themselve on-the-record - tropo.say("Go ahead, sing-along."); - tropo.say("http://denalidomain.com/music/keepers/HappyHappyBirthdaytoYou-Disney.mp3"); + tropo.startRecording(Key.URL("http://postrecording.com/tropo"),Key.TRANSCRIPTION_OUT_URI("mailto:xxx@url.com"),Key.TRANSCRIPTION_EMAIL_FORMAT(EmailFormat.ENCODED),Key.TRANSCRIPTION_ID("1234"),Key.TRANSCRIPTION_LANGUAGE("pt-br")); - assertEquals(tropo.text(),"{\"tropo\":[{\"on\":{\"event\":\"error\",\"next\":\"/error.json\"}},{\"on\":{\"event\":\"hangup\",\"next\":\"/hangup.json\"}},{\"on\":{\"event\":\"continue\",\"next\":\"/next.json\"}},{\"say\":[{\"value\":\"Hello\"}]},{\"startRecording\":{\"url\":\"http://heroku-voip.marksilver.net/post_audio_to_s3?filename=foo.wav&unique_id=bar\"}},{\"say\":[{\"value\":\"You are now on the record.\"}]},{\"say\":[{\"value\":\"Go ahead, sing-along.\"}]},{\"say\":[{\"value\":\"http://denalidomain.com/music/keepers/HappyHappyBirthdaytoYou-Disney.mp3\"}]}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"startRecording\":{\"url\":\"http://postrecording.com/tropo\",\"transcriptionOutURI\":\"mailto:xxx@url.com\",\"transcriptionEmailFormat\":\"encoded\",\"transcriptionID\":\"1234\",\"transcriptionLanguage\":\"pt-br\"}}]}"); } @Test - public void testTransferFailsWithInvalidElement() { - + public void testStartRecordingWithAsyncUpload() { + Tropo tropo = new Tropo(); - try { - tropo.transfer(URL("tel:+14157044517")); - } catch (TropoException te) { - assertEquals(te.getMessage(), "Invalid key 'url' for action"); - } + tropo.startRecording(Key.URL("http://postrecording.com/tropo"),Key.ASYNC_UPLOAD(true)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"startRecording\":{\"url\":\"http://postrecording.com/tropo\",\"asyncUpload\":true}}]}"); } + @Test + public void testStartRecordingLargeExample() { + + Tropo tropo = new Tropo(); + tropo.on(Key.EVENT("error"), Key.NEXT("/error.json"), Key.SAY_OF_ON("error")); // For fatal programming errors. Log some details so we can fix it + tropo.on(Key.EVENT("hangup"), Key.NEXT("/hangup.json"),Key.SAY_OF_ON("hangup")); // When a user hangs or call is done. We will want to log some details. + tropo.on(Key.EVENT("continue"), Key.NEXT("/next.json"), Key.SAY_OF_ON("continue")); + tropo.say("Hello", "say"); + tropo.startRecording(Key.URL("http://heroku-voip.marksilver.net/post_audio_to_s3?filename=foo.wav&unique_id=bar")); + // [From this point, until stop_recording(), we will record what the caller *and* the IVR say] + tropo.say("You are now on the record.", "say"); + // Prompt the user to incriminate themselve on-the-record + tropo.say("Go ahead, sing-along.", "say"); + tropo.say("http://denalidomain.com/music/keepers/HappyHappyBirthdaytoYou-Disney.mp3", "say"); + + assertEquals(tropo.text(),"{\"tropo\":[{\"on\":{\"event\":\"error\",\"next\":\"/error.json\",\"say\":[{\"value\":\"error\"}]}},{\"on\":{\"event\":\"hangup\",\"next\":\"/hangup.json\",\"say\":[{\"value\":\"hangup\"}]}},{\"on\":{\"event\":\"continue\",\"next\":\"/next.json\",\"say\":[{\"value\":\"continue\"}]}},{\"say\":[{\"value\":\"Hello\",\"name\":\"say\"}]},{\"startRecording\":{\"url\":\"http://heroku-voip.marksilver.net/post_audio_to_s3?filename=foo.wav&unique_id=bar\"}},{\"say\":[{\"value\":\"You are now on the record.\",\"name\":\"say\"}]},{\"say\":[{\"value\":\"Go ahead, sing-along.\",\"name\":\"say\"}]},{\"say\":[{\"value\":\"http://denalidomain.com/music/keepers/HappyHappyBirthdaytoYou-Disney.mp3\",\"name\":\"say\"}]}]}"); + } + @Test public void testStartTraditionalWay() { @@ -78,14 +85,52 @@ public void testStartTraditionalWay3() { assertEquals(tropo.text(), "{\"tropo\":[{\"startRecording\":{\"url\":\"http://postrecording.com/tropo\",\"format\":\"audio/mp3\",\"username\":\"martin\",\"password\":\"pass\"}}]}"); } + @Test + public void testFailsStartRecordingWithNoUrlParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.startRecording(Key.ASYNC_UPLOAD(true)); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'url'"); + } + } + @Test public void testStartRecordingFailsWithInvalidElement() { Tropo tropo = new Tropo(); try { - tropo.startRecording(TO("http://postrecording.com/tropo")); + tropo.startRecording(Key.TO("http://postrecording.com/tropo")); } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'to' for action"); } } + + @Test + public void testStartRecordingAndUrl() { + + Tropo tropo = new Tropo(); + tropo.startRecording(Key.URL(new Url("http://postrecording.com/tropo")), Key.METHOD(Method.POST)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"startRecording\":{\"url\":{\"url\":\"http://postrecording.com/tropo\"},\"method\":\"POST\"}}]}"); + } + + @Test + public void testStartRecordingAndUrl1() { + + Tropo tropo = new Tropo(); + tropo.startRecording(Key.URL("http://postrecording.com/tropo", "http://postrecording1.com/tropo"), Key.METHOD(Method.POST)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"startRecording\":{\"url\":[{\"url\":\"http://postrecording.com/tropo\"},{\"url\":\"http://postrecording1.com/tropo\"}],\"method\":\"POST\"}}]}"); + } + @Test + public void testStartRecordingAndUr2() { + + Tropo tropo = new Tropo(); + tropo.startRecording(Key.URL(new Url("http://postrecording.com/tropo"), new Url("http://postrecording1.com/tropo")), Key.METHOD(Method.POST)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"startRecording\":{\"url\":[{\"url\":\"http://postrecording.com/tropo\"},{\"url\":\"http://postrecording1.com/tropo\"}],\"method\":\"POST\"}}]}"); + } } diff --git a/src/test/java/com/voxeo/tropo/TranscriptionTest.java b/src/test/java/com/voxeo/tropo/TranscriptionTest.java index d408734..0a20c6f 100644 --- a/src/test/java/com/voxeo/tropo/TranscriptionTest.java +++ b/src/test/java/com/voxeo/tropo/TranscriptionTest.java @@ -2,9 +2,7 @@ import static com.voxeo.tropo.Key.BEEP; import static com.voxeo.tropo.Key.EMAIL_FORMAT; -import static com.voxeo.tropo.Key.EXIT_TONE; import static com.voxeo.tropo.Key.NAME; -import static com.voxeo.tropo.Key.SEND_TONES; import static com.voxeo.tropo.Key.TO; import static com.voxeo.tropo.Key.URL; import static org.junit.Assert.assertEquals; @@ -20,7 +18,7 @@ public void testTranscriptionFailsWithInvalidElement() { Tropo tropo = new Tropo(); try { - tropo.record(NAME("foo"), URL("http://sendme.com/tropo"), BEEP(true), SEND_TONES(true), EXIT_TONE("#")).and( + tropo.record(NAME("foo"), URL("http://sendme.com/tropo"), BEEP(true)).and( Do.transcription(TO("bling"), URL("mailto:jose@voxeo.com"), EMAIL_FORMAT("encoded"))); } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'to' for action"); diff --git a/src/test/java/com/voxeo/tropo/TransferActionTest.java b/src/test/java/com/voxeo/tropo/TransferActionTest.java index abd6178..d84dfd5 100644 --- a/src/test/java/com/voxeo/tropo/TransferActionTest.java +++ b/src/test/java/com/voxeo/tropo/TransferActionTest.java @@ -1,109 +1,166 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.*; +import static com.voxeo.tropo.Key.EVENT; +import static com.voxeo.tropo.Key.NEXT; +import static com.voxeo.tropo.Key.VALUE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import java.util.LinkedHashMap; +import java.util.Map; + import org.junit.Test; +import com.voxeo.tropo.actions.AskAction.Say; import com.voxeo.tropo.actions.Do; import com.voxeo.tropo.actions.TransferAction; - +import com.voxeo.tropo.enums.Mode; +import com.voxeo.tropo.enums.Terminator; +import com.voxeo.tropo.enums.Voice; public class TransferActionTest { @Test public void testTransfer() { - + Tropo tropo = new Tropo(); - tropo.transfer(TO("tel:+14157044517")); - + tropo.transfer(Key.TO("tel:+14157044517")); + assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\"}}]}"); - } - + } + @Test public void testTransferWithOnAndChoices() { - + Tropo tropo = new Tropo(); - tropo.transfer(TO("tel:+14157044517")).and( - Do.on(EVENT("unbounded"), NEXT("/error.json")), - Do.choices(VALUE("[5 DIGITS]")) - ); - - assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"on\":[{\"event\":\"unbounded\",\"next\":\"/error.json\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); - } - - + tropo.transfer(Key.TO("tel:+14157044517"),Key.CHOICES(Terminator.POUND)).and( + Do.on(EVENT("unbounded"), NEXT("/error.json"))); + + assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"choices\":{\"terminator\":\"#\"},\"on\":[{\"event\":\"unbounded\",\"next\":\"/error.json\"}]}}]}"); + } + + + @Test + public void testTransferWithAnswerOnMedia() { + Tropo tropo = new Tropo(); + tropo.transfer(Key.TO("tel:+14157044517"),Key.ANSWER_ON_MEDIA(true)); + assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"answerOnMedia\":true}}]}"); + } + + @Test public void testTransferFailsWithInvalidElement() { Tropo tropo = new Tropo(); try { - tropo.transfer(TO("tel:+14157044517"), BEEP(true)); + tropo.transfer(Key.NAME("transfer"), Key.TO("tel:+14157044517"), Key.BEEP(true)); } catch (TropoException te) { assertEquals(te.getMessage(), "Invalid key 'beep' for action"); - } + } } - + @Test - public void testFailsRedirectWithNoToParameter() { + public void testTransferFailsWithNoToParameter() { Tropo tropo = new Tropo(); try { - tropo.transfer(FROM("4155551212")); + tropo.transfer(Key.FROM("4155551212")); fail("Expected exception in test"); } catch (TropoException te) { assertEquals(te.getMessage(), "Missing required property: 'to'"); } } + @Deprecated + public void testTransferFailsWithNoNameParameter() { + + Tropo tropo = new Tropo(); + try { + tropo.transfer(Key.TO("4155551212")); + fail("Expected exception in test"); + } catch (TropoException te) { + assertEquals(te.getMessage(), "Missing required property: 'name'"); + } + } + @Test public void testTransferTraditionalWay() { - + Tropo tropo = new Tropo(); tropo.transfer("tel:+14157044517"); - + assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\"}}]}"); - } + } @Test public void testTransferTraditionalWay2() { - + Tropo tropo = new Tropo(); - tropo.transfer("tel:+14157044517","tel:+14157044522"); - - assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"from\":\"tel:+14157044522\"}}]}"); + tropo.transfer("tel:+14157044517","tel:+14157044522","transfer"); + + assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"from\":\"tel:+14157044522\",\"name\":\"transfer\"}}]}"); } - + @Test public void testAllowSignals() { - + Tropo tropo = new Tropo(); - tropo.transfer(TO("tel:+14157044517"),ALLOW_SIGNALS("exit","stopHold")); - + tropo.transfer(Key.TO("tel:+14157044517"),Key.ALLOW_SIGNALS("exit","stopHold")); + assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"allowSignals\":[\"exit\",\"stopHold\"]}}]}"); } - + @Test public void testTransferWithHeadersTraditional() { Tropo tropo = new Tropo(); - TransferAction transfer = tropo.transfer(TO("tel:+14157044517")); + TransferAction transfer = tropo.transfer(Key.TO("tel:+14157044517")); transfer.headers(new String[]{"fooKey","fooValue"}, new String[]{"barKey","barValue"}); - assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"headers\":{\"fooKey\":\"fooValue\",\"barKey\":\"barValue\"}}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"headers\":{\"fooKey\":\"fooValue\",\"barKey\":\"barValue\"}}}]}"); } - - + + @Test + public void testTransferWithHeaders() { + + Tropo tropo = new Tropo(); + Map headers = new LinkedHashMap(); + headers.put("fooKey","fooValue"); + headers.put("barKey","barValue"); + tropo.transfer(Key.TO("tel:+14157044517"),Key.HEADERS(headers)); + + assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"headers\":{\"fooKey\":\"fooValue\",\"barKey\":\"barValue\"}}}]}"); + } + @Test public void testTransferWithOnAndChoicesTraditional() { - + Tropo tropo = new Tropo(); - TransferAction transfer = tropo.transfer(TO("tel:+14157044517")); + TransferAction transfer = tropo.transfer(Key.TO("tel:+14157044517")); transfer.on(EVENT("unbounded"), NEXT("/error.json")); transfer.choices(VALUE("[5 DIGITS]")); - + assertEquals(tropo.text(), "{\"tropo\":[{\"transfer\":{\"to\":\"tel:+14157044517\",\"on\":[{\"event\":\"unbounded\",\"next\":\"/error.json\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); - } + } + + @Test + public void testTransferWithOnAndAsk() { + + Tropo tropo = new Tropo(); + tropo.say(Key.VALUE("you are now being transfered")); + TransferAction transfer = tropo.transfer(Key.TO("14075550100"), Key.FROM("14075550122"), + Key.TIMEOUT(60f), Key.ANSWER_ON_MEDIA(false), Key.REQUIRED(true), Key.ALLOW_SIGNALS("exit", "quit"), + Key.MACHINE_DETECTION(false), Key.CHOICES(Terminator.ZERO), Key.INTERDIGIT_TIMEOUT(5.5f), Key.RING_REPEAT(5), + Key.PLAY_TONES(true), Key.VOICE(Voice.TOM), Key.CALLBACK_URL("http://localhost:8080/tropo"), + Key.LABEL("transferLabel")); + transfer.and(Do.on(Key.EVENT("ring")).say("http://www.phono.com/audio/holdmusic.mp3","say")); + transfer.and(Do.on(Key.EVENT("connect")).ask(Key.ATTEMPTS(3), + Key.SAY_OF_ASK(new Say("Sorry. Please enter you 5 digit account number again.", "nomatch"), + new Say("Sorry, I did not hear anything.", "timeout"), new Say("Please enter 5 digit account number")), + Key.REQUIRED(true), Key.BARGEIN(true), Key.TIMEOUT(10f), Key.NAME("ask"), + Key.CHOICES_OF_ASK(new com.voxeo.tropo.actions.AskAction.Choices("[5 DIGITS]", Mode.DTMF)))); + + assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"you are now being transfered\"}]},{\"transfer\":{\"to\":\"14075550100\",\"from\":\"14075550122\",\"timeout\":60.0,\"answerOnMedia\":false,\"required\":true,\"allowSignals\":[\"exit\",\"quit\"],\"machineDetection\":false,\"choices\":{\"terminator\":\"0\"},\"interdigitTimeout\":5.5,\"ringRepeat\":5,\"playTones\":true,\"voice\":\"tom\",\"callbackUrl\":\"http://localhost:8080/tropo\",\"label\":\"transferLabel\",\"on\":[{\"event\":\"ring\",\"say\":[{\"value\":\"http://www.phono.com/audio/holdmusic.mp3\",\"name\":\"say\"}]},{\"event\":\"connect\",\"ask\":{\"attempts\":3,\"say\":[{\"value\":\"Sorry. Please enter you 5 digit account number again.\",\"event\":\"nomatch\"},{\"value\":\"Sorry, I did not hear anything.\",\"event\":\"timeout\"},{\"value\":\"Please enter 5 digit account number\"}],\"required\":true,\"bargein\":true,\"timeout\":10.0,\"name\":\"ask\",\"choices\":{\"value\":\"[5 DIGITS]\",\"mode\":\"DTMF\"}}}]}}]}"); + } } diff --git a/src/test/java/com/voxeo/tropo/TropoTest.java b/src/test/java/com/voxeo/tropo/TropoTest.java index d4cd6e8..aa0956a 100644 --- a/src/test/java/com/voxeo/tropo/TropoTest.java +++ b/src/test/java/com/voxeo/tropo/TropoTest.java @@ -1,13 +1,32 @@ package com.voxeo.tropo; -import static com.voxeo.tropo.Key.*; -import static org.junit.Assert.*; +import static com.voxeo.tropo.Key.BARGEIN; +import static com.voxeo.tropo.Key.BEEP; +import static com.voxeo.tropo.Key.EVENT; +import static com.voxeo.tropo.Key.NAME; +import static com.voxeo.tropo.Key.NEXT; +import static com.voxeo.tropo.Key.REQUIRED; +import static com.voxeo.tropo.Key.TIMEOUT; +import static com.voxeo.tropo.Key.URL; +import static com.voxeo.tropo.Key.VALUE; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import javax.servlet.http.HttpServletRequest; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Before; import org.junit.Test; +import com.voxeo.tropo.actions.AskAction.Say; import com.voxeo.tropo.actions.Do; import com.voxeo.tropo.mock.MockHttpServletRequest; import com.voxeo.tropo.mock.MockHttpServletResponse; @@ -63,6 +82,8 @@ public void testParseJsonSessionWithParameters() { Tropo tropo = new Tropo(); TropoSession session = tropo.session(json_session); assertNotNull(session); + assertEquals(session.getAccountId(), "12345"); + assertEquals(session.getUserType(), "NONE"); assertNotNull(session.getParameters()); assertEquals(session.getParameters().get("token"),"token_id"); } @@ -84,22 +105,22 @@ public void testParseJsonSessionFromServletRequest() { public void testSayOnAndRecordTraditionalWay() { Tropo tropo = new Tropo(); - tropo.say("Welcome to the app"); - tropo.on(EVENT("hangup"), NEXT("/hangup.json")); - tropo.record(NAME("foo"), BEEP(true), SEND_TONES(false), EXIT_TONE("#"), URL("http://sendme.com/tropo")).and( - Do.say("Please say your account number"), + tropo.say("Welcome to the app", "say"); + tropo.on(EVENT("hangup"), NEXT("/hangup.json"), Key.SAY_OF_ON("hangup")); + tropo.record(NAME("foo"), BEEP(true), URL("http://sendme.com/tropo")).and( + Do.say("Please say your account number","say"), Do.choices(VALUE("[5 DIGITS]")) ); - assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"Welcome to the app\"}]},{\"on\":{\"event\":\"hangup\",\"next\":\"/hangup.json\"}},{\"record\":{\"name\":\"foo\",\"beep\":true,\"send_tones\":false,\"exit_tone\":\"#\",\"url\":\"http://sendme.com/tropo\",\"say\":[{\"value\":\"Please say your account number\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); + assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"Welcome to the app\",\"name\":\"say\"}]},{\"on\":{\"event\":\"hangup\",\"next\":\"/hangup.json\",\"say\":[{\"value\":\"hangup\"}]}},{\"record\":{\"name\":\"foo\",\"beep\":true,\"url\":\"http://sendme.com/tropo\",\"say\":[{\"value\":\"Please say your account number\",\"name\":\"say\"}],\"choices\":{\"value\":\"[5 DIGITS]\"}}}]}"); } @Test public void testReset() { Tropo tropo = new Tropo(); - tropo.ask(NAME("foo"), BARGEIN(true), TIMEOUT(30.0f), REQUIRED(true)); - assertEquals(tropo.text(), "{\"tropo\":[{\"ask\":{\"name\":\"foo\",\"bargein\":true,\"timeout\":30,\"required\":true}}]}"); + tropo.ask(Key.CHOICES_OF_ASK("[5 DIGITS]"),Key.SAY_OF_ASK(new Say("Please say your account number")),NAME("foo"), BARGEIN(true), TIMEOUT(30.0f), REQUIRED(true)); + assertEquals(tropo.text(), "{\"tropo\":[{\"ask\":{\"choices\":{\"value\":\"[5 DIGITS]\"},\"say\":[{\"value\":\"Please say your account number\"}],\"name\":\"foo\",\"bargein\":true,\"timeout\":30.0,\"required\":true}}]}"); tropo.reset(); assertEquals(tropo.text(), "{\"tropo\":[]}"); @@ -108,18 +129,22 @@ public void testReset() { @Test public void testTropoResultSingle() { - String json_session = "{\"result\":{\"sessionId\":\"CCFD9C86-1DD1-11B2-B76D-B9B253E4B7FB@161.253.55.20\",\"callState\":\"ANSWERED\",\"sessionDuration\":2,\"sequence\":1,\"complete\":true,\"error\":null,\"actions\":{\"name\":\"zip\",\"attempts\":1,\"disposition\":\"SUCCESS\",\"confidence\":100,\"interpretation\":\"12345\",\"utterance\":\"1 2 3 4 5\"}}}"; + String json_session = "{\"result\":{\"sessionId\":\"CCFD9C86-1DD1-11B2-B76D-B9B253E4B7FB@161.253.55.20\",\"state\":\"ANSWERED\",\"sessionDuration\":2,\"sequence\":1,\"complete\":true,\"error\":null,\"actions\":{\"name\":\"zip\",\"attempts\":1,\"disposition\":\"SUCCESS\",\"confidence\":100,\"interpretation\":\"12345\",\"utterance\":\"1 2 3 4 5\"}}}"; Tropo tropo = new Tropo(); TropoResult result = tropo.parse(json_session); assertNotNull(result); + assertEquals(result.getSequence(), new Integer(1)); assertNotNull(result.getActions()); assertEquals(result.getActions().get(0).getName(),"zip"); + assertEquals(result.getActions().get(0).getInterpretation(),"12345"); + assertEquals(result.getActions().get(0).getUtterance(),"1 2 3 4 5"); + assertEquals(result.getActions().get(0).getDisposition(),"SUCCESS"); } @Test public void testTropoResultArray() { - String json_session = "{\"result\":{\"sessionId\":\"CCFD9C86-1DD1-11B2-B76D-B9B253E4B7FB@161.253.55.20\",\"callState\":\"ANSWERED\",\"sessionDuration\":2,\"sequence\":1,\"complete\":true,\"error\":null,\"actions\":[{ \"name\": \"account_number\", \"attempts\": 1, \"disposition\": \"SUCCESS\", \"confidence\": 100, \"interpretation\": \"12345\", \"utterance\": \"1 2 3 4 5\", \"concept\": \"12345\" }, { \"name\": \"pin\", \"attempts\": 1, \"disposition\": \"SUCCESS\", \"confidence\": 100, \"interpretation\": \"9876\", \"utterance\": \"9 8 7 6\", \"concept\": \"9876\" }]}}"; + String json_session = "{\"result\":{\"sessionId\":\"CCFD9C86-1DD1-11B2-B76D-B9B253E4B7FB@161.253.55.20\",\"state\":\"ANSWERED\",\"sessionDuration\":2,\"sequence\":1,\"complete\":true,\"error\":null,\"actions\":[{ \"name\": \"account_number\", \"attempts\": 1, \"disposition\": \"SUCCESS\", \"confidence\": 100, \"interpretation\": \"12345\", \"utterance\": \"1 2 3 4 5\", \"concept\": \"12345\" }, { \"name\": \"pin\", \"attempts\": 1, \"disposition\": \"SUCCESS\", \"confidence\": 100, \"interpretation\": \"9876\", \"utterance\": \"9 8 7 6\", \"concept\": \"9876\" }]}}"; Tropo tropo = new Tropo(); TropoResult result = tropo.parse(json_session); assertNotNull(result); @@ -131,16 +156,16 @@ public void testTropoResultArray() { @Test public void testObjectArrivesInJson() { - String json_session = "{\"result\":{\"sessionId\":\"CCFD9C86-1DD1-11B2-B76D-B9B253E4B7FB@161.253.55.20\",\"callState\":\"ANSWERED\",\"sessionDuration\":2,\"sequence\":1,\"complete\":true,\"error\":null,\"actions\":{\"name\":\"zip\",\"attempts\":1,\"disposition\":\"SUCCESS\",\"confidence\":100,\"interpretation\":\"12345\",\"utterance\":\"1 2 3 4 5\"}}}"; + String json_session = "{\"result\":{\"sessionId\":\"CCFD9C86-1DD1-11B2-B76D-B9B253E4B7FB@161.253.55.20\",\"state\":\"ANSWERED\",\"sessionDuration\":2,\"sequence\":1,\"complete\":true,\"error\":null,\"actions\":{\"name\":\"zip\",\"attempts\":1,\"disposition\":\"SUCCESS\",\"confidence\":100,\"interpretation\":\"12345\",\"utterance\":\"1 2 3 4 5\"}}}"; Tropo tropo = new Tropo(); TropoResult result = tropo.parse(json_session); - assertEquals(result.getCallState(),"ANSWERED"); + assertEquals(result.getState(),"ANSWERED"); } @Test public void testParseTropoResultFromServletRequest() { - String json_session = "{\"result\":{\"sessionId\":\"CCFD9C86-1DD1-11B2-B76D-B9B253E4B7FB@161.253.55.20\",\"callState\":\"ANSWERED\",\"sessionDuration\":2,\"sequence\":1,\"complete\":true,\"error\":null,\"actions\":[{ \"name\": \"account_number\", \"attempts\": 1, \"disposition\": \"SUCCESS\", \"confidence\": 100, \"interpretation\": \"12345\", \"utterance\": \"1 2 3 4 5\", \"concept\": \"12345\" }, { \"name\": \"pin\", \"attempts\": 1, \"disposition\": \"SUCCESS\", \"confidence\": 100, \"interpretation\": \"9876\", \"utterance\": \"9 8 7 6\", \"concept\": \"9876\" }]}}"; + String json_session = "{\"result\":{\"sessionId\":\"CCFD9C86-1DD1-11B2-B76D-B9B253E4B7FB@161.253.55.20\",\"state\":\"ANSWERED\",\"sessionDuration\":2,\"sequence\":1,\"complete\":true,\"error\":null,\"actions\":[{ \"name\": \"account_number\", \"attempts\": 1, \"disposition\": \"SUCCESS\", \"confidence\": 100, \"interpretation\": \"12345\", \"utterance\": \"1 2 3 4 5\", \"concept\": \"12345\" }, { \"name\": \"pin\", \"attempts\": 1, \"disposition\": \"SUCCESS\", \"confidence\": 100, \"interpretation\": \"9876\", \"utterance\": \"9 8 7 6\", \"concept\": \"9876\" }]}}"; HttpServletRequest request = new MockHttpServletRequest(json_session); Tropo tropo = new Tropo(); @@ -155,12 +180,12 @@ public void testParseTropoResultFromServletRequest() { public void testOutputIsRenderedToServletResponse() { Tropo tropo = new Tropo(); - tropo.say("1234"); + tropo.say("1234", "say"); MockHttpServletResponse response = new MockHttpServletResponse(); tropo.render(response); - assertEquals(response.getContent(), "{\"tropo\":[{\"say\":[{\"value\":\"1234\"}]}]}"); + assertEquals(response.getContent(), "{\"tropo\":[{\"say\":[{\"value\":\"1234\",\"name\":\"say\"}]}]}"); } @Test @@ -172,17 +197,118 @@ public void testLaunchSession() { TropoLaunchResult result = tropo.launchSession(token); assertNotNull(result); - assertEquals(result.getSuccess(),true); + assertEquals(result.isSuccess(),true); assertEquals(result.getToken(),token); } - - + + @Test(expected = TropoException.class) + public void testLaunchSessionWithProvidedHttpClientExpectTimeout() { + + // This tropo test is hosted in a special Tropo username "hudson"'s account + String token = "bb308b34ed83d54cab226f4af7969e4c7d7d9196cdb3210b5ef0cb345616629005bfd05efe3f4409cd496ca2"; + Tropo tropo = new Tropo(); + + //creates a config with 1 ms socket timeout, will not connect in time + RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1).build(); + HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); + + TropoLaunchResult result = tropo.launchSession(token, Collections.EMPTY_MAP, httpClient); + } + @Test public void testEmpty() { Tropo tropo = new Tropo(); assertTrue(tropo.isEmpty()); - tropo.say("1234"); + tropo.say("1234", "say"); assertFalse(tropo.isEmpty()); } + + @Test + public void testSession() { + + String requestBody = "{\"session\":{\"id\":\"0206f42b41db24008375ca4e745dc784\",\"accountId\":\"1\",\"applicationId\":\"1\",\"timestamp\":\"2017-04-27T08:55:49.252Z\",\"userType\":\"HUMAN\",\"initialText\":null,\"subject\": \"Inbound MMS subject\",\"initialMedia\":[{\"status\":\"success\",\"media\": \"http://filehosting.tropo.com/account/1.jpg\"},{\"status\":\"success\",\"text\": \"this is text\"},{\"status\":\"failure\",\"disposition\": \"Failed to upload: 500 Internal Error\",\"media\": \"2.jpg\"}],\"callId\":\"363241bb23fd2e2fd56775f112afb27f\",\"to\":{\"id\":\"9999452355\",\"e164Id\":\"9999452355\",\"name\":\"9999452355\",\"channel\":\"VOICE\",\"network\":\"SIP\"},\"from\":{\"id\":\"pengxli\",\"e164Id\":\"pengxli\",\"name\":\"pengxli\",\"channel\":\"VOICE\",\"network\":\"SIP\"},\"headers\":{\"Call-ID\":\"83369ZmNjOTdlZWVmOTk4ZjVkMmM2ODg3YWMyYTExZDRmMGU\",\"CSeq\":\"1 INVITE\",\"Max-Forwards\":\"69\",\"Request URI\":\"sip:9999452355@10.140.254.38;x-rt=0\",\"Record-Route\":\"\",\"x-sid\":\"0721d0422c85a7e0eb0c6dc4949827ea\",\"User-Agent\":\"X-Lite release 4.9.7.1 stamp 83369\",\"From\":\";tag=adf8ca71\",\"Supported\":\"replaces\",\"Allow\":\"SUBSCRIBE\r\nNOTIFY\r\nINVITE\r\nACK\r\nCANCEL\r\nBYE\r\nREFER\r\nINFO\r\nOPTIONS\r\nMESSAGE\",\"Via\":\"SIP/2.0/UDP 192.168.26.102:5060;branch=z9hG4bK1rc8iqaigvz77;rport=5060\r\nSIP/2.0/UDP 192.168.26.1:5678;branch=z9hG4bK-524287-1---33c9837c07a3ea75;rport=5678\",\"Contact\":\"\",\"To\":\"\",\"Content-Length\":\"335\",\"Content-Type\":\"application/sdp\"}}}"; + HttpServletRequest mockRequest = new MockHttpServletRequest(requestBody); + + Tropo tropo = new Tropo(); + TropoSession session = tropo.session(mockRequest); + assertNotNull(session); + assertEquals(session.getAccountId(), "1"); + assertEquals(session.getCallId(), "363241bb23fd2e2fd56775f112afb27f"); + assertEquals(session.getId(), "0206f42b41db24008375ca4e745dc784"); + assertEquals(session.getInitialText(), null); + assertEquals(session.getTimestamp(), "2017-04-27T08:55:49.252Z"); + assertEquals(session.getUserType(), "HUMAN"); + assertEquals(session.getSubject(), "Inbound MMS subject"); + List initialMedias = session.getInitialMedia(); + assertEquals(initialMedias.get(0).getStatus(), "success"); + assertEquals(initialMedias.get(0).getMedia(), "http://filehosting.tropo.com/account/1.jpg"); + assertEquals(initialMedias.get(1).getStatus(), "success"); + assertEquals(initialMedias.get(1).getText(), "this is text"); + assertEquals(initialMedias.get(2).getStatus(), "failure"); + assertEquals(initialMedias.get(2).getDisposition(), "Failed to upload: 500 Internal Error"); + assertEquals(initialMedias.get(2).getMedia(), "2.jpg"); + + TropoEntity to = session.getTo(); + assertNotNull(to); + assertEquals(to.getId(), "9999452355"); + assertEquals(to.getE164Id(), "9999452355"); + assertEquals(to.getName(), "9999452355"); + assertEquals(to.getChannel(), "VOICE"); + assertEquals(to.getNetwork(), "SIP"); + + TropoEntity from = session.getFrom(); + assertNotNull(from); + assertEquals(from.getId(), "pengxli"); + assertEquals(from.getE164Id(), "pengxli"); + assertEquals(from.getName(), "pengxli"); + assertEquals(from.getChannel(), "VOICE"); + assertEquals(from.getNetwork(), "SIP"); + + assertEquals(session.getParameters(), null); + + assertNotNull(session.getHeaders()); + } + + @Test + public void testResult() { + + String requestBody = "{\"result\":{\"sessionId\":\"c377075800c4bad1031ba7eca97641c1\",\"callId\":\"15c1e1abe490752831f98ee6c6ea2b2f\",\"state\":\"ANSWERED\",\"sessionDuration\":10,\"sequence\":1,\"complete\":true,\"error\":null,\"calledid\":\"9999452355\",\"actions\":[{\"name\":\"one\",\"attempts\":1,\"disposition\":\"SUCCESS\",\"confidence\":100,\"interpretation\":\"1\",\"utterance\":\"1\",\"value\":\"1\"},{\"name\":\"two\",\"attempts\":1,\"disposition\":\"SUCCESS\",\"confidence\":100,\"interpretation\":\"12\",\"utterance\":\"12\",\"value\":\"12\"}]}}"; + Tropo tropo = new Tropo(); + TropoResult result = tropo.parse(requestBody); + assertNotNull(result); + assertEquals(result.getCallId(), "15c1e1abe490752831f98ee6c6ea2b2f"); + assertEquals(result.getCalledId(), "9999452355"); + assertEquals(result.isComplete(), true); + assertEquals(result.getError(), null); + assertEquals(result.getSequence(), new Integer(1)); + assertEquals(result.getSessionDuration(), new Integer(10)); + assertEquals(result.getSessionId(), "c377075800c4bad1031ba7eca97641c1"); + assertEquals(result.getState(), "ANSWERED"); + + ArrayList actions = result.getActions(); + assertNotNull(result); + + assertEquals(actions.get(0).getName(), "one"); + assertEquals(actions.get(0).getAttempts(), new Integer(1)); + assertEquals(actions.get(0).getDisposition(), "SUCCESS"); + assertEquals(actions.get(0).getConfidence(), new Integer(100)); + assertEquals(actions.get(0).getInterpretation(), "1"); + assertEquals(actions.get(0).getUtterance(), "1"); + assertEquals(actions.get(0).getValue(), "1"); + assertEquals(actions.get(0).getConcept(), null); + assertEquals(actions.get(0).getXml(), null); + assertEquals(actions.get(0).getuploadStatus(), null); + + assertEquals(actions.get(1).getName(), "two"); + assertEquals(actions.get(1).getAttempts(), new Integer(1)); + assertEquals(actions.get(1).getDisposition(), "SUCCESS"); + assertEquals(actions.get(1).getConfidence(), new Integer(100)); + assertEquals(actions.get(1).getInterpretation(), "12"); + assertEquals(actions.get(1).getUtterance(), "12"); + assertEquals(actions.get(1).getValue(), "12"); + assertEquals(actions.get(1).getConcept(), null); + assertEquals(actions.get(1).getXml(), null); + assertEquals(actions.get(1).getuploadStatus(), null); + } } diff --git a/src/test/java/com/voxeo/tropo/WaitActionTest.java b/src/test/java/com/voxeo/tropo/WaitActionTest.java new file mode 100644 index 0000000..7826975 --- /dev/null +++ b/src/test/java/com/voxeo/tropo/WaitActionTest.java @@ -0,0 +1,19 @@ +package com.voxeo.tropo; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class WaitActionTest { + + @Test + public void testWait() { + + Tropo tropo = new Tropo(); + tropo.say("Connected!", "connected"); + tropo.serverWait(Key.ALLOW_SIGNALS("exit", "quit"), Key.MILLISECONDS(10000L)); + tropo.say("Bye!", "bye"); + + assertEquals(tropo.text(), "{\"tropo\":[{\"say\":[{\"value\":\"Connected!\",\"name\":\"connected\"}]},{\"wait\":{\"allowSignals\":[\"exit\",\"quit\"],\"milliseconds\":10000}},{\"say\":[{\"value\":\"Bye!\",\"name\":\"bye\"}]}]}"); + } +}