Wiki

« Back to HttpMakeCall

HttpMakeCall-Java

About This Application#

This application is triggered by an inbound HTTP request to the Cisco Unified Application Environment (CUAE) server, which then places an outbound call to a configurable IP Phone directory number. Upon receiving the acknowledgement that the call has been answered, the application plays a text message. The call remains active until the destination (called party) hangs up.

Creating the Application Project#

  1. Open a command shell.
  2. The cuae requires, at a minimum, the name of the application project,

the implementation language and the module name to get started. If the language and or the module name are omitted the tool will prompt the you for them. Let's use the cuae tool to create a new application.

c:\> cd Development\JAVA\workspace
c:\Development\JAVA\workspace> cuae create HttpMakeCall

3. First the tool asks if you are building an application or a plugin. In this example, the correct choice is application:

Project Type? [application or plugin] application

4. Next the tool prompts you to specify the programming language. In this example, the correct choice is java:

Programming language? [java or csharp] java

5. The tool prompts you for the build format that is used for developing the application. In this example, we are using ant:

Build format? [ant or maven2] ant

6. Next the tool prompts you for the namespace for the application. A Java program might want to use a fully qualified namespace like com.company.HttpMakeCall or something simple like HttpMakeCall. The tool offers you a simple namespace based on the project name. Let's use cisco.uc.cuae.samples for now:

Project namespace? [default: httpmakecall] cisco.uc.cuae.samples <Return>

7. Finally the tool asks if you would like to specify a triggering event. All CUAE applications need to register against at least one triggering event. You can specify the triggering event now or wait and specify the triggering event later. You can also change the triggering event during development. Again since we know that this application needs to be triggered on an incoming call, let's go ahead and specify the triggering event now. Select option 5 cisco.uc.cuae.legacy.Http.GotRequest:

Available application triggering event:
   0: Skip this step
   1: cisco.uc.cuae.legacy.JTapi.JTapiIncomingCall
   2: cisco.uc.cuae.legacy.JTapi.JTapiCallInitiated
   3: cisco.uc.cuae.legacy.JTapi.JTapiCallEstablished
   4: cisco.uc.cuae.legacy.CallControl.IncomingCall
   5: cisco.uc.cuae.legacy.Http.GotRequest
   6: cisco.uc.cuae.legacy.Presence.SubscriptionTerminated
   7: cisco.uc.cuae.legacy.Presence.Notify
   8: cisco.uc.cuae.legacy.TimerFacility.TimerFire
Triggering event? [0-8] 5

The tool now has enough information to generate the project template.

Generating:
   * application named "MakeCall"
   * with namespace "MakeCall"
   * with laguage "java"
   * with trigger event "cisco.uc.cuae.legacy.CallControl.Http.GotRequest"
   * in location C:\Development\Java\workspace\
Created project "HttpMakeCall" in directory
"C:\Development\Java\workspace\HttpMakeCall\"

Inspecting the Generated Project#

Let's inspect the files that were generated by the CUAE command-line tool. It created an HttpMakeCall directory in the directory from which you ran the cuae create command. The HttpMakeCall directory contains the following files and directories:

  • HttpMakeCall.etch
  • HttpMakeCall.properties
  • build.xml
  • cuae-resources/
  • README.txt
  • src/

The most important of which, for your purposes, are:

  • HttpMakeCall.etch--CUAE application Etch service definition. Edit this file to use additional CUAE services in your project.
  • build.xml--Ant build script file with predefined targets for managing the lifecycle of your CUAE project.
  • cuae-resources/--CUAE application resource directory.
  • src/--Generated application source files.

Declaring Services#

The first step in building an Etch-based application is identifying which Cisco Unified Application Environment hosted services the application requires and then editing the .etch file to declare the names of those services into the application.

Note:

Once you identify the services you need, you can familiarize yourself with them by visiting the API Reference for the version of the Unified Application Environment you are using.

The following snippet is the default content of the .etch file that the CUAE command-line tool generates. We use the mixin command to declare the appropriate services.

// CUAE Application Etch Service Definition
//
// This service defines your application and the CUAE services that you
// use in your application.

// The service module namespace, this will be translated to the
// namespace of the generated source code.
module HttpMakeCall

// The name of your service.
service HttpMakeCall
{
    // By default, you must always use the EtchBridge service. Do not
    // remove this mixin, otherwise your application won't work.
    mixin cisco.uc.cuae.EtchBridge

    // You may add any additional service mixins that you require. For
    // example, if you'd like to make and receive phone calls, add the
    // following line:
    //     mixin cisco.uc.cuae.legacy.CallControl
    mixin cisco.uc.cuae.legacy.Http

}

For this application we will want to answer an incoming HTTP request, make a call, and play a media stream back to the caller. This means that we need to build an application capable of both CallControl and MediaControl.

The default etch file already has a mixin for Http:

  mixin cisco.uc.cuae.legacy.Http

so we need to add a mixin declaration for MediaControl and CallControl. Add the following lines right after the mixin for Http but before the final "}":

  mixin cisco.uc.cuae.legacy.CallControl
  mixin cisco.uc.cuae.legacy.MediaControl

Building the Application#

After declaring the services you need, you must build the application to generate source files.

1. Open a Command Prompt and navigate to the application directory.

2. Run the ant command to generate source files.

c:\Development\Java\workspace> cd HttpMakeCall
c:\Development\Java\workspace\HttpMakeCall> ant

The following source file templates are then created in the directory src\cisco\uc\cuae\samples:

  • MainHttpMakeCallClient.java
  • ImplHttpMakeCallClient.java

Creating Configuration Items#

YAML is the file format for Unified Application Environment application configuration (config.yaml) and metadata definitions project_name.yaml).

All application configuration items are written in the config.yaml file, which is located in the cuae-resources directory.

Configuration items follow a specific syntax, as follows.

-name:

[display name:]

format:

[description:]

[minvalue:]

[maxvalue:]

[defaultvalue:]

[readonly:]

[required]}}}

  • Items in square brackets
    []
    are optional

The default config.yaml file contains the following information:

# CUAE Application Configuration Definition
#
# You only need to edit this file if you want to expose configuration to
# the administrator through cuaeadmin.
#
# This file was auto-generated from a template but will never be
# overwritten. You should edit this file directly if required.

configuration:
  # Indicates the name of your configuration item. It will be how you
  # reference this configuration item from code.
  #- name: myConfValue

    # Controls how the visible label of the configuration value. For
    # example, if 'name' was defined as: myConfValue, you may choose to
    # define 'displayName' as: My Config Value. Think of it as a friendly
    # name. This field is optional.
    #displayName: My Config Value

    # Defines the format of the configuration item's value. This will
    # control how cuaeadmin renders and validates the value. Possible
    # values for the 'format' field are: String, Bool, Number, IP_Address,
    # Array, HashTable, Password.
    #format: String

    # A description of the configuration item that will be displayed to
    # the administrator in cuadmin. This field is optional.
    #description: Some description here.

    # For configuration items that are formatted as numbers, the
    # 'minValue' and 'maxValue' configuration items define the acceptable
    # range of input for the item. These fields are optional.
    #minValue:
    #maxValue:

    # Defines the default value of the configuration. This field is
    # optional.
    #defaultValue:

    # Inidicates whether the configuration item is editable. If
    # 'readOnly' is set to true, the administrator will not be able to
    # edit it in cuaeadmin, but will be able to view it. The default is
    # false, and this field is optional.
    #readOnly:

    # Indicates whether the configuration item is required. If required,
    # the administrator will have to set a value before the application
    # will run. The default is false, and this field is optional.
    #required: false

In this example, the application has one configuration item, the content of the rendering text. Add the following block to the config.yaml file in the configuration section:

Code Sample#

