Skip to content

Instantly share code, notes, and snippets.

@harrisitservices
Last active February 2, 2021 22:13
Show Gist options
  • Save harrisitservices/82d02e274268b1191ba486150569fdb9 to your computer and use it in GitHub Desktop.
Save harrisitservices/82d02e274268b1191ba486150569fdb9 to your computer and use it in GitHub Desktop.
ServiceNow: Exporting Update Sets to the Midserver

ServiceNow: Exporting Update Sets to the MidServer

This gist includes a script include and background script that can be used to export files from ServiceNow to a connected Midserver in many different formats. I took the code provided here and tweaked it so that I could do what I wanted to do.

Components

  • MidServer Script Include
var ExportToMidserver = Class.create();

ExportToMidserver.prototype = {

   initialize: function () {
      //
      // Set up the Packages references
      //
      this.File = Packages.java.io.File;
      this.FileOutputStream = Packages.java.io.FileOutputStream;
      this.HttpClient = Packages.org.apache.commons.httpclient.HttpClient;
      this.UsernamePasswordCredentials = Packages.org.apache.commons.httpclient.UsernamePasswordCredentials;
      this.AuthScope = Packages.org.apache.commons.httpclient.auth.AuthScope;
      this.GetMethod = Packages.org.apache.commons.httpclient.methods.GetMethod;

      //
      //Set up the parameters
      //
      this.domain = probe.getParameter("httpDomain");
      this.port = probe.getParameter("httpDomainPort");
      this.protocol = probe.getParameter("httpProtocol"); //http/https
      this.relativeUrl = probe.getParameter("relativeUrl");
      this.verbose = probe.getParameter("verbose");
      this.filename = probe.getParameter("filename");
	  this.directory = probe.getParameter("directory");
	  this.username = probe.getParameter("username");
	  this.password = probe.getParameter("password");
      //
      // run it automatically
      //
      //return this.execute();

   },

   execute: function () {
      //
      // Set up the HTTP Connection.  We will use the PDF web service built into SN
      //
      var client = new this.HttpClient();
      var authScope = new this.AuthScope(this.domain, this.port, null);
      var credentials = new this.UsernamePasswordCredentials(this.username,this.password);
      client.getState().setCredentials(authScope, credentials);
      var url = this.protocol + "://" + this.domain + ":" + this.port + "/" + this.relativeUrl;
      this.debug("URL: "+url);
      var get = new this.GetMethod(url);
      get.setDoAuthentication(true);

      //
      // Now that we have the HTTP client set up, we are going to submit the request
      // to ServiceNow
      //
      var status = client.executeMethod(get);
      this.debug("GET Status: " + status);

      if( status == "200" ){
     //
     // We are going to write the HTTP Response to a file
     //
         this.debug("Attempted to save the file to filname: " + this.filename);
		 var f = new this.File(this.directory).mkdirs();
         var f = new this.File(this.directory+'/'+this.filename);
         var inputStream = get.getResponseBodyAsStream();
         var out = new this.FileOutputStream(f);
         var buf = Packages.java.lang.reflect.Array.newInstance(Packages.java.lang.Byte.TYPE, 1024);
         while ((len = inputStream.read(buf)) > 0) {
            this.debug("Writing to the file…with buffer size of "+len);
            out.write(buf, 0, len);
         }
         out.close();
         inputStream.close();
         var result = "Done creating "+this.filename;
     this.debug(result);
      } else {
         var result = "Invalid HTTP Response.  Exiting Early.";
         this.debug(result);
      }
      return result;
   },

   debug: function (m) {
      if (this.verbose == "true") {
         ms.log(m);
      }
   },

   type: ExportToMidserver
};
  • Background Script (For Testing)
var username = ""; // Enter username of an admin
var password = ""; // Enter password of an admin

var updates = getUpdateSetIds();
createXmlForUpdateSets(updates);

function getUpdateSetIds() {
	var ids = [];
	var us = new GlideRecord('sys_update_set');
	us.addEncodedQuery('state=in progress^sys_created_by!=system^ORsys_created_by=NULL');
	us.query();
	while(us.next()) {
		ids.push(us.sys_id+'');
	}
	return ids;
}

function createXmlForUpdateSets(ids) {
	for (var i = 0; i < ids.length; i++) {
		var update_set = new GlideRecord('sys_update_set');
		update_set.get(ids[i]);

		var retrievedUpdateSet = new GlideRecord('sys_remote_update_set');
		retrievedUpdateSet.initialize();
		retrievedUpdateSet.description = update_set.description+'';
		retrievedUpdateSet.name = update_set.name+'';
		retrievedUpdateSet.release_date = update_set.release_date+'';
		retrievedUpdateSet.remote_sys_id = update_set.sys_id+'';
		retrievedUpdateSet.application = update_set.application+'';

		var scopeGr = new GlideRecord('sys_scope');
		scopeGr.get(update_set.application);
		if (scopeGr.isValid()) {
			retrievedUpdateSet.application_name = scopeGr.name;
			retrievedUpdateSet.application_scope = scopeGr.scope;
			retrievedUpdateSet.application_version = scopeGr.version;
		}

		retrievedUpdateSet.state = "loaded";
		var exp_id = retrievedUpdateSet.insert();

		var update = new GlideRecord('sys_update_xml');
		update.addQuery('update_set', update_set.sys_id);
		update.query();

		while(update.next()) {
		   update.remote_update_set = retrievedUpdateSet.sys_id+'';
		   update.update_set = '';
		   update.insert();
		}
		var file_name = '';
		if (update_set.name+''== 'Default') {
			file_name = update_set.name+' - '+update_set.application.name+'';
		} else {
			file_name = update_set.name+'';
		}
		_exportToMid(exp_id, file_name);
	}
}

function _exportToMid(sys_id, name) {
	var jspr = new JavascriptProbe('cfdlsnmid01');
	jspr.setName('ExportToMidserver'); //Any descriptive name will do
	jspr.setJavascript('var exp = new ExportToMidserver(); res = exp.execute();');
	jspr.addParameter("httpDomain", "cfadev.service-now.com");
	jspr.addParameter("httpDomainPort", "443");
	jspr.addParameter("httpProtocol", "https");
	jspr.addParameter("relativeUrl", "export_update_set.do?sysparm_sys_id=" + sys_id + "&sysparm_delete_when_done=true");
	jspr.addParameter("verbose", "true");
	jspr.addParameter("filename", name+".xml");
        jspr.addParameter("directory", "/apps/servicenow/files/"+_getDate());
	jspr.addParameter("username", username);
	jspr.addParameter("password", password);
	jspr.create();
}

function _getDate() {
    var currentTime = new Date();
    var month = ("0"+(currentTime.getMonth()+1)).slice(-2);
    var day = ("0"+currentTime.getDate()).slice(-2);
    var year = currentTime.getFullYear();
    var today = year+'_'+month+'_'+day;
    return today;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment