LogoLogo
AboutSupport
4.2
4.2
  • Unifi User Documentation
  • Install
    • Release Notes
      • Unifi 4.2 Release Notes
      • Unifi 4.1 Release Notes
      • Unifi 4.0 Release Notes
      • Unifi 3.1 Release Notes
      • Unifi 3.0 Release Notes
      • Unifi 2.2 Release Notes
      • Unifi 2.1 Release Notes
      • Unifi 2.0 Release Notes
    • Install or Upgrade
      • Global Utility
      • Hotfix
  • Configure
    • Integration Designer
    • Processes
    • Integrations
    • Connections
    • Messages
    • Message Scripts
    • Fields
    • Field Maps
    • Response Actions
    • Event Actions
    • Datasets
      • Create a New Dataset
      • Dataset Extras
    • Polling
      • Pollers
      • Poll Processors
    • Administration
      • Activity Logs
      • Data Stores
      • Properties
      • Scheduled Scripts
      • System Logs
    • Attachments
      • Extracting Attachments
      • Fetching Attachments
      • Embedded Attachments
    • Scripting
      • Snippets
      • Variables
    • Documentation
    • How to guides
      • How to Handle Attachments
        • Message
        • Scripted REST Resource
        • Test AddAttachment
      • How to Manually Close a Bond
      • How to Poll for Large Response Payloads
      • How to Setup an OAuth Connection
        • Identity Provider Instance
        • Identity Consumer Instance
        • OAuth Refresh Token Job
      • How to Setup Heartbeat Messages
  • Deploy
    • Package
    • Instance Clone
  • Operate
    • Bonding
      • Bonds
      • Bonded Attachments
    • Transport
      • Snapshots
      • Transactions
      • Stages
      • HTTP Requests
      • Dataset Requests
      • Poll Requests
    • Error Handling
      • Integration Pause and Resume
      • Integration Repair
      • Request Retry
      • Transaction & Request Replay
      • Transaction Ignore
  • Test
    • Overview
    • Integration Test
    • Test Scenario
    • Test Scenario Data
    • Test Result
    • Test Scenario Result
    • Generating Tests
    • Running Tests
    • Exploring Results
  • Integration Guides
    • Outbound Incident Guide
      • Getting Started
      • Process
      • Integration
      • Connection
      • Create Scenario
        • CreateIncidentResponse Message
        • CreateIncidentResponse Fields
        • CreateIncident Message
        • CreateIncident Fields
        • Trigger
        • Test CreateIncident
      • Update Scenario
        • Response Message
        • UpdateIncident Message
        • UpdateIncident Fields
        • Test UpdateIncident
      • Resolve Scenario
        • ResolveIncident Message
        • ResolveIncident Fields
        • Test ResolveIncident
      • Build - Integration Level
      • Conclusion
    • Bidirectional Asynchronous Incident Guide
      • Getting Started
      • Process
      • Web Service
      • Integration
      • Connection
      • Create Scenario
        • Response Message
        • CreateIncidentReceipt Message
        • CreateIncidentReceipt Fields
        • CreateIncident Message
        • CreateIncident Fields
        • Trigger
        • Test CreateIncident
      • Update Scenario
        • Receipt Message
        • UpdateIncident Message
        • UpdateIncident Fields
        • Test UpdateIncident
      • Resolve Scenario
        • ResolveIncident Message
        • ResolveIncident Fields
        • Test ResolveIncident
      • Build - Integration Level
      • Build the Other Half
        • Move the Integration
        • Reconfigure the Connections
      • Conclusion
    • Incident Update Poller Guide
      • Polling
        • Poll Processor
        • Poller
      • Inbound Message
        • UpdateIncidentInbound Message
        • UpdateIncidentInbound Fields
      • Message Identification
      • Bond Identification
        • Edit Incident Form
        • Edit CreateIncident Message
      • Test Update Poll
      • Conclusion
    • Incident Multiple Message Poller Guide
      • Polling
        • Poll Processor
        • Poller
      • Inbound Messages
        • ResolveIncidentInbound Message
        • ResolveIncidentInbound Fields
      • Testing
        • Test UpdateIncidentInbound
        • Test ResolveIncidentInbound
      • Conclusion
    • Incident Create Poller Guide
      • Polling
        • Connection Variables
        • Poll Processor
        • Poller
      • Messages
        • CreateIncidentInboundReceipt Message
        • CreateIncidentInboundReceipt Fields
        • CreateIncidentInbound Message
        • CreateIncidentInbound Fields
      • Build - Integration Level
      • Test Create Poll
      • Conclusion
    • Incident Parent and Child Poller Guide
      • Polling
        • Connection Variables
        • Child Poll Processor
        • Child Poller
        • Parent Poll Processor
        • Parent Poller
      • Inbound Messages
      • Testing
        • Test UpdateIncidentInbound
        • Test ResolveIncidentInbound
      • Conclusion
    • Incident Attachment Poller Guide
      • Polling
        • Connection Variables
        • Edit Endpoint URLs
        • Get Attachment Poll Processor
        • Get Attachment Poller
        • Select Attachments Poll Processor
        • Select Attachments Poller
        • Edit Child Poll Processor
        • Edit Child Update Poller
      • Messages
        • AddAttachmentInbound Message
      • Testing
        • Test Outbound Scenarios
        • Test CreateIncidentInbound
        • Test UpdateIncidentInbound
        • Test ResolveIncidentInbound
        • Test AddAttachmentInbound
      • Conclusion
  • Troubleshooting
    • Attachments
      • Inbound SOAP/Base64 attachments stopped working
      • New record attachments are not sent from Portal
      • Special characters in attachment file names
    • Datasets
    • Development
      • Bonding to existing records
      • Copying an existing Unifi trigger rule doesn't work
      • Duplicate messages being sent
      • Deleted records are not packaged
      • Multipart Form Data
      • Undefined error when building an integration
    • Diagnostic
    • Installation
      • Latest version of Unifi not accessible
    • Integration Responses
      • Transaction has been processed already
      • Initiating transaction not found for inbound receipt
      • Message has already been processed
      • Message ID not found
      • Message is not valid for this bond
      • Message name not recognised
      • No retry for requests with 401 response
      • Unable to identify message name from request
    • Other
      • Dynamic stage does not render
      • Duplicate bonds on Request integrations
    • Self-test
  • About
    • Quick Tour
    • Supported Features
    • Application Modules
    • Data Model
    • Transport Data Flow
