Thank you for your feedback.
Form temporarily unavailable. Please try again or contact docfeedback@servicenow.com to submit your comments.
Versions
  • Madrid
  • London
  • Kingston
  • Jakarta
  • Istanbul
  • Helsinki
  • Geneva
  • Store
Close

Custom connector code sample

Log in to subscribe to topics and get notified when content changes.

Custom connector code sample

The code sample used in this connector definition demonstrates how to manage events using web service API.

Note: The sample connector code is not updated automatically. Check the connector code on the instance from time-to-time as it might be updated.
You can use the following code sample to create a JavaScript connector for receiving events from a SolarWinds external source.
var SolarWindsJS = Class.create();

var SUCCESS = Packages.com.service_now.mid.probe.tpcon.OperationStatusType.SUCCESS;
var FAILURE = Packages.com.service_now.mid.probe.tpcon.OperationStatusType.FAILURE;
var Event   = Packages.com.snc.commons.eventmgmt.Event;
var SNEventSenderProvider = Packages.com.service_now.mid.probe.event.SNEventSenderProvider;
var HTTPRequest = Packages.com.glide.communications.HTTPRequest;


var SOLAR_WINDS = "SolarWinds";
var MAX_EVENTS_TO_FETCH = 3000;

SolarWindsJS.prototype = Object.extendsObject(AProbe, {

    // test the connection with SolarWind server 
    testConnection : function() {

        ms.log("Solarwinds testing connection");
         
        var retVal = {};
        
        try {

            var query = 'SELECT TOP 10 NodeID FROM Orion.Nodes';  
         
            var response = this.getResponse(query);
    
            ms.log('SolarWindJS Connector Test Connection response:' + response.getBody());      
            ms.log('result:' + response.getStatusCode());
            
            if (response.getStatusCode() == 200)
                retVal['status']  = "" + SUCCESS.toString();
            else
                retVal['status']  = "" + FAILURE.toString();

        } catch (e) {
            ms.log("Failed to connect to Solarwinds");
            ms.log(e); 
            retVal['status'] = FAILURE.toString();
        }
        
        ms.log("SolarWindJS Connector testConnection " + retVal['status'] );
        
        return retVal;
        
        
    },
    


    execute: function() {

        ms.log("SolarWindJS Connector: execute connection ...");
                
        var retVal = {};
            
        var lastSignature = this.probe.getParameter("last_event");
        
        var events = this.getEvents(lastSignature);
        if (events == null) {
            retVal['status'] = FAILURE.toString();
            return retVal;
        }

        // send all events          
        var sender = SNEventSenderProvider.getEventSender();
        var i = 0;
        for (; i< events.length; i++) {
            if (events[i]) {
                sender.sendEvent(events[i]);
            }
        }

        retVal['status'] = SUCCESS.toString();
        if (events.length > 0) {
            // the result is sorted, but the sort order can differ. Therefore 
            // the last signature is either on the first or the last event
            var firstEventSignature = events[0].getField("swEventId");
            var lastEventSignature = events[events.length-1].getField("swEventId");
            
            if (firstEventSignature >= lastEventSignature)
                retVal['last_event'] = firstEventSignature;
            else 
                retVal['last_event'] = lastEventSignature;
        }
        
        ms.log("SolarWindJS Connector: sent " + events.length + 
               " events. Return to instance: status="+retVal['status'] + 
               "  lastDiscoverySignature=" + retVal['last_event'] );

        return retVal;
    },
    
    getResponse: function(query) {
        
        var username =  this.probe.getParameter("username");
        var password =  this.probe.getParameter("password");
        var host =  this.probe.getParameter("host");

        var port =  this.probe.getAdditionalParameter("port");

        var url = 'https://'+host+':' + port + '/SolarWinds/InformationService/v3/Json/Query?query=' 
                +encodeURIComponent(query);  
        
        ms.log('SolarWindJS Connector URL: ' + url);    
        var request = new HTTPRequest(url);
        request.setBasicAuth(username, password);
        request.addHeader('Accept','application/json');
        var response = request.get();
        return response;
    },
    
    
    getEvents: function(latestTimestamp) 
    {

        


        var query = "SELECT TOP " + MAX_EVENTS_TO_FETCH + 
            " EventID, EventTime, NetworkNode, NetObjectID, EventType, Message, Acknowledged, " +
            "NetObjectType, Timestamp FROM Orion.Events " +
            "WHERE NetworkNode > 0 AND NetObjectID > 0 ";

 
        if (latestTimestamp != null) {
            query = query + "AND EventID > " + latestTimestamp + " order by EventID asc ";
        } else {
            // if this is the first time just take maxEventsCount events from the end
            query = query + " order by EventID desc ";
        }
        
        var resultJson = this.getJSON(query);
        
        if (resultJson == null)
            return null;
               
        var emsName =  this.probe.getParameter("connector_name");
        var events = [];
                
        // if no events were found, return
        if (resultJson.results.length === 0)
            return events;
        
        
        // init all maps with additional information for events
        var eventTypes = this.getEventTypes();
        var applications = this.getApplications();
        var components = this.getComponents();
        var nodes = this.getNodes();
        
        if (eventTypes == null || applications == null || components == null || nodes == null) {
            return null;
        }
        
        var i = 0;
        for (; i<resultJson.results.length; i++) {
            var event = Event();

            if (resultJson.results[i].EventTime != null) {

                // input is yyyy-MM-dd'T'HH:mm:ss.mmm. we are taking yyyy-MM-dd HH:mm:ss
                var stringToParse = resultJson.results[i].EventTime;        
                var dateStr = stringToParse.substr(0,10);
                var timeStr = stringToParse.substr(11,8);       
                event.setTimeOfEvent(dateStr + " " + timeStr); 
            }
                    
            var component = components[resultJson.results[i].NetObjectID];
            if (component != null) {
                event.setMetricName(component[0]);
                if (component[1] != null) {
                    var applicationName = applications[component[1]];   
                    if (applicationName != null) {
                        event.setResource(applicationName);
                    }

                }
            }
            
    
            // remove not ascii chars
            var sanitizedMessage = resultJson.results[i].Message.replace(/[^\x00-\x7F]/g, " ");
            
            // replace \" with "
            sanitizedMessage = sanitizedMessage.replace(/\\"/g, "\"");
            
            event.setText(sanitizedMessage);
            
            if (nodes[resultJson.results[i].NetworkNode] != null) { 
                var node = nodes[resultJson.results[i].NetworkNode];
                event.setHostAddress(node[0]);
                event.setField("hostname", node[1]);
            
            }
    
            
            
            event.setField("eventType", resultJson.results[i].EventType);
            
            if (eventTypes[resultJson.results[i].EventType] != null) 
                event.setField("icon", eventTypes[resultJson.results[i].EventType]);
            
                        
            event.setField("netObjectId", resultJson.results[i].NetObjectID);
            event.setField("swEventId", resultJson.results[i].EventID);
                        
            event.setField("networkNodeId", resultJson.results[i].NetworkNode);
    
            event.setSource(SOLAR_WINDS);
            event.setEmsSystem(emsName);
            
            event.setResolutionState("New");

            // filter out events on first pull
            if (latestTimestamp != null || !this.filterEvent(event)) {
                events[i] = event;    
            }
        }

        return events;
    },
    
    filterEvent : function (event) {
        var icon = String(event.getField("icon"));
        if (icon === "Add" || icon === "Green" || icon === "Start") {
            return true;
        }
            
        return false;
    },
    
    getEventTypes : function () {
        
       var resultJson = this.getJSON(
           "SELECT EventType, Name, Icon, NotifyMessage,NotifySubject FROM  Orion.EventTypes");

        if (resultJson == null)
            return null;
        
        var resultMap = {};
        
        var i = 0;
        for (; i<resultJson.results.length; i++) 
            resultMap[resultJson.results[i].EventType] = resultJson.results[i].Icon;
            
        return resultMap;
    },

    
    getApplications : function () {
        
        var resultJson = this.getJSON("SELECT ApplicationId, Name FROM Orion.Apm.Application");

        if (resultJson == null)
            return null;
        
        var resultMap = {};
        var i = 0;
        for (; i<resultJson.results.length; i++)  
            resultMap[resultJson.results[i].ApplicationId] = resultJson.results[i].Name;

        return resultMap;
    },
    
    getComponents : function () {
        
        var resultJson = 
            this.getJSON("SELECT ComponentID, Name, applicationID FROM Orion.Apm.Component");

        if (resultJson == null)
            return null;
        
        var resultMap = {};
        var i = 0;
        for (; i< resultJson.results.length; i++)  
                resultMap[resultJson.results[i].ComponentID] = 
                    [resultJson.results[i].Name, resultJson.results[i].applicationID];
                    
        return resultMap;
    },
    
    getNodes : function () {
        
       var resultJson = this.getJSON(
           "SELECT NodeID, IPAddress, DNS FROM Orion.Nodes");

        if (resultJson == null)
            return null;
        
        var resultMap = {};
        
        var i = 0;
        for (; i<resultJson.results.length; i++) 
                resultMap[resultJson.results[i].NodeID] = 
                    [resultJson.results[i].IPAddress, resultJson.results[i].DNS];
            
        return resultMap;
    },

    getJSON : function (query) {
        
        var response = this.getResponse(query);
    
        if (response == null) {
            ms.log("SolarWindJS Connector: Failed to bring data. Null response");
            return null;
        }
        
        if (response.getStatusCode() != 200) {
            ms.log("SolarWindJS Connector Error Code: " +  response.getStatusCode());
            return null;
        }

        var parser = new JSONParser();
        var resultJson =  parser.parse(response.getBody() );
        ms.log("SolarWindJS Connector: Found " + resultJson.results.length + " records");
        return resultJson;
            
    },
    

    type: "SolarWindsJS"
});

Feedback