Skip to content

Commit 0e18db6

Browse files
authored
Merge branch 'ServiceNowDevProgram:main' into main
2 parents 737c90e + 9ad7cb4 commit 0e18db6

File tree

506 files changed

+13328
-179
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

506 files changed

+13328
-179
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.DS_Store

Attachments/CSVParser/script.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/********************************************************************************/
2+
Input:
3+
attachmentQuery - Pass sysId CSV attachment
4+
5+
Output:
6+
converted into object from CSV
7+
8+
/********************************************************************************/
9+
10+
function parseCSVFile(sysId) {
11+
var attachmentRecord = new GlideRecord("sys_attachment");
12+
attachmentRecord.get(sysId);
13+
attachmentRecord.query();
14+
15+
if (attachmentRecord.next()) {
16+
var stringUtil = new GlideStringUtil();
17+
var sysAttachment = new GlideSysAttachment();
18+
var bytesData = sysAttachment.getBytes(attachmentRecord);
19+
var encData = stringUtil.base64Encode(bytesData);
20+
var decData = stringUtil.base64Decode(encData) + '';
21+
22+
var delimiter = ',';
23+
var quoteCharacter = '"';
24+
var csvArray = decData.split("\r\n");
25+
26+
var index = 0
27+
var result = [];
28+
for (index = 0; index < csvArray.length; index++) {
29+
var row = csvArray[index];
30+
if (row) {
31+
var csvParser = new sn_impex.CSVParser().parseLineToArray(row, delimiter, quoteCharacter);
32+
var rowObject = {};
33+
for (var i = 0; i < csvParser.length; i++) {
34+
rowObject['column' + (i + 1)] = csvParser[i];
35+
}
36+
result.push(rowObject);
37+
}
38+
}
39+
return result;
40+
}
41+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
//It can be used within a Business Rule - After Insert
2+
(function executeRule(current, previous /*null when async*/) {
3+
4+
insertAttachment();
5+
6+
})(current, previous);
7+
8+
function insertAttachment() {
9+
10+
var gsa = new GlideSysAttachment();
11+
var attachmentId = gsa.write(current, "fileName.txt", 'text/plain', "some data");
12+
13+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
## Create an Attachment via script
2+
3+
You can create a Business Rule (ie: After Insert) to automatically create an Attachment.
4+
5+
In this example we're creating a text file containing 'some data'.
6+
7+
The file name is 'fileName.txt'
Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
// To automatically delete RITM attachment, when an attachment is deleted on SCTASK.
2-
// Create a After Business Rule, and set business rule condition as Table name is "sctask", so that when an attachment is deleted on SCTASK, this business rule will run.
2+
// Create a After Delete Business Rule on sys_attachment table, and set business rule condition as Table name is "sctask", so that when an attachment is deleted on SCTASK, this business rule will run.
33

4-
var gr = new GlideRecord("sys_attachment");
5-
var task = new GlideRecord('sc_task');
6-
if (task.get(current.table_sys_id)) {
7-
gr.addEncodedQuery("table_name=sc_req_item^table_sys_id=" + task.request_item.sys_id + "^file_nameSTARTSWITH" + current.file_name);
8-
gr.query();
9-
if(gr.next())
10-
//gr.deleteRecord();
4+
var glideAttachment = new GlideRecord("sys_attachment");
5+
var glideTask = new GlideRecord('sc_task');
6+
if (glideTask.get(current.table_sys_id)) {
7+
glideAttachment.addEncodedQuery("table_name=sc_req_item^table_sys_id=" + glideTask.request_item.sys_id + "^file_name=" + current.file_name);
8+
glideAttachment.query();
9+
if(glideAttachment.next())
10+
1111
var attachment = new GlideSysAttachment();
12-
attachment.deleteAttachment(gr.getValue("sys_id"));
12+
attachment.deleteAttachment(glideAttachment.getValue("sys_id"));
13+
1314
}
1415

1516
})(current, previous);

Attachments/ExportRecordsAnyFormat/exportRecords.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/*****************************************************************************************/
1+
/*
22
INPUT:
33
tableName - Name of table whose records need to be exported
44
recordId - sys_id of the record where the exported attachment should be uploaded
@@ -10,12 +10,17 @@ fileName - Name of exported file along with its extension eg fileName.csv, fileN
1010
OUTPUT:
1111
status - HTTP status of export
1212
200 = Successfully exported
13+
14+
Access - The user should have required access/roles to read the exported tables, and write to the record where the file will be attached
15+
16+
Authentication option #1 - preferred
17+
Create a Basic Auth credential record and insert the sys_id of the Credential record in the script below
1318
14-
Note: Create 2 system properties to store the user_name and password of a web service access user
19+
Authentication option #2 - less secure
20+
Create 2 system properties to store the user_name and password of a web service access user
1521
pdf.export.user.id - user_name of the web service only access user
1622
pdf.export.user.password - password of the user
17-
The user should have required access to read the exported tables
18-
/*****************************************************************************************/
23+
*/
1924

2025
function exportRecords(tableName, recordId, recordQuery, recordView, dataType, fileName) {
2126
var response;
@@ -31,7 +36,16 @@ function exportRecords(tableName, recordId, recordQuery, recordView, dataType, f
3136
url = gs.getProperty('glide.servlet.uri') + tableName + '.do?'+ dataType + '&sysparm_query=' + recordQuery + '&sysparm_view='+recordView;
3237
}
3338
restMessage.setEndpoint(url);
34-
restMessage.setBasicAuth(gs.getProperty('pdf.export.user.id'), gs.getProperty('pdf.export.user.password'));
39+
40+
//Authentication option #1 - preferred
41+
var credentialID = "ef43c6d40a0a0b5700c77f9bf387afe3"; //SYSID of the Credential record, REPLACE VALUE FROM YOUR INSTANCE
42+
var provider = new sn_cc.StandardCredentialsProvider();
43+
var credential = provider.getCredentialByID(credentialID);
44+
restMessage.setBasicAuth(credential.getAttribute("user_name"), credential.getAttribute("password"));
45+
46+
//Authentication option #2 - less secure
47+
//restMessage.setBasicAuth(gs.getProperty('pdf.export.user.id'), gs.getProperty('pdf.export.user.password'));
48+
3549
restMessage.saveResponseBodyAsAttachment(tableName, recordId, fileName);
3650
response = restMessage.execute();
3751
status = response.getStatusCode();
Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,42 @@
1-
The snippet can be used to export records from any table and then attach on another record. You could export records in any of the these formats (CSV, XLS, XLSX, PDF, JSON, XML, XSD, SCHEMA, RSS) from any table view based on an encoded query. If required, the attachment can be send out to users through a notification (with check include attachments).
1+
The snippet can be used to export records from any table and then attach on another record. Records can be exported records from any table view based on an encoded query in any of the these formats: CSV, XLS, XLSX, PDF, JSON, XML, XSD, SCHEMA, RSS. If required, the attachment can be send out to users through a notification (with check include attachments).
22

3-
Sample Usage:
3+
#### Access & Authentication
4+
A user with web service access and read access to the data needs to be present in the instance. The user must also have write access to the record where the file will be attached.
45

5-
//Export all active incidents from the ESS view into XLSX format
6+
In the script there are two options for authentication:
67

8+
1. [Credentials](https://docs.servicenow.com/en-US/bundle/vancouver-platform-security/page/product/credentials/reference/credentials-getting-started.html) - preferred
9+
2. Using system properties to store username and password - less secure
10+
11+
#### Input Format
12+
13+
- tableName: Name of table whose records need to be exported
14+
- recordId: sys_id of the record where the exported attachment should be uploaded, this record must exist on the same table
15+
- recordQuery: encoded query to access the required records. For PDF files, you should only pass sys_id eg: sys_id=b3f076504750210042bd757f2ede273f
16+
- recordView: Specify the required view, Pass empty string for default view eg: ess, portal,
17+
- dataType: The required export format - Supported formats eg CSV, XLS, EXCEL, XLSX, PDF, JSONv2, XML, XSD, SCHEMA, RSS
18+
- fileName: Name of exported file along with its extension eg fileName.csv, fileName.json
19+
20+
EXAMPLE: ```gs.print(exportRecords(tableName, recordId, recordQuery, recordView, dataType, fileName));```
21+
22+
### Sample Usage
23+
24+
#### Export all active incidents from the ESS view into XLSX format
25+
26+
```javascript
727
gs.print(exportRecords('incident', 'b3f076504750210042bd757f2ede273f', 'active=true', 'ess', 'XLSX', 'Active Incidents.xlsx'));
28+
```
829

9-
//Export all active incident from the defaut view in JSON format
30+
#### Export all active incident from the default view in JSON format
1031

32+
```javascript
1133
gs.print(exportRecords('incident', 'b3f076504750210042bd757f2ede273f', 'active=true', '', 'JSONv2', 'Active Incidents.json'));
34+
```
1235

13-
//Export a record into PDF
36+
#### Export a record into PDF
1437

38+
```javascript
1539
gs.print(exportRecords('incident', 'b3f076504750210042bd757f2ede273f', 'sys_id=b3f076504750210042bd757f2ede273f', '', 'PDF', 'record.pdf'));
40+
```
1641

1742

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
var AttachmentSftpUtils = Class.create();
2+
AttachmentSftpUtils.prototype = {
3+
initialize: function () {
4+
// Set up the Packages references
5+
6+
this.File = Packages.java.io.File;
7+
this.FileOutputStream = Packages.java.io.FileOutputStream;
8+
9+
10+
//get the parameters
11+
12+
this.relativeUrl = probe.getParameter("relativeUrl");
13+
this.domain = probe.getParameter("httpDomain");
14+
this.midlogs = probe.getParameter("MidLogs");
15+
this.filename = probe.getParameter("filename");
16+
this.midserverfilepath = probe.getParameter("midserverpath");
17+
this.midserverfilename = probe.getParameter("filename");
18+
//this.deleteAfterUpload = probe.getParameter("deleteAfterUpload");
19+
this.SnowMidUserName = probe.getParameter("SnowMidUsername");
20+
this.SnowMidPassword = probe.getParameter("SnowMidPassword");
21+
22+
//sftp
23+
24+
this.targetServer = probe.getParameter('sftpTargetServer');
25+
this.targetUsername = probe.getParameter('sftpTargetUsername');
26+
this.targetPassword = probe.getParameter('sftpTargetPassword');
27+
this.targetPort = probe.getParameter('sftpTargetPort');
28+
this.sftpFilePath = probe.getParameter('sftpFilePath');
29+
},
30+
31+
processFileTransfer: function() {
32+
33+
this.log("ShammaSalhotra");
34+
35+
36+
var localFileName = this.midserverfilepath + "/" + this.midserverfilename;
37+
38+
try {
39+
var fn = this.saveToFile(localFileName);
40+
this.log("File is moved to MIDserver or not "+ fn);
41+
42+
if(fn){
43+
this.log("Initiated file transfer from MID Server: " + localFileName);
44+
45+
var fnc = this.sftpFile(this.targetServer, this.targetUsername, this.targetPassword, localFileName, this.sftpFilePath + this.midserverfilename);
46+
if(fnc!=""){
47+
48+
return fnc;
49+
50+
}
51+
return "file is moved to mid server";
52+
}
53+
} catch (e) {
54+
this.log("ShammaSalhotra1");
55+
this.log("Error in writing file to SFTP server: " + e);
56+
57+
return "Error in writing file to SFTP server: " + e;
58+
}
59+
60+
},
61+
saveToFile: function(targetPath) {
62+
var tmpLoc;
63+
var result = true;
64+
65+
//var DPassword = new Packages.com.glide.util.Encrypter().decrypt(this.SnowMidPassword); // decrypting the password
66+
var DPassword = this.SnowMidPassword;
67+
//Initiating the webservice to get the attachment from servicenow
68+
69+
this.HttpClients = Packages.com.glide.communications.HTTPRequest; // GlideHTTPRequest
70+
71+
var munewurl = this.relativeUrl;
72+
73+
74+
var request = new this.HttpClients(munewurl);
75+
request.setBasicAuth(this.SnowMidUserName,DPassword);
76+
request.addHeader('Accept','application/json');
77+
var response = request.get();
78+
79+
80+
81+
var status = response.getStatusCode();
82+
83+
this.log("Response " + status);
84+
tmpLoc = targetPath;//this.midserverfilepath + this.midserverfilename;
85+
86+
if( status == "200" ){
87+
// Save the attachment in midserver
88+
89+
try {
90+
91+
this.log("Saving the attachment to " + this.filename +"::" + targetPath);
92+
var f = new this.File(targetPath);
93+
var inputStream = response.getBodyAsStream();
94+
var out = new this.FileOutputStream(f);
95+
var buf = Packages.java.lang.reflect.Array.newInstance(Packages.java.lang.Byte.TYPE, 1024);
96+
while ((len = inputStream.read(buf)) > 0) {
97+
98+
out.write(buf, 0, len);
99+
}
100+
out.close();
101+
102+
this.log("File saved to: " + f);
103+
inputStream.close();
104+
105+
}catch (e) {
106+
107+
result = false;
108+
}
109+
}
110+
else{
111+
112+
result = false;
113+
}
114+
return result;
115+
},
116+
117+
118+
sftpFile : function(hostName, userName, password, localFileName, remoteFileName) {
119+
// Initiate the file transfer from midserver to sftp server
120+
this.log("Shamma");
121+
var result = "";
122+
this.log('sftpFile(): attempting to connect to ' + hostName);
123+
var ssh = new Packages.com.sshtools.j2ssh.SshClient();
124+
var ignoreHost = new Packages.com.sshtools.j2ssh.transport.IgnoreHostKeyVerification();
125+
if (!this.targetPort){
126+
this.targetPort = 22;
127+
}
128+
this.log('sftpFile(): attempting to connect to ' + hostName + " on port " + this.targetPort);
129+
ssh.connect(hostName, this.targetPort, ignoreHost);
130+
131+
var pwd = new Packages.com.sshtools.j2ssh.authentication.PasswordAuthenticationClient();
132+
//var authPassword = new Packages.com.glide.util.Encrypter().decrypt(password);
133+
//var tarpassword = this.targetPassword;
134+
pwd.setUsername(userName);
135+
pwd.setPassword(password);
136+
137+
138+
this.log('sftpFile(): attempting to copy ' + localFileName + ' to ' + remoteFileName);
139+
if(ssh.authenticate(pwd) == new Packages.com.sshtools.j2ssh.authentication.AuthenticationProtocolState().COMPLETE) {
140+
sftp = ssh.openSftpClient();
141+
142+
try {
143+
sftp.put(localFileName, remoteFileName);
144+
this.log("File successfully uploaded to sftp " + remoteFileName);
145+
146+
result = "File successfully uploaded to sftp";
147+
148+
if (this.deleteAfterUpload == "true") {
149+
this.log("deleteAfterUpload -> " + this.deleteAfterUpload + ", deleting local file...");
150+
new this.File(localFileName)["delete"]();
151+
}
152+
} catch(e) {
153+
this.log('FILE NOT FOUND ' + remoteFileName + ' or error: ' + e);
154+
result = 'FILE NOT FOUND ' + remoteFileName + ' or error: ' + e;
155+
}
156+
sftp.quit();
157+
try{
158+
// kill connection
159+
ssh.disconnect();
160+
}
161+
catch(e){
162+
this.log('Manual connection kill not successful with error: ' + e);
163+
result = 'Manual connection kill not successful with error: ' + e;
164+
}
165+
}
166+
else {
167+
result = 'Error ' + new Packages.com.sshtools.j2ssh.authentication.AuthenticationProtocolState().COMPLETE;
168+
}
169+
170+
return result;
171+
172+
},
173+
174+
log: function(data) {
175+
if (this.midlogs == "true") {
176+
ms.log(data);
177+
}
178+
},
179+
180+
type: AttachmentSftpUtils
181+
};
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
This script helps you to copy file to MID Server/SFTP SErver via MID Server SCript Include. You can use this scripting to copy the file from ServiceNow Instance to MID Server or SFTP Server or any other Server. You just need to pass the parameters while calling this script like IP of Server, Server Authentication username and password. You can write this script in MID Server Script Include table in ServiceNow and you can call this script from any business rule with the help of JAvascript Probe. This is very useful script and can be used in scoped and global application.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
var priorityMapping = {
2+
'Network': 1,
3+
'Application': 2,
4+
'Hardware': 3
5+
};
6+
7+
var incidentGR = new GlideRecord('incident');
8+
incidentGR.addQuery('active', true);
9+
incidentGR.query();
10+
11+
while (incidentGR.next()) {
12+
var category = incidentGR.category.toString();
13+
var newPriority = priorityMapping[category];
14+
15+
if (newPriority) {
16+
incidentGR.priority = newPriority;
17+
incidentGR.update();
18+
gs.info('Updated Incident: ' + incidentGR.number + ' to Priority: ' + newPriority);
19+
}
20+
}

0 commit comments

Comments
 (0)