Powered by GitBook
On this page
  • Icons
  • New Poll Processor
  • Setup Script
  • Request Script
  • Response Script

Was this helpful?

Export as PDF
  1. Integration Guides
  2. Incident Multiple Message Poller Guide
  3. Polling

Poll Processor

The Poll Processor contains the logic that will be applied when polling a remote system for data.

PreviousPollingNextPoller

Was this helpful?

The Poll Processor is a configuration record which contains the logic that will be applied when polling a remote system for data. There are three main scripts which are used to setup, execute and process the Poll Requests. The scripts given here are examples of how you might configure your Poll. The details of yours may differ depending on your requirements.

Icons

Before continuing we would again like to remind you of the relevant icons that are visible down the left hand navigation strip of the Unifi Integration Designer.

The icons are:

a) 'Integration' icon: Opens the current integration's Details page.

b) 'Messages' icon: Opens the current integration's Messages page.

c) 'Fields' icon: Opens the current integration's Fields page.

d) 'Field Maps' icon: Opens the current integration's Field Maps page.

e) 'Pollers' icon: Opens the current integration's Pollers page.

f) 'Poll Processors' icon: Opens the current integration's Poll Processors page.

New Poll Processor

In Unifi Integration Designer, navigate to & open < Your Integration > (created following the Outbound Incident Guide & Incident Update Poller Guide).

Click the 'Poll Processors' icon & then New.

The fields to be configured for the New Poll Processor modal are as follows:

Field
Description
Value

Name

The name of the Processor.

<Your Name>

Your New Poll Processor modal should look like this:

Submit and view to further configure the Poll Processor.

Setup Script

The Setup Script is the first script to run (it runs at the point in time the Poll Request is created). It is used to build the environment for the poll and define what it will do. We will use it to setup the URL that will be called.

Navigate to Scripts > Setup Script.

The initial Poll Processor fields to be configured are as follows:

Field
Description
Value

Setup script

The script to setup the Poll Request record.

Update the code in the Setup script field so that it looks like the code below

The code in the Setup script field should look like this:

