Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Dynamic Call Center with Java and Servlets

Download the Code

In this tutorial we will show how to automate the routing of calls from customers to your support agents. Customers will be able to select a product and wait while TaskRouter tries to contact a product specialist for the best support experience. If no one is available, our application will save the customer's number and selected product so an agent can call them back later on.

This is what the application does at a high level:

  1. Configure a workspace using the Twilio TaskRouter REST API.
  2. Listen for incoming calls and let the user select a product with the dial pad.
  3. Create a Task with the selected product and let TaskRouter handle it.
  4. Store missed calls so agents can return the call to customers.
Let's get started!

Configure the Workspace

In order to instruct TaskRouter to handle the Tasks, we need to configure a Workspace. We can do this in the TaskRouter Console or programmatically using the TaskRouter REST API.

A Workspace is the container element for any TaskRouter application. The elements are:

  • Tasks - Represents a customer trying to contact an agent.
  • Workers - The agents responsible for handling Tasks.
  • Task Queues - Holds Tasks to be consumed by a set of Workers.
  • Workflows - Responsible for placing Tasks into Task Queues.
  • Activities - Possible states of a Worker, e.g. Idle, Offline, Busy.
Loading Code Sample...
      
      
      
      
      /src/main/resources/workspace.json

      Configuring the Workspace

      /src/main/resources/workspace.json

      In order to build a client for this API, we need as system variables a TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN which you can find on Twilio Console. The class TwilioAppSettings creates a TwilioTaskRouterClient, which is provided by the Twilio Java library. This client is used by WorkspaceFacade which encapsulates all logic related to the Workspace class.

      Let's take a look at a Gradle task that will handle the Workspace setup for us.

      The CreateWorkspace Gradle Task

      The CreateWorkspace Gradle Task

      In this application the Gradle task createWorkspace is used to orchestrate calls to our WorkspaceFacade class in order to handle a Workspace. CreateWorkspaceTask is the java main class behind the Gradle task. It uses data provided by workspace.json and expects 3 arguments in the following order:

      1. hostname - A public URL to which Twilio can send requests. This can be either a cloud service or ngrok, which can expose a local application to the internet.
      2. bobPhone - The telephone number of Bob, the Programmable SMS specialist.
      3. alicePhone - Same for Alice, the Programmable Voice specialist.

      The function createWorkspaceConfig is used to load the configuration of the workspace from workspace.json.

      Loading Code Sample...
          
          
          
          
          src/main/java/com/twilio/taskrouter/application/CreateWorkspaceTask.java

          CreateWorkspace Gradle Task

          src/main/java/com/twilio/taskrouter/application/CreateWorkspaceTask.java

          Now let's look in more detail at all the steps, starting with the creation of the workspace itself.

          See how to create a new workspace

          Create a Workspace

          Before creating a workspace, we need to delete any others with the same FriendlyName as identifier. In order to create a workspace we need to provide a FriendlyName, and a EventCallbackUrl which contains an URL to be called every time an event is triggered in the workspace.

          Loading Code Sample...
              
              
              
              
              src/main/java/com/twilio/taskrouter/domain/model/WorkspaceFacade.java

              Create Workspace

              src/main/java/com/twilio/taskrouter/domain/model/WorkspaceFacade.java

              We have a brand new workspace, now we need workers. Let's create them on the next step.

              Check out how to create a couple of workers

              Create the Workers

              We'll create two workers, Bob and Alice. They each have two attributes: contact_uri a phone number and products, a list of products each worker is specialized in. We also need to specify an activity_sid and a name for each worker. The selected activity will define the status of the worker.

              Loading Code Sample...
                  
                  
                  
                  
                  Creating the Workers

                  Create Workers

                  Creating the Workers

                  After creating our workers, let's set up the Task Queues.

                  See how to create the Task Queues

                  Create the Task Queues

                  Next, we set up the Task Queues. Each with a name and a TargetWorkers property, which is an expression to match Workers. Our Task Queues are:

                  1. SMS - Will target Workers specialized in Programmable SMS, such as Bob, using the expression "products HAS \"ProgrammableSMS\"".
                  2. Voice - Will do the same for Programmable Voice Workers, such as Alice, using the expression "products HAS \"ProgrammableVoice\"".
                  3. All - This queue targets all users and can be used when there are no specialist around for the chosen product. We can use the "1==1" expression here.
                  Loading Code Sample...
                      
                      
                      
                      
                      Creating the Task Queues

                      Create Task Queues

                      Creating the Task Queues

                      We have a Workspace, Workers and Task Queues... what's left? A Workflow. Let's see how to create one next!

                      Check out the code to create a Workflow

                      Create a Workflow

                      Finally, we set up the Workflow using the following parameters:

                      1. FriendlyName as the name of a Workflow.
                      2. AssignmentCallbackUrl as the public URL where a request will be made when this Workflow assigns a Task to a Worker. We will learn how to implement it on the next steps.
                      3. TaskReservationTimeout as the maximum time we want to wait until a Worker handles a Task.
                      4. configuration which is a set of rules for placing Task into Task Queues. The routing configuration will take a Task's attribute and match this with Task Queues. This application's Workflow rules are defined as:
                        1. selected_product=="ProgrammableSMS" expression for SMS Task Queue. This expression will match any Task with ProgrammableSMS as the selected_product attribute.
                        2. selected_product=="ProgrammableVoice expression for Voice Task Queue.
                      Loading Code Sample...
                          
                          
                          
                          
                          Creating a Workflow

                          Create a Workflow

                          Creating a Workflow

                          Our workspace is completely setup. Now it's time to see how we use it to route calls.

                          See how we handle incoming Twilio requests

                          Handle Twilio's Request

                          Right after receiving a call, Twilio will send a request to the URL specified on the number's configuration.

                          The endpoint will then process the request and generate a TwiML response. We'll use the Say verb to give the user product alternatives, and a key they can press in order to select one. The Gather verb allows us to capture the user's key press.

                          Loading Code Sample...
                              
                              
                              
                              
                              src/main/java/com/twilio/taskrouter/application/servlet/IncomingCallServlet.java

                              Handle Incoming Call

                              src/main/java/com/twilio/taskrouter/application/servlet/IncomingCallServlet.java

                              We just asked the caller to choose a product, next we will use their choice to create the appropiate Task.

                              See how to create a Task

                              Create a Task

                              This is the endpoint set as the action URL on the Gather verb on the previous step. A request is made to this endpoint when the user presses a key during the call. This request has a Digits parameter that holds the pressed keys. A Task will be created based on the pressed digit with the selected_product as an attribute. The Workflow will take this Task's attributes and make a match with the configured expressions in order to find a corresponding Task Queue, so an appropriate available Worker can be assigned to handle it.

                              We use the Enqueue verb with a workflowSid attribute to integrate with TaskRouter. Then the voice call will be put on hold while TaskRouter tries to find an available Worker to handle this Task.

                              Loading Code Sample...
                                  
                                  
                                  
                                  
                                  src/main/java/com/twilio/taskrouter/application/servlet/EnqueueServlet.java

                                  Create a Task

                                  src/main/java/com/twilio/taskrouter/application/servlet/EnqueueServlet.java

                                  After sending a Task to Twilio, let's see how we tell TaskRouter which Worker to use to execute that task.

                                  See how to assign a Worker

                                  Assign a Worker

                                  When TaskRouter selects a Worker, it does the following:

                                  1. The Task's Assignment Status is set to reserved
                                  2. A Reservation instance is generated, linking the Task to the selected Worker
                                  3. At the same time the Reservation is created, a POST request is made to the Workflow's AssignmentCallbackURL, which was configured using the Gradle task createWorkspace

                                  This request includes the full details of the Task, the selected Worker, and the Reservation.

                                  Handling this Assignment Callback is a key component of building a TaskRouter application as we can instruct how the Worker will handle a Task. We could send a text, e-mail, push notifications or make a call.

                                  Since we created this Task during a voice call with an Enqueue verb, lets instruct TaskRouter to dequeue the call and dial a Worker. If we do not specify a to parameter with a phone number, TaskRouter will pick the Worker's contact_uri attribute.

                                  We also send a post_work_activity_sid which will tell TaskRouter which Activity to assign this worker after the call ends.

                                  Loading Code Sample...
                                      
                                      
                                      
                                      
                                      src/main/java/com/twilio/taskrouter/application/servlet/AssignmentServlet.java

                                      Assign a Worker

                                      src/main/java/com/twilio/taskrouter/application/servlet/AssignmentServlet.java

                                      Now that our Tasks are routed properly, let's deal with missed calls in the next step.

                                      Check out how to collect missed calls

                                      Collect Missed Calls

                                      This endpoint will be called after each TaskRouter Event is triggered. In our application, we are trying to collect missed calls, so we would like to handle the workflow.timeout event. This event is triggered when the Task waits more than the limit set on Workflow Configuration-- or rather when no worker is available.

                                      Here we use TwilioRestClient to route this call to a Voicemail Twimlet. Twimlets are tiny web applications for voice. This one will generate a TwiML response using Say verb and record a message using Record verb. The recorded message will then be transcribed and sent to the email address configured.

                                      We are also listening for task.canceled. This is triggered when the customer hangs up before being assigned to an agent, therefore canceling the task. Capturing this event allows us to collect the information from the customers that hang up before the Workflow times out.

                                      Loading Code Sample...
                                          
                                          
                                          
                                          
                                          src/main/java/com/twilio/taskrouter/application/servlet/EventsServlet.java

                                          Collect Missed Calls

                                          src/main/java/com/twilio/taskrouter/application/servlet/EventsServlet.java

                                          Most of the features of our application are implemented. The last piece is allowing the Workers to change their availability status. Let's see how to do that next.

                                          See how to allow Workers change their availability status

                                          Change a Worker's Activity

                                          We have created this endpoint, so a worker can send an SMS message to the support line with the command "On" or "Off" to change their availability status.

                                          This is important as a worker's activity will change to Offline when they miss a call. When this happens, they receive an SMS letting them know that their activity has changed, and that they can reply with the On command to make themselves available for incoming calls again.

                                          Loading Code Sample...
                                              
                                              
                                              
                                              
                                              src/main/java/com/twilio/taskrouter/application/servlet/MessageServlet.java

                                              Change a Worker's Activity

                                              src/main/java/com/twilio/taskrouter/application/servlet/MessageServlet.java

                                              Congratulations! You finished this tutorial. As you can see, using Twilio's TaskRouter is quite simple.

                                              Where to Next?

                                              Where to Next?

                                              If you're a Java developer working with Twilio, you might enjoy these other tutorials:

                                              Click to Call

                                              An example application implementing Click to Call using Twilio.

                                              Automated-Survey

                                              Instantly collect structured data from your users with a survey conducted over a call or SMS text messages.

                                              Did this help?

                                              Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio to let us know what you think!

                                              Agustin Camino Jose Oliveros David Prothero Kat King

                                              Need some help?

                                              We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

                                              Loading Code Sample...