configuration:
  - name: UseTTS
    format: Bool
    displayName: UseTTS
    defaultValue: True

  - name: TTSMessage
    format: String
    displayName: TTSMessage
    defaultValue: Hello, welcome to answer and play demo application

  - name: To
    format: String
    displayName: To
    defaultValue:

Writing the Application Code#

This section provides instructions and code samples for writing the application logic.

Importing the Project into Your IDE#

1. Open Eclipse.

2. Create a new Java project from an existing Ant buildfile by choosing File -> New -> Other -> Java Project from an existing Ant buildfile

3. Select the build.xml from the directory (HttpMakeCall).

Code Samples: OnGotRequest, beginMakeCall#

Write the following code in ImplHttpMakeCallClient.java file. Once the script is triggered by the incoming HTTP request you can send a response back to the browser and then make the outbound call using the "server.sendResponse" and "server.beginMakeCall" actions as follows:

private boolean bUseTTS = false;
private String sTTSMessage = "This is a TTS message";
private String sTo = "100265";

@Override
public void gotRequest(String sessionId, GotRequestOptions options)
{
  ConfigEntry[] configs = null;
  try {
    configs = server.getConfig("Default");
  }
  catch (Exception e)
  {
    System.out.println("Failed to get config entries for partition Default");
    server.removeCuaeSession(sessionId);
    return;
  }

  try
  {
    for ( int i=0; i<configs.length; i++ )
    {
      if ( configs[ i ].name.matches("UseTTS"))
        bUseTTS = Boolean.parseBoolean(configs[ i ].configValue.toString());
      else if ( configs[ i ].name.matches("TTSMessage"))
        sTTSMessage = configs[ i ].configValue.toString();
      else if ( configs[ i ].name.matches("To"))
	sTo = configs[ i ].configValue.toString();
     }
  }
  catch ( Exception e )
  {
      System.out.println( "Error reading application configs: " + e.getMessage());
  }

  // HttpSendResponse application is triggered on this event, send back response in plain text to client.
  String body = "Placing a call...";
  SendResponseResult srr = server.sendResponse(sessionId, options.remoteHost, 200, "text/plain", body, "OK", null);

  if (srr.returnValue != CuaeResult.SUCCESS)
  {
    System.out.println("SendResponse Failed");
    server.removeCuaeSession(sessionId);
    return;
  }

  //Make A Call
  MakeCallResult smcr = server.beginMakeCall(sessionId, sTo, " ", "test app", null, null);

  if (smcr.returnValue != CuaeResult.SUCCESS)
  {
    System.out.println("MakeCall Failed");
    server.removeCuaeSession(sessionId);
    return;
  }
}

The first portion of the sample code handles the current application's configurations from the CUAE server in the "getConfigs(partition)" method call. The developer can walk through the configurations array and parse the configuration item based on its type.

Note: The collected configurations are always the latest from CUAE server forregistered application's name and partition.

Handy Hint: In the sample code above we use the "System.out.println" function to printoutput to the console. To print output to the app server log file you canuse the "server.logWrite" function:server.logWrite(LogLevel.VERBOSE, "DEBUG:", " Configs.length " + configs.length);

Code Samples: onMakeCallComplete, beginPlay#

When using the "beginMakeCall" action, you should follow-up with the "onMakeCallComplete" function. And, the next transition is to the "beginPlay" action:

@Override
public void onMakeCallComplete(String sessionId, MakeCallResult results, Object state)
{
  System.out.println("\nMakeCall completed..");
  System.out.println("\nBegin play..");

  // Play prompt in non-blocking fashion, pass in AnswerCallResult as state info
  if (server.beginPlay(sessionId, sTTSMessage, results.connectionId, null, null, results.callId).returnValue != CuaeResult.SUCCESS)
  {
    System.out.println("beginPlay failed");

    server.hangup(sessionId, results.callId, null);
    server.removeCuaeSession(sessionId);
  }
}

Code Sample: onPlayComplete#

When using the "beginPlay" action, you should follow up with the "onPlayComplete" function:

@Override
public void onPlayComplete(String sessionId, PlayResult results, Object state)
{
  System.out.println("\nPlay completed..");

  String callId = (String)state;

  System.out.println("\nHangup..");
  if (server.hangup(sessionId, callId, null).returnValue != CuaeResult.SUCCESS)
    System.out.println("Hangup failed");

  System.out.println("\nEndScript");
  server.removeCuaeSession(sessionId);
}

Code Samples:Call Control Events: startTx, stopTx, startRx and remoteHangup#

During the design of this applications you need to account for the following Call Control Events by adding a stub to your Impl src file:

public void startTx(String sessionId,StartTxOptions options)
{
}

public void stopTx(String sessionId,StopTxOptions options)
{
}

public void startRx(String sessionId,StartRxOptions options)
{
}

public void remoteHangup(String sessionId,RemoteHangupOptions options)
{
}

Registering the Application#

The previous steps completed the core logic of the example applications, but before any Etch-based API calls can actually be made, we must register the application with the Cisco Unified Application Server. To register your application, follow these steps:

1. Open the MainHTTPMakeCallClient file in the /src directory. It contains the following content by default:

// Generated by:
// 0.95.0 (ETCH-TRUNK-840) / java 0.95.0 (ETCH-TRUNK-840)
// Sun Jun 08 22:47:33 CDT 2008

package cisco.uc.cuae.samples;

/**
 * Main program for HTTPMakeCallClient. This program makes a connection to the
 * listener created by HTTPMakeCallListener.
 */
public class MainHTTPMakeCallClient implements HTTPMakeCallHelper.HTTPMakeCallClientFactory
{
	/**
	 * Main program for HTTPMakeCallClient.
	 *
	 * @param args command line arguments.
	 * @throws Exception
	 */
	public static void main( String[] args ) throws Exception
	{
		// TODO Change to correct URI
		String uri = "tcp://localhost:4001";
		RemoteHTTPMakeCallServer server = HTTPMakeCallHelper.newServer( uri, null,
			new MainHTTPMakeCallClient() );

		// Connect to the service
		server._startAndWaitUp( 4000 );

		// TODO Insert Your Code Here

		// Disconnect from the service
		server._stopAndWaitDown( 4000 );
	}

	public HTTPMakeCallClient newHTTPMakeCallClient( RemoteHTTPMakeCallServer server )
		throws Exception
	{
		return new ImplHTTPMakeCallClient( server );
	}
}

2. To make a connection to the listener, add a server.registerApplication() request.

// TODO Insert Your Code Here
		String key = server.registerApplication("HTTPMakeCall", "Default",
"<user-id>", "<password>");
		System.out.println("HTTPMakeCall is registered: " + key);
		System.in.read();

3. Modify the String URI to match the IP address and port of the Cisco Unified Application Server.

URI settings vary slightly between 2.5(1) Beta 1 and more recent versions of 2.5(1), as follows:

2.5(1) and 2.5(1) Beta 2, Beta 3, Beta 4 & later releases#

// TODO Change to correct URI
String uri = "tls://appserver_ipaddress:9000?TlsConnection.authReqd=false&filter=KeepAlive
 &KeepAlive.Count=5&Packetizer.maxPktSize=102400&TcpTransport.reconnectDelay=4000;

Note In Beta 2, the Etch Bridge was updated to use Transport Layer Security for encryption by default. For your applications to work, you must specify TLS as the protocol in the URI and set the authReqd parameter to false. In the example above, the Keep Alive filter and MaxPacketSizeand Reconnect Delay parameters have also been set.

2.5(1) Beta 1#

// TODO Change to correct URI
		String uri = "tcp://appserver_ipaddress:9000?&TcpConnection.reconnect_delay=4000";

Note In addition to setting the correct IP address and port for the Cisco Unfied Application Server, the Reconnect Delay parameter should be set on all connection URIs.

Packaging the Test Application#

  1. Execute a succesful build request for your test applcation within your IDE.
  2. To package the JAVA application, execute the "cuae package" command from a DOS command shell in the parent directory of the test application.