// Configure the new Poll Request record
(function(poll_request, poller, params) {

    var gdt = new GlideDateTime();
    gdt.addSeconds(-1800);

    var connection = poller.getIntegration().getActiveConnection();
    var user = connection.getBasicAuthUser();
    var time = connection.getData('last_update_time', (gdt + ''));

    var fields = 'sys_id,number,correlation_id,short_description,description,state,close_code,close_notes,sys_updated_on,sys_updated_by';

    var query = [
        'correlation_idISNOTEMPTY',
        'sys_updated_by!=' + user,
        'sys_updated_on>' + time
    ];

    var uri_query = query.map(function(c) {
        return encodeURIComponent(c);
    }).join('%5E');

    poll_request.endpoint_url += '/table/incident?sysparm_query=' + uri_query +
        '&sysparm_fields=' + encodeURIComponent(fields) + '&sysparm_limit=10';

})(poll_request, poller, params);

Setup script: The parameters for which data to return are contained in the endpoint url.

fields: The table API will return all the data by default, so we choose to deliberately limit what is returned to the fields listed in this variable.

query: Instead of querying all the records on the remote instance, we deliberately limit the records to those where the correlation id is not empty (i.e. it's bonded), that haven't been updated by the Authentication user (our system) and that were updated since either since the last update time (if one exists), or in the last 30 minutes.

Endpoint URL: The value used in the poll_request.endpoint_url was initially generated using the ServiceNow REST API Explorer, substituting variables in for the uri query and fields. This value is appended to the existing endpoint url in the active connection before being added to the Poll Request.

(We have also chosen to limit the number of records returned to 10.)

params: The params object is passed through to the subsequent scripts (and on to further Pollers, if required).

Your Setup Script form should look like this:

Navigate to Request Script.

Request Script

The Request Script is used to reach into the remote system and execute the request. We will use the ServiceNow RESTMessageV2() web service to make a REST call to the URL defined in the Setup Script.

The next Poll Processor field to be configured is as follows:

Field
Description
Value

Request script

The script that executes the request.

Update the code in the Request script field so that it looks like the code below

The code in the Request script field should look like this:

// Process the request e.g. by executing a web service and returning the response
(function(poll_request, poller, connection, params) {

    var rm = new sn_ws.RESTMessageV2();
    rm.setEndpoint(poll_request.endpoint_url);
    rm.setHttpMethod('GET');
    rm.setRequestHeader('Accept', 'application/json');
    rm.setRequestHeader('Content-type', 'application/json');
    rm.setBasicAuth(connection.getBasicAuthUser(), connection.getBasicAuthPassword());

    // rm.setRequestBody(JSON.stringify(body));
    var resp = rm.execute();

    answer = resp.getBody() + '';

})(poll_request, poller, connection, params);

Request script: This script uses the ServiceNow RESTMessageV2() web service to make a REST call to the endpoint url created in the Setup script. It returns the body of the request as the answer which it passes to the Response script

Your Request Script form should look like this:

Navigate to Response Script.

Response Script

The Response Script is used to process the information returned from the remote system. We will pass this data to Unifi, telling it which Message to use to process the data.

The last Poll Processor field to be configured is as follows:

Field
Description
Value

Response script

The script that processes the response to the request.

Update the code in the Response script field so that it looks like the code below

The code in the Response script field should look like this:

// Process the response returned by the request script
// The 'answer' variable from the request script is passed in here as the 'response' parameter 
(function (poll_request, poller, response, params) {

    var body = JSON.parse(response);

    // Nothing to do if no results were returned
    if ( body.result.length == 0 ) {
        poll_request.response_status = 'No Incidents returned\n\n' + JSON.stringify(body,null,2);
        return;
    }

    // Sample result
/*
{
  "result": [
    {
      "sys_id": "0ecc4865db734010c3ebde82ca961960",
      "number": "INC0010107",
      "correlation_id": "INC0010345",
      "short_description": "Demo two - Fixing request",
      "description": "A long description",
      "state":"2",
      "sys_updated_on": "2020-04-02 14:00:00",
      "sys_updated_by": "a.user"
    },
    {
      ... next Incident
    }
  ]
}    
*/

    // Establish the environment
    var integration = poller.getIntegration();
    var config = integration.getConfig();
    var conn   = integration.getActiveConnection();
    var cvars  = conn.getVariables();

    var poll_helper = new x_snd_eb.PollHelper(poll_request);
    var info = [];

    // Use Unifi code to find the Bond for an Incident
    function get_bond(inc) {
        var bond = new x_snd_eb.Bond(config);
        bond.locateReference(integration,inc.correlation_id,inc.sys_id);
        if ( !bond.isValidRecord() ) { return null; }
        return bond; 
    }

    // Work out the message type to send to Unifi based upon the change of state
    function get_message_name(curr,prev) {

        // Default message type is an update
        var message_name = 'UpdateIncidentInbound';

        // Use the default type if we have no previous state
        if ( !prev || !prev.state ) { 
            return message_name; 
        }

        // Use the default type if there is no change in state
        if ( curr.state == prev.state ) { 
            return message_name; 
        }

        // We know the state has changed, check if it is Resolved (6)
        if ( curr.state == '6' ) {
            message_name = 'ResolveIncidentInbound';
        }

        return message_name;
    }

    function process_incident(inc) {

        // Log the incident number and time
        var inc_time = inc.sys_updated_on;
        info.push('Incident : ' + inc.number + ' (' + inc_time + ')');

        // Find the bond on which the previous data is stored
        var bond = get_bond(inc);

        // If no bond was found, ignore this incident
        if ( !bond ) {
            info.push('- Bond not found - Incident ignored');
            return;
        }

        // Get the data stored for the incident by a previous poll
        var previous_inc = bond.getDataObject('previous_inc',{ state : '2' });

        // Work out the message type to send into Unifi 
        var message_name = get_message_name(inc,previous_inc);
        info.push('- Message name: ' + message_name);

        // Set up the payload object for passing into Unifi
        var payload = {
            message : {
                name: message_name,
                source_reference: inc.sys_id,
            },
            detail : {
                short_description : inc.short_description,
                description : inc.description,
                state : inc.state,
                close_code : inc.close_code,
                close_notes : inc.close_notes
            }
        };

        // Submit the message into Unifi
        poll_helper.processInbound({
            payload : JSON.stringify(payload)
        });

        // Save the current incident as the previous incident for the next poll
        bond.setDataObject('previous_inc',inc);

        // Update last update time (if later)
        var conn_time = conn.getData('last_update_time');
        if ( inc_time > conn_time ) {
            conn.setData('last_update_time',inc_time);
        }

    }

    // Process each result
    body.result.forEach(function(inc){
        process_incident(inc);
    });

    poll_request.response_status = info.join('\n') + '\n\n' + JSON.stringify(body,null,2);

})(poll_request, poller, response, params);

Response script: This script parses the response into a body object to contain the result, (returning if it doesn't contain anything).

It then sets up some objects to help us; these include the essential PollHelper() function (which we initialise from the poll_request) along with two other functions: get_bond() to find the Bond for an Incident & get_message_name() to work out the message type to send to Unifi based upon the change of state.

After that it loops through each of the returned tickets. For each ticket, it logs the incident number & time, finds the bond & returns any previous data stored on the bond, decides which Message to use, sets up a payload object and submits it to Unifi by calling the processInbound() method. It then saves the current incident as the previous incident for the next poll & checks whether the ticket was updated later than the last update time; if so, it sets and stores the last update time as that 'sys_updated_on' value (this 'last_update_time' is what the Setup script checks against when defining what the Poll will do).

After looping through all the records (processing each result), the results are logged to the Response status field of the Poll Request.

Essential code: the following lines of code must be included in the response script to enable Unifi

var poll_helper = new x_snd_eb.PollHelper(poll_request);
poll_helper.processInbound({
            payload : JSON.stringify(payload)
        });

processInbound(): Having the 'poll_helper.processInbound()' function inside the loop means that an update message will be generated for each updated ticket.

Payload object: We have chosen to structure the payload object (var payload) as we have. There is no obligation to keep the same structure. Yours can be defined to suit your requirements.

Message name: Unifi needs to know the message name in order to know how to process the inbound request. We can either set it in the payload (as we have), or declare a variable that sets it which is passed into the processInbound() function along with the payload. (Unifi will always check processInbound() first. If no Message name is set here it will use the 'Identify message script' on the Integration).

Your Response Script form should look like this:

Save the Poll Processor.

Now let's move on and configure the Poller.

Note: We have included the /table/incident element of the endpoint url because we used the truncated url in the Connection when following the . If you have used the full url there, then this element can be excluded here.

Outbound Incident Guide