All pages
Powered by GitBook
1 of 9

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Polling

We will configure an on-demand poll to query the remote system and pull back a list of attachments added to bonded records that have changed. Each will then be retrieved by another on-demand poll.

To set up an on-demand poll that will query the remote system for attachments and pass each to a subsequent poll, which will then retrieve them and pass them to Unifi to process, we will need to configure a further two each of the following records:

  • Child Poll Processor

  • Child Poller

(Note: one of the children will be a parent to the other)

We will also need to edit the previously configured (per the Parent & Child Poller Guide) to kick-off the first of our attachment Child Pollers.

To facilitate polling both the Table API and Attachment API, we may also need to make changes to the Endpoint URLs* configured in earlier Guides in the following places: (*only if the Connection contains the full endpoint url)

  • Connection

  • Outbound Message Path

  • Poll Processor Setup Script

We will look at each of those edits and the polling records in turn over subsequent pages. Before configuring those records, let’s first look at Connection Variables.

Connection Variables

Connection Variables can be especially useful if you have multiple connection environments - e.g. Dev, Test, Prod - each containing different data.

Although having multiple environments may not apply to this integration, we will create Connection Variables to contain certain data values which will be substituted into the Poll Processor scripts.

Instead of scripting data values directly into the code of your Poll Processor scripts, it may be better practice to use Connection Variables in their place. Not only does it make those scripts cleaner, but it also means that changes in requirements can be more easily enacted by changing the values of the data in those variables, without having to change the code in the scripts.

We will create an additional two Connection Variables to identify the Child Pollers we shall be creating.

Icons

Before continuing we would like to draw your attention to some of the relevant icons that will be visible down the left hand navigation strip in Unifi Integration Designer.

The icons are:

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

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

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

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

Variable: get_attachment_poller

This variable will contain the sys_id of the child Poller which we will create on the '' page of this Guide. Once you have created the Poller, copy the sys_id and paste it as the value in this variable.

To open Unifi Integration Designer, navigate to Unifi > Unifi Integration Designer, then navigate to < Your Integration > (created following the Outbound Incident Guide).

Click the 'Connections' icon, then navigate to and open < Your Connection >.

From the Connection, navigate to Connection > Variables & click New.

The 'get_attachment_poller' New Connection Variable fields to be configured are as follows:

Field
Description
Value

*Value may vary. Use the sys_id of the Poller you will create from the Get Attachment Poller page.

Your 'get_attachment_poller' New Connection Variable modal should look like this:

Click Submit.

You will be redirected back to the Variables page of the Connection record.

Variable: select_attachments_poller

This variable will contain the sys_id of the child Poller which we will create on the '' page of this Guide. Once you have created the Poller, copy the sys_id and paste it as the value in this variable.

From the Connection, navigate to Connection > Variables & click New.

The 'select_attachments_poller' New Connection Variable fields to be configured are as follows:

Field
Description
Value

*Value may vary. Use the sys_id of the Poller you will create from the Select Attachments Poller.

Your 'select_attachments_poller' New Connection Variable modal should look like this:

Click Submit.

The following Connection Variables should now be in place for your Connection:

Now let's move on and edit the Endpoint URLs.

Edit Endpoint URLs

We have previously been polling the Table API of our PDI. We now want to poll the Attachment API. To facilitate this, we will need to make changes to the Endpoint URLs in multiple places.

The instructions on this page only apply if you have configured the Connection with the full endpoint url (including the /table/incident element).

If you have used the truncated url in the Connection (moving the /table/incident element to the outbound Message path & Poll Processors), this page may be skipped.

To facilitate polling both the Table API and Attachment API, we will need to edit the Endpoint URLs configured in earlier Guides in the following places:

  • Connection

  • Outbound Message Path

  • Previously Configured Poll Processors

Edit Connection

First, edit the Endpoint URL in the Connection.

In Unifi Integration Designer, navigate to the 'Connections' icon. Click to open & edit < Your Connection > (configured following the Outbound Incident Guide).

Remove /table/incident from the Endpoint URL and Save. (This will be prepended to the Outbound Message Path & previously configured Poll Processors.)

Edit Outbound Message Path

Edit each of the previously configured Outbound Messages:

  • CreateIncident

  • UpdateIncident

  • ResolvIncident

  • CreateIncidentInboundReceipt

To edit the CreateIncident Message, navigate to the 'Messages' icon & click to open the CreateIncident Message.

Navigate to Outbound > Settings. Add the previously cut /table/incident to the Path & Save.

Repeat for each of the other Outbound Messages.

DO NOT delete the existing path, rather prepend it with /table/incident (as cut from the Connection). For example, the Path for the UpdateIncident Message should now read as follows: /table/incident/{bond.getValue("external_reference")}.

Edit Previously Configured Poll Processors

Edit the Endpoint URL in the Setup script for each of the previously configured Poll Processors_:*_

*(The names of your Poll Processors may differ.)

  • Unifi - SN REST Poll Processor (as configured in the

  • Unifi - SN REST Poller with Incident DataStore (as configured in the )

  • Unifi - SN REST Create Poll processor (as configured in the )

Note: Although it is necessary to edit the Endpoint URL for all of the previously configured Poll Processors for each of them to work, it is only essential (for the purposes of this Guide) that this is done for the Parent and Child Poll Processors and the Create Poll Processor as these will be used when testing our Integration (& the Messages).

To edit the Unifi - SN REST Poll Processor, navigate to the 'Poll Processors' icon & click to open the Unifi - SN REST Poll Processor.

Navigate to Scripts > Setup Script.

Edit the code by prepending the existing Endpoint URL with /table/incident i.e. insert it immediately after the poll_request.endpoint_url += ' value & click Save. That line of code should now read as follows:

Your Unifi - SN REST Poll Processor Setup Script should now look like this:

Repeat for each of the other previously configured Poll Processors.

Once complete we can configure the first of our Child Poll Processors, the Get Attachment Poll Processor.

Edit Child Update Poller

A Poller is a configuration record which defines the frequency of polling and which logic to use.

We will edit the previously created Child Update Poller, so that it runs our new "Unifi - SN REST Poller Single Incident with Attachments" (as created in the previous section) instead of the originally configured Poll Processor.

To edit the Child update Poller, click the 'Pollers' icon.

Click to open < Your Child Update Poller > (created following the )

Child Poll Processor
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

Unifi - SN REST Poller Single incident (as configured in the 'Child Poll Processor' page of the Incident Parent and Child Poller Guide)

  • Unifi - SN REST Poller Incident List (as configured in the 'Parent Poll Processor' page of the Incident Parent and Child Poller Guide)

  • 'Poll Processor' page of the Incident Update Poller Guide
    'Poll Processor' page of the Incident Multiple Message Poller Guide
    'Poll Processor' page of the Incident Create Poller Guide
    Details

    The fields to be edited for the Details form are as follows:

    Field
    Description
    Value

    Poll processor

    The Poll Processor to use when running this Poller.

    <Your Poll Processor>*

    Description

    A description of what this Poller is for and/or how it works.

    <Your Description> (edit accordingly)

    *Poll Processor: Value may vary. Choose the Poll Processor you created in the previous section.

    Your Details form should look like this:

    Save the Poller.

    In the next section, we will look at the Inbound Messages.

    Incident Parent and Child Poller Guide

    Key

    A unique name that will be used to get the value.

    'get_attachment_poller'

    Value

    The variable value to be used in the integration.

    <Your Value>*

    Description

    Describe what this connection variable is for and how it should be used.

    <Your Description>

    Key

    A unique name that will be used to get the value.

    'select_attachments_poller'

    Value

    The variable value to be used in the integration.

    <Your Value>*

    Description

    Describe what this connection variable is for and how it should be used.

    <Your Description>

    Get Attachment Poller
    Select Attachments Poller

    Select Attachments Poller

    A Poller is a configuration record which defines the frequency of polling and which logic to use.

    A Poller is a configuration record which defines the frequency of polling and which logic to use (the logic itself is defined in the Poll Processor). Each time it is run, it creates a corresponding Poll Request record.

    New Poller

    Click the 'Pollers' icon & then New.

    The fields to be configured for our Poller record are as follows:

    Field
    Description
    Value

    *These fields are mandatory, or automatically defaulted to true.

    Your New Poller modal should look like this:

    Submit and view to further configure the Poller.

    Details

    The fields to be configured for the Details form are as follows:

    Field
    Description
    Value

    Your Details form should look like this:

    Save the Poller.

    Update Connection Variable

    Update the value of the 'select_attachments' Connection Variable with the sys_id of the child Poller.

    Click on the Hamburger Menu and select Open in platform.

    The Poller opens in a new window.

    Right-click the Header & 'Copy sys_id'.

    Open the variable created on the '' page of this Guide and update the value with the copied sys_id.

    Next, we will edit our previously configured Child Poll Processor so that it becomes the parent of this.

    Get Attachment Poller

    A Poller is a configuration record which defines the frequency of polling and which logic to use.

    A Poller is a configuration record which defines the frequency of polling and which logic to use (the logic itself is defined in the Poll Processor). Each time it is run, it creates a corresponding Poll Request record.

    New Poller

    Click the 'Pollers' icon & then New.

    The fields to be configured for our Poller record are as follows:

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

    Name*

    The name of your Poller.

    <Your Name>

    Poll processor*

    The Poll Processor to use when running this Poller.

    <Your Poll Processor>

    Run

    The frequency at which the Poller should run.

    'On Demand'

    Run as

    Poller will run with credentials of specified user.

    <Your Inbound user> (from Connection)

    Active*

    Set to true to use this Poller record for processing.

    *These fields are mandatory, or automatically defaulted to true.

    Your New Poller modal should look like this:

    Submit and view to further configure the Poller.

    Details

    The fields to be configured for the Details form are as follows:

    Field
    Description
    Value

    Description

    A description of what this Poller is for and/or how it works.

    <Your description>

    Your Details form should look like this:

    Save the Poller.

    Update Connection Variable

    Update the value of the 'get_attachment_poller' Connection Variable with the sys_id.

    Click on the Hamburger Menu and select Open in platform.

    The Poller opens in a new window.

    Right-click the Header & 'Copy sys_id'.

    Open the variable created on the 'Connection Variables' page of this Guide and update the value with the copied sys_id.

    Next, we will configure the Select Attachments Poll Processor.

    Name*

    The name of your Poller.

    <Your Name>

    Poll processor*

    The Poll Processor to use when running this Poller.

    <Your Poll Processor>

    Run

    The frequency at which the Poller should run.

    'On Demand'

    Run as

    Poller will run with credentials of specified user.

    <Your Inbound user> (from Connection)

    Active*

    Set to true to use this Poller record for processing.

    Description

    A description of what this Poller is for and/or how it works.

    <Your description>

    Connection Variables

    <true>

    <true>

    Edit Child Poll Processor

    Our previously configured Child Poll Processor only polled for updates against records passed to it from its Parent. We will now edit it so that it will also kick off the Select Attachments Poller.

    Rather than just making edits to the existing Child Poll Processor, we will instead copy it & edit the copy. That way we will have one Child Poll Processor that just polls for updates and another that polls for updates and attachments.

    Copy Child Poll Processor

    To copy the Child Poll processor, in Unifi Integration Designer, click the 'Poll Processors' Icon.

    Click the ellipsis to the right of < Your Child Poll Processor > (created following the ) & then click Copy.

    Copy Poll Processor Modal

    Click Copy.

    Your Copy Poll Processor modal should look like this:

    You will be redirected to the Details page of the newly copied Poll Processor.

    Edit Copied Poll Processor

    The fields to edit for the Copied Poll Processor are as follows:

    Field
    Description
    Value

    *Name: We've chosen to append the existing value with, "(with Attachments)".

    Your Copied Poll Processor should look like this:

    Navigate to Scripts > Response Script.

    Response Script

    The Response Script field is to be edited as follows:

    Field
    Description
    Value

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

    Response script: This script creates a variable to store a time based high water marker and parses the response into a body object to contain the result, (returning if it doesn't contain anything).

    It then establishes the environment, getting the Integration, Configuration, Connection & Connection Variables and sets up the essential PollHelper() function (which we initialise from the poll_request) along with the info [] array.

    After that it sets up some other functions: get_bond() finds the bond for the Incident (returning if there isn't one), get_message_name() works out the message type to send to Unifi based upon the change of state & execute_child_poller() sets up a Poll Request to check for new attachments.

    Your Response Script form should look like this:

    Click Save.

    Update Select Attachments Poll Processor

    Navigate to and open the Select Attachments Poll Processor (created on the ' page) and update the value of the Parent field by selecting its parent Poll Processor created above.

    Remember, We have not scripted any business logic to run from the value in the Parent field. It is given for documentary purposes only (for you to easily identify which parent Poll Processor kicked off the child).

    The following Poll Processors should now be in place on the Integration:

    We could Deactivate the copied "Unifi - SN REST Poller Single Incident" now that we've created this version, "with Attachments". However, we will instead edit the Child Update Poller that runs it.

    Now let's move on and edit the Child Update Poller (configured when following the Incident Parent and Child Poller Guide) so that it runs the Poll Processor created above.

    Get Attachment Poll Processor

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

    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.

    This Get Attachment Poll Processor will take take each record passed to it from its parent - Select Attachments Poll Processor - and then make a Poll Request against that record, retrieving the attachment, building a payload and passing it to Unifi to process.

    It then processes each of the results (passed in tickets). For each, it logs the incident number & time, finding the bond & returning any previous data stored on the bond, deciding which Message to use, setting up a payload object and submitting it to Unifi by calling the processInbound() method. It then runs the execute_child_poller() function and 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).

    On processing each result, it is then logged to the Response status field of the Poll Request.

    params: The params object is passed through to the subsequent scripts (and on to further Pollers, if required). This is used to pass the int_ref, ext_ref & attachment_hwm elements to the child Poller.

    Code Edits - The following code snippets were added to the existing codebase to facilitate polling for attachments:

    This is a DataStore name constant to store a time based high water mark.

    The x_snd_eb.Poller.execute() method has two parameters. In the first we pass the sys_id of the child Poller (as created on the 'Select Attachments Poller' page). In the second we pass an object containing the correlation_id on the bonded Incident as the int_ref element, the sys_id of the bonded Incident as the ext_ref element and the value of the ATTACHMENT_HWM DataStore as the attachment_hwm element (telling the child Poller which attachment records to poll).

    Causing the execute_child_poller() function to run (as set up above) - passing in the Incident & Bond.

    Name

    The name of the Processor.

    <Your Name>*

    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

    Incident Parent and Child Poller Guide
    Select Attachments Poll Processor'
    New Poll Processor

    In Unifi Integration Designer, navigate to & open < Your Integration > (created following the Outbound Incident 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>

    Run parallel

    Allow concurrent Poll Requests to be executed.

    <true>*

    *Run parallel: Each Poll Request will have different input parameters (i.e. the sys_id of one of the attachments passed from its Parent). We can therefore run concurrent Poll Requests on the different records without concern for overlap issues.

    Your New Poll Processor modal should look like this:

    'Parent' - Once we have created its Parent Poll Processor, we can then select it here. We have not scripted any business logic to run from the value in this field. It is given for documentary purposes only.

    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:

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

    Endpoint URL: The value used in the poll_request.endpoint_url was initially generated using the ServiceNow REST API Explorer polling the Attachment API, substituting a variable in for the sys_id of a specific attachment to query. This value is appended to the existing endpoint url in the active connection before being added to the Poll Request.

    params: The params object is passed through to the subsequent scripts (and on to further Pollers, if required). This script has been passed the sys_id of a specific attachment from its parent Poller.

    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:

    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 an attachment who's sys_id it passes to the Response script

    saveResponseBodyAsAttachment(): This method takes three parameters:

    tableName - the table that contains the record you want to attach the saved file to.

    recordSysId - the sys_id of the record you want to attach the saved file to.

    fileName - the file name to give to the saved file.

    request.execute(): The response object returned by request.execute() provides a method called getResponseAttachmentSysid().

    getResponseAttachmentSysid(): This method returns the sys_id of the attachment generated by the REST call.

    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:

    Response script: This script sets up some objects to help us; this includes the essential PollHelper() function (which we initialise from the poll_request) along with the info [] array.

    After that it sets params.attachment.data to the sys_id of the created attachment, setting up a payload object and submitting it to Unifi by calling the processInbound() method.

    After processing the single result, it is 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

    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 did in previous Guides), or declare a variable that sets it which is passed into the processInbound() function along with the payload (as we have here). (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 Get Attachment Poller.

    Select Attachments Poll Processor

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

    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.

    This Select Attachments Poll Processor will pull back a list of the relevant attachment records. Each record it identifies will be passed on to its child - Get Attachment Poll Processor.

    New Poll Processor

    In Unifi Integration Designer, navigate to & open < Your Integration > (created following the Outbound Incident 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

    Your New Poll Processor modal should look like this:

    'Parent' - Once we have created its , we can then select it here. We have not scripted any business logic to run from the value in this field. It is given for documentary purposes only.

    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

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

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

    query: Instead of querying all the attachments on the remote instance, we deliberately limit the query to those where the table_sys_id (target record) is the sys_id of a bonded Incident (passed in from the Response script of its Parent Poll Processor), that haven't been updated by the Authentication user (our system) and that were updated 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 a variable in for the uri query. 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.)

    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

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

    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 use it to build an attachment object to pass this data to the next Poll Processor.

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

    Field
    Description
    Value

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

    Response script: This script creates a variable to store a time based high water marker and parses the response into a body object to contain the result, (returning if it doesn't contain anything).

    It then establishes the environment, getting the Integration, Connection & Connection Variables and sets up the essential PollHelper() function (which we initialise from the poll_request) along with the info [] array.

    After that it finds the bond for the Incident (returning if there isn't one) & then processes each of the results (returned attachment records). For each, it builds an attachment object and sets up a Poll Request to retrieve & process the remote attachment (returning a PollRequest object). It also tracks the latest sys_created_on time.

    After processing each result, the script checks whether the attachment was created later than the latest attachment high water mark; if so, it sets and stores that 'sys_created_on' value as the attachment high water mark (the 'attachment_hwm' is what the Setup script checks against when defining what the Poll will do). The results are then logged to the Response status field of the Poll Request.

    Your Response Script form should look like this:

    Save the Poll Processor.

    Update Child Poll Processor

    Navigate to and open the Get Attachment Poll Processor (created on the '' page) and update the value of the Parent field by selecting its parent Poll Processor created above.

    Remember, We have not scripted any business logic to run from the value in the Parent field. It is given for documentary purposes only (for you to easily identify which parent Poll Processor kicked off the child).

    Now let's move on and configure the Select Attachments Poller.

    // 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) {
    
        // DataStore name constant
        // Storage of time based High Water Marker
        var ATTACHMENT_HWM = 'attachment_hwm';
    
        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 (single Incident)
        /*
        {
          "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"
          }
        }    
        */
    
        // 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 execute_child_poller(inc, bond) {
    
            if (!bond) {
                return {};
            }
    
            // Set up a Poll to check for new attachments
            x_snd_eb.Poller.execute(cvars.select_attachments_poller, {
                int_ref: inc.correlation_id,
                ext_ref: inc.sys_id,
                attachment_hwm: bond.getData(ATTACHMENT_HWM, '')
            });
    
        }
    
        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)
            });
    
            // Check for Attachments
            execute_child_poller(inc, bond);
    
            // 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 the single result
        process_incident(body.result);
    
        poll_request.response_status = info.join('\n') + '\n\n' + JSON.stringify(body, null, 2);
    
    })(poll_request, poller, response, params);
        var ATTACHMENT_HWM = 'attachment_hwm';
     function execute_child_poller(inc, bond) {
     
             if (!bond) {
                 return {};
             }
     
             // Set up a Poll to check for new attachments
             x_snd_eb.Poller.execute(cvars.select_attachments_poller, {
                 int_ref: inc.correlation_id,
                 ext_ref: inc.sys_id,
                 attachment_hwm: bond.getData(ATTACHMENT_HWM, '')
             });
     
         }
            execute_child_poller(inc, bond);
    var poll_helper = new x_snd_eb.PollHelper(poll_request);
    poll_helper.processInbound({
            message_name : 'AddAttachmentInbound',
            payload : JSON.stringify(payload)
        });
    // Configure the new Poll Request record
    (function (poll_request, poller, params) {
    
        // Params contain an attachment object containing details of the remote attachment
        // remote_id : The sys_id of the attachment in the remote system
        // Also contains: file_name, content_type, size_bytes
    
        var attach_id = params.attachment.remote_id;
    
        poll_request.endpoint_url += '/attachment/' + attach_id + '/file';
    
    })(poll_request, poller, params);
    // Process the request e.g. by executing a web service and returning the response
    (function (poll_request, poller, connection, params) {
    
        var request, response;
    
        request = new sn_ws.RESTMessageV2();
        request.setHttpMethod('GET');
        request.setEndpoint(poll_request.endpoint_url);
        request.setRequestHeader('Content-Type','application/json');
        request.setBasicAuth(connection.getBasicAuthUser(), connection.getBasicAuthPassword());
    
        // Save the response as a new attachment (on the poll request)
        request.saveResponseBodyAsAttachment(
          poll_request.getTableName(), poll_request.sys_id, params.attachment.file_name
        );
    
        response = request.execute();
    
        poll_request.response_code   = response.getStatusCode();
        poll_request.response_status = response.getErrorMessage();
        if (response.haveError()) {
          throw '\nResponse Code: ' + response.getErrorCode() + '\nResponse error: ' + response.getErrorMessage();
        }
    
        // Return the sys_id of the saved attachment
        answer = response.getResponseAttachmentSysid() + '';
    
    })(poll_request, poller, connection, params);
    // 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) {
    
        // Establish the environment
        var poll_helper = new x_snd_eb.PollHelper(poll_request);
        var info = [
            'Incident : ' + params.int_ref,
            '- Attachment file name: ' + params.attachment.file_name,
            '- Attachment id: ' + response
        ];
    
        // The response should be the sys_id of the created attachment
        params.attachment.data = '<x-attachment-data sys_id="' + response + '" />';
    
        // Build the payload for Unifi
        var payload = {
            sys_id : params.ext_ref,
            correlation_id : params.int_ref,
            attachment : params.attachment
        };
    
        // Submit the message into Unifi
        poll_helper.processInbound({
            message_name : 'AddAttachmentInbound',
            payload : JSON.stringify(payload)
        });
    
        poll_request.response_status = info.join('\n');
    
    })(poll_request, poller, response, params);

    x_snd_eb.Poller.execute(): This method has two parameters. In the first we pass the sys_id of the child Poller (as created in __ the 'Get Attachment Poller' page). In the second we pass an object containing the correlation_id on the bonded Incident as the int_ref element, the sys_id of the bonded Incident as the ext_ref element and the attachment object as the attachment element (telling the child Poller which attachment record to poll).

    params: The params object is passed through to the subsequent scripts (and on to further Pollers, if required). This is used to pass the int_ref, ext_ref & attachment elements to the child Poller.

    Name

    The name of the Processor.

    <Your name>

    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

    Request script

    The script that executes the request.

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

    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

    Parent Poll Processor
    Get Attachment Poll Processor
    // Configure the new Poll Request record
    (function (poll_request, poller, params) {
    
        var gdt = new GlideDateTime();
        gdt.addSeconds(-1800);
    
        var conn = poller.getIntegration().getActiveConnection();
        var user = conn.getBasicAuthUser();
        var time = params.attachment_hwm || (gdt+'');
    
        var query = [
            'table_sys_id=' + params.ext_ref,
            'sys_created_by!=' + user,
            'sys_created_on>' + time,
            'ORDERBYsys_created_on'
        ];
    
        var uri_query = query.map(function(c) { return encodeURIComponent(c); }).join('%5E');
    
        poll_request.endpoint_url += '/attachment?sysparm_query=' + uri_query + '&sysparm_limit=10';
    
    })(poll_request, poller, params);
    // 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);
    // 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) {
    
        // DataStore name constants
        // Storage of time based High Water Marker
        var ATTACHMENT_HWM = 'attachment_hwm';
    
        var body = JSON.parse(response);
    
        // Nothing to do if no results were returned
        if ( body.result.length == 0 ) {
            poll_request.response_status = 'No Attachments returned\n\n' + JSON.stringify(body,null,2);
            return;
        }
    
    /*
    
           {
                "size_bytes": "2330",
                "file_name": "MPFD-!--1539262705666--!",
                "sys_mod_count": "0",
                "average_image_color": "",
                "image_width": "",
                "sys_updated_on": "2018-10-11 12:58:26",
                "sys_tags": "",
                "table_name": "incident",
                "sys_id": "6c559892db812300f56c711ebf96192d",
                "image_height": "",
                "sys_updated_by": "ws_hn",
                "download_link": "https://dev22291.service-now.com/api/now/attachment/6c559892db812300f56c711ebf96192d/file",
                "content_type": "application/octet-stream",
                "sys_created_on": "2018-10-11 12:58:26",
                "size_compressed": "1055",
                "compressed": "true",
                "state": "",
                "table_sys_id": "bcdf18d5db241300f56c711ebf961947",
                "chunk_size_bytes": "",
                "hash": "",
                "sys_created_by": "ws_hn"
            },
    
    */
    
        // Establish the environment
        var poll_helper = new x_snd_eb.PollHelper(poll_request);
        var integration = poller.getIntegration();
        var conn = integration.getActiveConnection();
        var cvar = conn.getVariables();
        var info = [
            'Incident : ' + params.int_ref
        ];
    
        // Use Unifi code to find the Bond for the Incident
        var bond = new x_snd_eb.Bond(integration.getConfig());
        bond.locateReference(integration,params.int_ref,params.ext_ref);
        if ( !bond.isValidRecord() ) {
            // If no bond was found, ignore this poll
            info.push('- Bond not found - Attachments ignored');
            poll_request.response_status = info.join('\n') + '\n\n' + JSON.stringify(body,null,2);
            return;
        }
    
        var attachment_hwm;
    
        // Process each result
        body.result.forEach(function(attach){
    
            // Build an attachment object to pass on to the next poller
            var attachment = {
                remote_id    : attach.sys_id,
                file_name    : attach.file_name,
                content_type : attach.content_type,
                size_bytes   : attach.size_bytes
            };
    
            info.push('- Get attachment (' + attach.remote_id + '): ' + attach.file_name);
    
            x_snd_eb.Poller.execute( cvar.get_attachment_poller, {
                int_ref    : params.int_ref,
                ext_ref    : params.ext_ref,
                attachment : attachment
            });
    
            // Keep track of the latest created_on time
            attachment_hwm = attach.sys_created_on;
    
        });
    
        // Update Attachment High water mark (if later)
        if ( attachment_hwm > params.attachment_hwm ) {
            bond.setData(ATTACHMENT_HWM,attachment_hwm);
        }
    
        poll_request.response_status = info.join('\n') + '\n\n' + JSON.stringify(body,null,2);
    
    })(poll_request, poller, response, params);