C:\Development\Java\workspace\HttpMakeCall>cuae package
Created package file
"C:\Development\Java\workspace\HttpMakeCall\bin\HttpMakeCall.mca".

The following files are added to the "\bin" sub-directory:

  • HttpMakeCall.mca (application bundle to be uploaded into the CUAE server)
  • INSTALLER.xml - (contains the config items in config.yaml)
  • MANIFEST.xml - (bundle details for the package comamnd).

C:\Development\Java\workspace\HttpMakeCall>dir bin HttpMakeCall.mca INSTALLER.xml MANIFEST.xml

Installing the Test Application#

To install the test application on a CUAE server, execute the cuae install command from a DOS command shell in test application parent directory of the test application. The cuae install command varies slightly between 2.5(1) Beta 1 and Beta 2.

2.5(1) Beta 2#

You are prompted to enter an IP address, username, and password (to view the help, run the cuae install -h command). When prompted, enter Y or N to save management settings. This will save the answers to the above three questions in the properties file and remember them the next time you go to install.

Note

You are also prompted for the communications protocol (TCP or TLS). Select the protocol that is set on the Management Service. TLS is the default supported protocol. If you want to use TCP, follow the instructions in Management Service Transport Layer Security (TLS) to change the default URI of the Management Service before running these commands.

C:\Development\JAVA\workspace\HttpMakeCall>cuae package
Created package file
"C:\Development\JAVA\workspace\HttpMakeCall\bin\HttpMakeCall.mca"

C:\Development\JAVA\workspace\HttpMakeCall>cuae install
Enter the hostname or IP address of the management service (for example: localhost, 1.1.1.1): localhost
Protocol: tls
Generated mgmt-service uri: tls://localhost:9001?TlsConnection.authReqd=false
Enter management service login username:
Entermanagement service login password: ********
Save the amanagement settings with the project? [yes or no] no
Application : C:\Development\JAVA\workspace\HttpMakeCall\bin\HttpMakeCall.mca
Uploading :  ===========================> 100%
Application has been installed successfully

2.5(1) Beta 1#

You are prompted to enter an IP address, username, and password (to view the help, run the cuae install -h command). When prompted, enter Y or N to save management settings. This will save the answers to the above three questions in the properties file and remember them the next time you go to install.

C:\workspace\HttpMakeCall>cuae package
Created package file
"C:\Development\Java\workspace\HttpMakeCall\bin\HttpMakeCall.mca"

C:\workspace\AnswerAndPlay>cuae install
Enter management service uri or host/IP <for example: localhost, tcp://1.1.1.1.:4001>:
Enter management service login username:
Entermanagement service login password: ********
Save the amanagement settings with the project? [YyNn] n
Application : C:\workspace\HttpMakeCall\bin\HttpMakeCall.mca
Uploading :  ===========================> 100%
Application ahas been installed successfully

Configuring the Test Application Using the Administration Interface#

1. Log into the CUAE server, click on the Applications tab and select the test application HttpmakeCall_JAVA from the list of applcations.

You will see that the config.yaml file defaults have been populated into the application configuration form. You can now use this form to update the values as necessary between executions.

2. Choose Applications -> Find/List triggers to generate a list of applications and their associated triggers. 3. Select the application "HttpmakeCall_JAVA" from the list and add the URL trigger used to launch this application using a web browser.

Running the Application#

1. Run the class HTTPMakeCall.MainHTTPMakeCallClient to register the application.

At this point the application will remain registered and running until either you stop your application or the application loses connectivity to the Unified Application server.

2. Open a web browser and launch the application using the URL trigger you assigned to the application in "Configuring the Test Application Using the Administration Interface" above.

The image below represents the output for both the Web Browser request and the output to the IDE console for a successful test execution.

0 Attachments
2615 Views
Average (0 Votes)
The average rating is 0.0 stars out of 5.
Comments
No comments yet. Be the first.