Professional Documents
Culture Documents
HP Service Manager 7 Javascript HP
HP Service Manager 7 Javascript HP
Introduction......................................................................................................................................... 4
Requirements ................................................................................................................................... 4
How to use this document ................................................................................................................. 4
Introduction to JavaScript in Service Manager ......................................................................................... 4
Language overview .......................................................................................................................... 4
Basic rules of JavaScript.................................................................................................................... 5
Structure of a JavaScript application ............................................................................................... 5
Expressions and operators............................................................................................................. 5
JavaScript objects and properties ................................................................................................... 6
Built-in objects and functions .......................................................................................................... 6
Conditional statements .................................................................................................................. 6
While and loop statements ............................................................................................................ 6
Break and continue statements ....................................................................................................... 7
Exception Handling statements....................................................................................................... 8
Use of JavaScript in Service Manager .................................................................................................... 8
Order of execution of JavaScript versus RAD language......................................................................... 8
The ScriptLibrary ............................................................................................................................ 10
Using the ScriptLibrary ................................................................................................................ 10
Corresponding JavaScript syntax for RAD language tasks ................................................................... 11
JavaScript global properties ............................................................................................................ 12
Query operators......................................................................................................................... 12
JavaScript return code properties.................................................................................................. 12
Examples of calling JavaScript from different Service Manager tools .................................................... 13
FormatControl ............................................................................................................................ 13
Triggers..................................................................................................................................... 14
Links ......................................................................................................................................... 16
Programmer’s reference...................................................................................................................... 17
JavaScript global system objects ...................................................................................................... 17
system.files ................................................................................................................................ 18
system.forms .............................................................................................................................. 18
system.functions ......................................................................................................................... 19
system.library............................................................................................................................. 19
system.oldrecord ........................................................................................................................ 20
system.record............................................................................................................................. 20
system.sysinfo ............................................................................................................................ 20
system.threads ........................................................................................................................... 21
system.user ................................................................................................................................ 21
system.users............................................................................................................................... 22
system.vars ................................................................................................................................ 22
JavaScript global methods............................................................................................................... 22
print.......................................................................................................................................... 22
readFile..................................................................................................................................... 23
writeFile .................................................................................................................................... 23
Quit.......................................................................................................................................... 24
base64Encode........................................................................................................................... 24
base64Decode .......................................................................................................................... 25
xmlstring ................................................................................................................................... 25
doHTTPRequest .......................................................................................................................... 26
doSOAPRequest ......................................................................................................................... 26
makeSCWebURL........................................................................................................................ 28
help .......................................................................................................................................... 29
RCtoString ................................................................................................................................. 29
execute ..................................................................................................................................... 30
compile ..................................................................................................................................... 30
JavaScript objects .......................................................................................................................... 31
Attachment ................................................................................................................................ 31
Header ..................................................................................................................................... 32
SCFile ....................................................................................................................................... 32
XML .......................................................................................................................................... 34
XMLDate ................................................................................................................................... 35
JavaScript methods for the SCFile objects.......................................................................................... 37
SCFile.doAction() ....................................................................................................................... 37
SCFile.doDelete()........................................................................................................................ 38
SCFile.doInsert() ......................................................................................................................... 39
SCFile.doRemove() ..................................................................................................................... 40
SCFile.doSave() ......................................................................................................................... 40
SCFile.doSelect(“query”) ............................................................................................................. 41
SCFile.doUpdate() ...................................................................................................................... 42
SCFile.getFirst() .......................................................................................................................... 43
SCFile.getLast()........................................................................................................................... 44
SCFile.getNext()......................................................................................................................... 45
SCFile.getPrev().......................................................................................................................... 46
SCFile.getSize().......................................................................................................................... 47
SCFile.getText() .......................................................................................................................... 48
SCFile.getType() ......................................................................................................................... 49
SCFile.getXML().......................................................................................................................... 50
SCFile.join()............................................................................................................................... 50
SCFile.JSDate(dataType) ............................................................................................................. 51
SCFile.length()............................................................................................................................ 52
SCFile.pop() .............................................................................................................................. 54
SCFile.push(arrayItem) ................................................................................................................ 55
SCFile.setValue(newValue) .......................................................................................................... 56
SCFile.shift()............................................................................................................................... 56
SCFile.toArray() ......................................................................................................................... 57
SCFile.unshift(arrayItem).............................................................................................................. 58
JavaScript methods for the XML object .............................................................................................. 59
XML.addAttribute(AttributeName, AttributeValue) ........................................................................... 59
XML.addElement(String) .............................................................................................................. 61
XML.appendNode(name) ............................................................................................................ 63
XML.createNode(type, name, value) ............................................................................................. 64
XML.getAttributeNode(Attribute) ................................................................................................... 65
XML.getAttributeValue(Attribute) ................................................................................................... 67
XML.getDocumentElement().......................................................................................................... 69
XML.getFirstAttribute(Element) ...................................................................................................... 70
XML.getFirstChildElement(Element)................................................................................................ 73
XML.getName() .......................................................................................................................... 75
XML.getNextAttribute(Element) ..................................................................................................... 76
XML.getNextSiblingElement(Element) ............................................................................................ 79
XML.getNodeName().................................................................................................................. 82
XML.getNodeType() .................................................................................................................... 83
XML.getNodeValue()................................................................................................................... 84
XML.getParentNode(Element) ....................................................................................................... 86
XML.getPrefix() ........................................................................................................................... 89
XML.getQualifiedName()............................................................................................................. 91
XML.getText() ............................................................................................................................. 93
XML.getValue()........................................................................................................................... 95
XML.importNode(name) .............................................................................................................. 97
XML.isDocumentElement() ............................................................................................................ 99
XML.setAttributeValue(AttributeName, AttributeValue) ................................................................... 100
XML.setContent(String) or XML.setContent("FilePath", IsFile) ........................................................... 103
XML.setNodeValue(String) ......................................................................................................... 104
XML.setText(String).................................................................................................................... 106
XML.setValue(String) ................................................................................................................. 108
XML.toXMLString() .................................................................................................................... 109
JavaScript methods for the XMLDate object ..................................................................................... 110
XMLDate.addDuration(duration) ................................................................................................. 110
XMLDate.getDate().................................................................................................................... 110
XMLDate.getDatum() ................................................................................................................. 110
XMLDate.getGMTSCDateTimeString().......................................................................................... 111
XMLDate.getISODate() .............................................................................................................. 111
XMLDate.getISODateTimeString() ............................................................................................... 111
XMLDate.getISODay() ............................................................................................................... 112
XMLDate.getISOMonth()............................................................................................................ 112
XMLDate.getISOTime() .............................................................................................................. 112
XMLDate.getISOYear() .............................................................................................................. 113
XMLDate.getSCDateTimeString()................................................................................................. 113
XMLDate.JSDate() ..................................................................................................................... 113
XMLDate.toSCDuration(duration) ................................................................................................ 114
Cross-reference: Index of methods and functions by task...................................................................... 115
Array handling ............................................................................................................................ 115
Date/Time handling ..................................................................................................................... 116
Database or file manipulation........................................................................................................ 117
Basic functionality ........................................................................................................................ 117
Conversions ................................................................................................................................ 118
XML............................................................................................................................................ 118
For more information........................................................................................................................ 121
Introduction
System administrators can now use the standard JavaScript scripting language to customize their
Service Manager applications. JavaScript is a widely supported, industry-standard programming
language that eliminates the need for a separate programming skill set, and reduces user reliance on
proprietary tools. The introduction of JavaScript into Service Manager does not invalidate the current
Service Manager RAD tool set; instead, the JavaScript interface is an alternative to the RAD language
for tailoring.
Requirements
This document is targeted for Service Manager system administrators and assumes that the reader is
familiar with object-oriented programming and JavaScript development. It provides an overview of
JavaScript functionality in Service Manager, using both examples and descriptions of JavaScript's
objects, properties, methods, and functions.
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
http://www.mozilla.org/js/spidermonkey/
Language overview
JavaScript is a scripting language which is different from programming languages like Java™, C++ or
Visual Basic®. It is a smaller, dynamically typed scripting language that offers programming tools
with easy syntax and built-in functionality.
Unlike programming languages, scripting languages do not use compilers to create executable
program code. Because JavaScript is an interpreted language, each time the script is executed, it is
loaded into an interpreter that runs the code. The Compile button in the Script Library does not create
an executable load module; it runs a syntax check to verify that the script is executable.
4
JavaScript can be either client-side, server-side, or core language. Core JavaScript is the base
JavaScript language with client-side and server-side JavaScript as extensions. Server-side JavaScript is
used for accessing and manipulating data, and is the only one available within Service Manager.
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
5
The list of operators includes assignment operators, comparison operators, arithmetic operators,
bitwise operators, logical operators, string operators, and special operators.
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
Conditional statements
The following example returns true if the date entered is within the number of days in a month (here,
30 days); otherwise, it returns false.
Note the use of the conditional statement to shorten the "if" expressions. The statement:
var return = (parm.Date.getDate <= 30) ? true : false;
Works in the same way as its much longer equivalent:
var return=false;
if (parm.Date.getDate <= 30)
{
return = true;
}
else
{
return=false;
}
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
6
The following example shows how to check how many times a given number can be divided by 2,
first using a "for" loop, and then using a "while" loop:
function DivisableByTwoFOR(ParmNumber)
{
for (var i=0; ParmNumber > 1; i++)
{
ParmNumber = ParmNumber / 2;
}
return i;
}
fuction DivisableByTwoWHILE(parmNumber)
{
var i = 0;
while( ParmNumber > 1 )
{
ParmNumber = ParmNumber / 2;
i++;
}
return i;
}
Note: A Do..While loop is available for those instances when you want to execute a statement (or
block of statements) at least once. In a Do..While loop the exit condition is checked after the
statements are executed.
7
{
print(parmArray[i].toString + “ is not numeric. Continuing with
next number”;
i++;
continue;
}
n = n + parmArray[i];
i++;
}
return n;
}
try
{
// statements to try
Var MyName=SetFullName(First, Last) // function could throw exception
}
catch (e)
{
MyName="unknown"
logMyErrors(e) // pass exception object to error handler
}
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
8
FormatControl
The JavaScript is executed after calculations and before validations. JavaScript code in
FormatControl is executed via the format.cjavascript RAD.
Links
JavaScript in links is executed after the (initial) expressions, but before the fill or find is executed. This
is done in us.link on evaluate.expressions.
The post JavaScript is executed after the fill or find was performed, immediately after the post
expressions. This happens in us.fill or us.find, respectively, on the eval.post.expressions panel.
Triggers
The JavaScript in the triggers file is executed after the RAD application. This is controlled by the
server binaries, and not by RAD code.
Cascade updates
The JavaScript in cascade updates is executed from the RAD application
process.update.config.record. The evaluate expressions panel is executed before the
evaluate.javascript panel, so that expressions take precedence over JavaScript.
Scripts
In script.execute on panel exec.statements, RAD expressions are processed before JavaScript
expressions.
Wizards
Wizards use JavaScript in 3 different areas: During File Selection, Actions, and Cancel Expressions.
File Selection: The Select $L.file by tab information is processed first, followed by the Initial
Expressions tab and the JavaScript tab.
Actions: In the Actions tab, the Expressions are run first, then the JavaScript, followed by the
information on the Format Control / Process Name tab.
Cancel Expressions: Here first the Expressions Executed on Cancel tab are processed, followed by
Javascript Executed on Cancel tab.
Display screens
In the display application on the panel prep.screen, the JavaScript expressions are executed after the
RAD expressions.
Display options
Display options have pre- and post-JavaScript and RAD expressions that are executed in the following
order:
1. Pre-RAD expression
2. Pre-JavaScript
3. RAD application
4. Post-RAD expression
5. Post-JavaScript
6. Display Action
9
Processes
Process records have initial and final JavaScript and RAD expressions that are executed in the
following order:
1. Initial RAD expression
2. Initial JavaScript
3. Pre-RAD expressions
4. RAD application(s)
5. Post-RAD expressions
6. Final RAD expression
7. Final JavaScript
8. Next Process (if applicable)
Schedule
JavaScript in the schedule record is executed after the RAD application is called, and before the
check for deleting or rescheduling the schedule record.
The ScriptLibrary
The ScriptLibrary is a file within Service Manager used to create, edit, compile, test, and store
scripts and functions that can be called and executed from anywhere within Service Manager.
Some of these stored JavaScript programs can be used to interface with 3rd party Web Services
providers, such as real-time currency conversions. All of these JavaScripts are identified as SOAP
packages within the ScriptLibrary. Integrations are typically performed through JavaScript stored in
the Script Library as well.
Note: Do not use Adminstrative Mode when entering the ScriptLibrary, since functions such as
compile and execute are not available in that mode.
The screen displayed below shows how all these colors appear in the script editor:
10
When working with the ScriptLibrary, you can compile the JavaScript code to check for syntax errors.
Executing the script will compile the code and then run it. For executing the code, ensure that all input
is made available.
You can access any script or function in the ScriptLibrary from any tool within Service Manager that
supports JavaScript, by using the following syntax:
system.library.<scriptname>.<functionname>( parameters )
Within a ScriptLibrary record, you can call any function that is defined previously within the same
record by simply typing:
<functionname>( parameters )
To call JavaScript from any RAD process panel, you can use the jscall RAD function. The syntax for
this function is:
jscall( "script.function" , arg1 , arg2, ... , argN )
The following statements illustrate a JavaScript call to the system library, and a call to the script library
via jscall(), respectively:
system.library.tzfunctions.getTZforOperator(“falcon”);
jscall(tzfunctions.getTZforOperator, “falcon”);
11
Service Manager task RAD panel / expression JavaScript expression
Query operators
These operators are used solely for constructing query expressions using the Query object.
Note: The Query object has been deprecated, but older JavaScript code within the ScriptLibrary still
uses the object.
EQ Equals to
GT Greater than
GE Greater or equal to
LT Lower than
LE Lower or equal to
Example:
var q=new SCFile("probsummary")
q.doSelect(new QueryCond("number", EQ, "IM10002"));
12
Return code Description
RC_CANT_HAVE The operation failed because the resource is unavailable because some
other user or process has the resource locked.
RC_DUPLICATE_KEY The insert operation failed because the file already contains a record
with this unique key value.
RC_MODIFIED The update operation failed because the record was modified by
another user or process since you read it.
RC_DELETED The operation failed because the record was deleted by another user
or process.
RC_VALIDATION_FAILED The operation failed because the data supplied in a field or the record
did not pass validity checks performed by the application.
RC_UNABLE_TO_WRITE_TO_FILE The operation failed. Check to make sure the table name is correct,
that the table exists, and that it is not read-only.
RC_UNABLE_TO_CLOSE_FILE The operation failed. Check to make sure the table name is correct,
that the table exists, and that it is not read-only.
RC_UNABLE_TO_DELETE_FILE The operation failed. Check to make sure the table name is correct,
that the table exists, and that it is not read-only.
RC_INVALID_FILENAME The operation failed because the table name is not valid.
Example
var rc = mySCFile.doInsert();
if ( rc == RC_SUCCESS )
{
print( "Insert succeeded" );
}
Else
throw( "Error " + RCtoString(rc) + " occurred trying to insert a
record" );
FormatControl
The following example can be used to verify whether the operator who was just entered in the
assignee.name field in the incident ticket is currently logged in. Otherwise, validation will fail.
13
In the Calculations section of FormatControl, in the initial column enter a condition of true. Then add
the following in the calculation column:
$assignee.old = nullsub(assignee.name in $file, “no assignee”)
Click the JavaScript tab, enter true for Add and Update, and enter the following statements:
var usersXML = system.users;
var usersString = usersXML.toXMLString();
system.vars.$IsUser=usersString.indexOf(newAssignee);
In the Validation section enter the following, in the Add and Update column:
assignee.name in $file~=$assignee.old;
And the following expression in the Validation column:
$IsUser > 0
Enter the following in the Validation message field:
The new assignee is not logged in at this time. Please try another
assignee.
This example uses the standard indexOf method for the String Object, and the toXMLString() function,
to search for the user who was entered as the new assignee in the XML object containing all logged-in
users.
Any RAD variable can be set and used by preceding it with system.vars. This lets variable values be
exchanged between JavaScript and RAD expressions.
Triggers
In this example a trigger sends a message to the assignment group in an incident ticket that the ticket
has been updated, and to whom it is assigned. Then it adds an activity with the information that the
message has been sent.
var NewRecord=system.vars.$L_new; /* This is the $L.new record passed in
from the trigger */
var incNumber=NewRecord.number;
var incAssignee=NewRecord.assignee_name;
if (incAssignee==null)
{
incAssignee="no one at the moment";
}
/* Insert a message schedule record into the schedule file */
function insertSchedule( incNumber, incAssignee, Adressees)
{
var newSchedule = new SCFile( "schedule" );
var today=new Date();
newSchedule.application= "message.bg";
newSchedule._class = "problem";
newSchedule.name= "message processor record";
newSchedule.expiration= today;
newSchedule.strings[1]="1";
newSchedule.strings[2]="problem update";
newSchedule.strings[3]="Problem " + incNumber + " has been
updated. It is assigned to " + incAssignee + ".";
14
newSchedule.strings[5]="pm.main";
newSchedule.strings[6]=" Soap-Windows XP";
newSchedule.strings1=Adressees;
var rc = newSchedule.doInsert();
}
15
Links
The following JavaScript code:
Queries the configuration item that was previously selected from a fill.
Increases a counter in that configuration item called num.issues.on.CI (this new field has to be
added in the device file).
Adds the new ticket number to an array of issues in the device file called array.incidents.
Updates the device record.
If the configuration item does not exist, it issues an error message.
If the item is currently down, it sends an alert to the person who is opening the ticket.
16
{
j=0;
}
else
{
j=array_incidents.length;
}
array_incidents[j] = incNumber;
CI.array_incidents = array_incidents;
}
CI.doUpdate();
}
/* Call previously defined functions to execute code */
CI=getConfigurationItem(CIName);
increaseUseCounter(CI);
This example shows how to query a record from within Service Manager, and how to update fields in
that record. Additionally it shows how to transfer an array from Service Manager to JavaScript. An
array from Service Manager cannot be directly copied into a JavaScript array, because the syntax of
Service Manager {“IM1001”, “IM1002”} does not work in JavaScript. Properties such as the length
property assume that the value is a function if it is enclosed in curly braces {}. To successfully convert
a Service Manager array into a JavaScript array, you can either use the SCFile.toArray() method, or
create a "while" loop or a "for" loop to move through the elements and do an element-by-element
transfer, as shown above.
Note: In JavaScript it is very important that you handle null values. Functions such as length may not
work on null values.
Programmer’s reference
This section can be used by JavaScript developers as a reference for:
JavaScript global system objects
JavaScript global methods
JavaScript objects
JavaScript methods for the SCFile objects
JavaScript methods for the XML object
JavaScript methods for the XMLDate object
17
system.oldrecord
system.record
system.sysinfo
system.sysobjects
system.threads
system.user
system.users
system.vars
Note: Although some shortcut aliases exist for these global system objects, they should not be used.
Scripts that attempt to use these names as variables may not function as expected. Therefore, you
must type out the entire global System object name, for example, system.user instead of user.
system.files
The system.files JavaScript object is unique to Service Manager. It allows you to call a particular
Service Manager table into memory. Its syntax is:
system.files.<table name>.
There are no arguments and no methods for the system.files object, and the following property is valid
for it:
table name Yes Specifies the table name you want to initialize for processing.
Example
This example sets a variable equal to system.files.contacts and displays the contents of the contacts
table. It requires a valid Service Manager table name (for example, contacts) as sample data:
var f = system.files.contacts;
print( "The value of system.files.contacts is:\n" + f );
system.forms
The system.forms object allows you to call a particular Service Manager form into memory. It is
unique to Service Manager. Its syntax is:
system.forms.form_name.
There are no arguments or methods for this object, and the following property is valid for it:
form_name Yes The name of the form you want to bring into memory.
Example
This example sets a variable equal to system.forms.ScriptLibrary, and displays the contents of the
ScriptLibrary form. It requires a valid Service Manager form name (for example, ScriptLibrary) as
sample data:
var fm = system.forms.ScriptLibrary;
print( "The value of system.forms.ScriptLibrary is:\n" + fm );
18
system.functions
This JavaScript object is unique to Service Manager. The system.functions object allows you to call a
particular Service Manager RAD function from JavaScript. Its syntax is:
RAD function arguments String Yes Contains any arguments required to execute the
RAD function.
Example
This example sets a variable equal to system.functions.date(), and displays the results of the RAD
date() function. It requires a valid Service Manager RAD function name (for example, date()) as
sample data:
fn = system.functions.date();
print( "The value of system.functions.date() is:\n" + fn );
A more complex use of system.functions shows how to insert a logical name value into the first
positition of the group.members array:
joinFile.group_members =
system.functions.insert(joinFile.group_members,0,1,
system.vars.$L_file.logical_name);
system.library
The system.library object allows you to call a particular Service Manager script library function. It is
unique to Service Manager. The syntax for this object is:
function arguments String Yes Contains the function arguments you want to use.
No methods are defined for this object. The following properties are valid for this object:
script name Yes Contains the name of the script you want to run.
function name No Contains the name of the function you want to run.
19
Example
This example calls a script from the Script library. It requires the name of a valid Service Manager
script (for example, SelfService) as sample data:
print( "Running script system.library.SelfService..." )
system.library.SelfService.registerEssUser( BOB, HELPDESK,
BOB.HELPDESK@acme.com, 858-555-1212 );
system.oldrecord
The system.oldrecord JavaScript object allows you to call a copy of the current Service Manager
record before modifications into memory. It is unique to Service Manager. Its syntax is:
system.oldrecord.
Example
The following example sets a variable equal to system.oldrecord, and displays the results of
system.oldrecord.
o = system.oldrecord;
print( "The value of system.record is:\n" + o );
system.record
The system.record JavaScript object allows you to call the current Service Manager record including
the latest modifications into memory. It is unique to Service Manager. The syntax for this object is:
system.record.
Example
This example sets a variable equal to system.record, and displays the results of system.record.
r = system.record;
print( "The value of system.record is:\n" + r );
system.sysinfo
The system.sysinfo JavaScript object allows you to get an XML list of properties about the Service
Manager server and the client settings. It is unique to Service Manager. Its syntax is:
system.sysinfo.
Example
This example sets a variable equal to system.sysinfo, and displays the results of system.sysinfo.
s = system.sysinfo;
print( "The value of system.sysinfo is:\n" + s );
20
<ActiveNamedUsers>1</ActiveNamedUsers>
<ClientNetAddress>127.0.0.1</ClientNetAddress>
<ClientVersion>7.0..010</ClientVersion>
<ClientPID>25</ClientPID>
<Display>gui</Display>
<Environment>scguiwswt</Environment>
<MaxFloatUsers>1</MaxFloatUsers>
<MaxLicenses></MaxLicenses>
<Mode>SOAP</Mode>
<PrevLabel>check.option.1</PrevLabel>
<PrintOption>client</PrintOption>
<Quiesce>0</Quiesce>
<RecList>true</RecList>
<ServerNetAddress>127.0.0.1</ServerNetAddress>
<ServerPID>25</ServerPID>
<SystemEvents></SystemEvents>
<Telephony></Telephony>
<ThreadID>2</ThreadID>
<TotalFloatUsers>25</TotalFloatUsers>
<TotalLicenses></TotalLicenses>
<TotalNamedUsers>25</TotalNamedUsers>
<TotalProcs>19</TotalProcs>
<TotalSystemProcs>18</TotalSystemProcs>
<TotalUserProcs>1</TotalUserProcs>
</sysinfo>
system.threads
The system.threads JavaScript object allows you to call an XML list of the current Service Manager
threads into memory. It is unique to Service Manager.
The syntax is:
system.threads
Example
This example sets a variable equal to system.threads, and displays the results of system.threads.
th = system.threads;
print( "The value of system.threads is:\n" + th );
system.user
The system.user JavaScript object allows you to call an XML list of properties of the currently logged
on Service Manager user. It is unique to Service Manager. The syntax is:
system.user.
Example
This example sets a variable equal to system.user, and displays the results of system.user.
u = system.user;
print( "The value of system.user is:\n" + u );
21
system.users
The system.users JavaScript object allows you to call an XML list of the currently logged on Service
Manager users into memory. It is unique to Service Manager. The syntax of this object is:
system.users.
Example
This example sets a variable equal to system.users, and displays the results of system.users
u = system.users;
print( "The value of system.users is:\n" + u );
system.vars
The system.vars JavaScript object allows you to call a particular Service Manager variable into
memory. It is unique to Service Manager. Its syntax is:
system.vars.variable name
There are no arguments or methods for this object. The following property is valid for this object:
variable name Yes Contains the variable name you want to bring into memory.
Example
This example sets a variable equal to system.vars.$L_file, and displays the contents of the $L_file
variable It requires a valid Service Manager variable name (for example, $L_file) as sample data:
var v = system.vars.$L_file;
print( "The value of system.vars.$L_file is:\n" + v );
print
Both displays the contents of the argument ("string" or StringVariable) in the client Messages view,
and prints it in the Service Manager log file.
The syntax is:
print ("string")
Or
print(StringVariable).
The print method does not return any value and does not have any throws. The following argument is
valid for this function:
22
"string" or output Yes Contains the text string or variable value you want the script to
StringVariable print to the Message View and the sc.log file. Enclose literal
text strings in quotation marks.
Example
var example = "abc123.";
print("The value of example is: " + example);
This example created the following output: "The value of example is: abc123."
readFile
Reads the contents of a local file and returns a string object with the contents of that file. The file can
be in either binary or text format, as specified by the binary argument. The syntax for this method is:
path String Yes Contains the text string or variable value containing the fully qualified
path of the file to be read. Enclose literal text strings in quotation marks.
binary String Yes Determines whether the file format is binary or text. Use the string "b"
or "B" to read a binary file. Use any other value to read a text file.
Example
This example reads the contents of a text file, and then reads the contents of a binary file. It requires
both a text file and a binary file on the local file system as sample data.
var textFile = readFile( "C:\\test.xml", "t" );
print( "The value of textFile is: " + textFile );
writeFile
Writes the contents of the object parameter to a specified path and file, which can be in either binary
or text format. It returns the number of bytes written to the file. The syntax for calling this method is:
path String Yes Contains the text string or variable value containing the fully qualified
path of the file to be written. Enclose literal text strings in quotation
marks.
binary String No Specifies whether the file format is binary or text. Use the string "b" or
"B" to write a binary file. Use any other value to write a text file.
object String Yes Contains the text string or variable value containing the data you want
to write to a file.
Example
This example writes the list of currently logged on users to a file. As sample data it needs the list of
currently logged on users stored in system.users.
23
var userList = system.users;
var filePath;
var isBinary;
var fileObject;
Quit
Stops the processing of JavaScript from the point it is called, and returns the failure return code
specified in the return code argument. All JavaScript code after the Quit() method call is ignored.
The syntax is:
return code Integer Yes Contains the numeric return code you want the method to return.
Example
This example prints a message, quits, and returns a failure return code:
print( "Testing the Quit() method..." );
Quit( -1 );
print( "You won't see this message because the JavaScript has already
quit" );
base64Encode
Converts binary data to a base-64 string format. You can also use this method to encode plain text
data in base-64 format. The method returns a string object with the data in base-64 format. The
syntax for using this global method is:
base64Encode( data ).
data Binary Yes Contains the data you want the script to encode in base-64 format.
Example
This example reads the contents of a binary file, converts the file to a base-64 string format, and prints
the base-64 string. It requires a binary file on the local file system (for example, an image file) as
sample data:
var source = readFile( "C:\\header_left.gif", "b" );
var encode = base64Encode( source );
24
print( "The value of encode is:\n" + encode );
base64Decode
Converts base-64 string data to its original format. Returns a binary or string object containing the
original data. The syntax for this method is:
base64Decode( data ).
data Binary Yes Contains the data you want the script to decode to its original format.
Example
This example does the following:
Reads the contents of a binary file.
Converts the file to a base-64 string format.
Writes the base-64 string data to a local file.
Prints the number of bytes written to the local file system.
Reads the contents of a base-64 string format file.
Converts the data into a binary file.
Writes the binary data to a local file.
Prints the number of bytes written to the local file system.
This example requires a binary file on the local file system (such as an image file) as sample data:
var source = readFile( "C:\\header_left.gif", "b" );
var encode = base64Encode( source );
var encodedFile = writeFile( "C:\\base64EncodedImage.txt", "b",
encode );
xmlstring
Converts a JavaScript string to an XML-formatted string. Does not return a value. The syntax is:
xmlstring (string)
string String No Contains the text string or variable value you want the script to convert
to an XML string.
Example
var xmldoc = new SCFile( system.users );
25
xmlstring( xmldoc );
print( xmldoc );
Output:
<users>
<user>falcon</user>
</users>
doHTTPRequest
Sends an HTTP request to a remote server specified by a URL. This method returns a string containing
an HTTP response or an error message. The syntax for this method is:
doHTTPRequest( HTTP command, URL, Headers, POST body, Connect timeout, Send timeout, Receive
timeout )
URL String Yes Specifies the URL to which the script should send an HTTP request. If the
HTTP request requires SSL then the URL must start with https.
Headers Array Yes Contains a JavaScript array of Service Manager-defined Header objects
or an empty array. See the Header object for more information.
Send timeout Integer No Specifies the send timeout threshold in seconds or milliseconds. Use
positive integers for second thresholds and negative integers for
millisecond thresholds. Use a value of zero for an infinite connection
timeout threshold.
Receive Integer No Specifies the receive timeout threshold in seconds or milliseconds. Use
timeout positive integers for second thresholds and negative integers for
millisecond thresholds. Use a value of zero for an infinite connection
timeout threshold.
Example
This example sends an HTTP request to the Service Manager Web Services API, and writes the
response to a local file. It requires the URL to the Service Manager Web Services API as sample data:
var url = "http://localhost:12670/IncidentManagement.wsdl";
var headers = new Array();
var IMWSDL = doHTTPRequest( "GET", url, headers, null, 10, 10, 10 );
var reply = writeFile( "C:\\IncidentManagement.wsdl", "text", IMWSDL );
doSOAPRequest
Issues a SOAP request to a remote server specified by an URL, and returns the SOAP response in a
string or an error message. The syntax for this method is:
doSOAPRequest( URL, SOAPAction, XML, SOAP user ID, SOAP password, Connect timeout, Send
timeout, Receive timeout, Attachment object )
26
The following arguments are valid for it:
Argument Data type Required Description
URL String Yes Specifies the URL to which the script should send an HTTP request. If
the HTTP request requires SSL, then the URL must start with https.
XML String Yes Contains the XML for an entire SOAP request including the SOAP
envelope. Refer to the Web Service's WSDL to determine the proper
format of the SOAP request.
SOAP user ID String No Contains the user ID to be used for the Basic Authorization HTTP
header.
SOAP String No Contains the password value to be used for the Basic Authorization
password HTTP header.
Send timeout Integer No Specifies the send timeout threshold in seconds or milliseconds. Use
positive integers for second thresholds and negative integers for
millisecond thresholds. Use a value of zero for an infinite connection
timeout threshold.
Receive Integer No Specifies the receive timeout threshold in seconds or milliseconds. Use
timeout positive integers for second thresholds and negative integers for
millisecond thresholds. Use a value of zero for an infinite connection
timeout threshold.
Example
This example sends a SOAP request to a delayed stock quote Web service, and prints the SOAP
response to the screen. It requires the following sample data:
The URL to a Web-based delayed stock quotation service.
The stock symbol for the company.
27
makeSCWebURL
This method creates and returns a string containing a URL query to the Service Manager Web tier. It
does not convert any special characters in the URL (such as spaces or quotation marks) to the
characer code equivalent in URL format. You can use the encodeURL method to convert any special
characters in the URL.
The syntax is
makeSCWebURL( Web tier URL, docEngine, table name, query, hash key seed, action, title )
This argument specifies the Document Engine action you want the
action String No URL query to perform. By default, the URL query performs a search
operation.
Example
This example creates a URL query to the Service Manager Web tier and converts any special
characters in the URL to valid URL format. It requires the following sample data:
The URL to Service Manager Web tier
A valid Service Manager table name (for example, incidents)
A valid Service Manager query against the table (for example, incident.id="SD1001")
webserver = "http://<servername>/sc/index.do";
doceng = "docEngine";
hashkey = "";
action = "";
webtier = makeSCWebURL( webserver,
28
doceng,
table,
query,
hashkey,
action,
title );
print( "Creating URL from information provided..." );
print( "The value of webtier is:\n" + webtier );
print( "Converting special characters in URL to valid URI format..."
);
url = encodeURI( webtier );
print( "The value of url is:\n" + url );
return url;
}
help
Displays a brief description of a Service Manager-defined JavaScript object. Requires the use of the
print() method to see the help text string. Returns a brief text string describing the Service Manager-
defined JavaScript object, or returns null if no help is available. The syntax is:
help( object ).
Example
This example displays the help contents of several Service Manager-defined JavaScript objects
var f = new SCFile();
print( help( f ) );
var x = new XML();
print( help( x ) );
var d = new XMLDate();
print( help( d ) );
RCtoString
Converts a Service Manager global return code value into a localized text string. The syntax is:
return code Integer Yes Contains the Service Manager global return code value that you want to
convert to a localized string.
29
Example
This example searches the contacts table for any contact name you define in the search variable, and
displays the contact record as a text string. It requires the following sample data: A valid contact
name (such as "FALCON, JENNIFER") and an invalid contact name (such as "NOT A, CONTACT").
var contactName;
execute
Validates the syntax of a JavaScript and displays the message "Successful compilation of JavaScript
function or expression" if the JavaScript passes validation; otherwise displays an error message. The
compile() method is an alias of the execute() method. The syntax for this method is:
No throws are defined for it, and the following arguments are valid for it:
script String Yes Contains the name of the script you want to validate.
description String No Use this argument to store any comments you want.
Example
This example creates a variable to store a JavaScript name, and validates the contents of the script. It
requires a valid JavaScript for sample data:
var s = "lib.SCFILEgetTextTest";
excute( s, "Testing execute" );
compile
Validates the syntax of a JavaScript and displays the message "Successful compilation of JavaScript
function or expression" if the JavaScript passes validation; otherwise displays an error message. The
compile() method is an alias of the execute() method. The syntax for this method is
30
compile( script, description ).
No throws are defined for compile(). The following arguments are valid for it:
script String Yes Contains the name of the script you want to validate.
description String No Use this argument to store any comments you want.
Example
This example creates a variable to store a JavaScript name, and validates the contents of the script. It
requires a valid JavaScript for sample data:
var s = "lib.SCFILEgetTextTest";
compile( s, "Testing execute" );
JavaScript objects
Attachment
This object is unique to Service Manager and contains attachment data for use with doSOAPRequest
methods. You can use the readFile global method to add data to the Attachment object. You can use
the push method to add Attachment objects to a JavaScript array.
The constructor is:
new Attachment();
No arguments are passed into the object. The following properties are valid for it:
href String Contains the unique identifier for the attachment in the SOAP request message.
action String Contains the name of action to take with the attachment in Service Manager Web
Services Service Manager API. The following options are available:
name String Contains the name of the attachment, which is typically a file name.
attachmentType String Pertains only to Service Manager attachments, and contains the attachment type as
defined in Service Manager. If present, and if the property has a value of "img," then the
attachment must also have a MIME type of "image/bmp".
Example
var a = new Attachment();
var source = readFile( "C:\\header_left.gif", "b" );
a.value = source;
a.name = "C:\\header_left.gif";
31
print( "The value of a is: " + a );
print( "Setting attachment value to source: " + a.name );
print( "The size of the attachment is: " + a.len + " bytes" );
Header
With no arguments, the Header() constructor, new Header(), creates an empty Header object.
With the HTTP header arguments, the Header() constructor,
creates an Header object containing the provided header types and values. Always enclose header
types and header values in quotation marks.
This JavaScript object is unique to Service Manager. The following arguments are valid for it:
Argument Description
Example
var h = new Header( "Accept-Encoding", "gzip,deflate" );
var hd = new Header();
hd.name = "Content-Type";
hd.value = "text/html";
var headers = new Array();
headers.push( hd );
SCFile
The SCFile JavaScript object is unique to Service Manager. When called with no parameters, the
SCFile() constructor,
new SCFile()
new SCFile(object)
creates an SCFile object containing the specified record, structure, or array. Always enclose table
names and arrays in quotation marks.
This object's methods use the Service Manager-defined global return codes. The following argument
is valid for this object:
object String The table name, record, structure, or array you want to query or update.
No properties are defined for this object. The following methods are valid for it:
Note: Detailed instructions for these methods can be found in the section JavaScript methods for the
SCFile objects.
32
Method Description
Name
doDelete Synonymous with the doRemove method, doDelete simply has a more intuitive name.
doSelect Makes a query. It no longer requires that the first argument be the name of the table if the object is
constructed with the name of the table.
getFirst Moves to the first record if the object represents a result set.
getLast Moves to the last record if the object represents a result set.
getNext Moves to the next record if the object represents a result set.
getPrev Moves to the previous record if the object represents a result set.
isRecord Checks whether an object represents a current table and has a record.
Example
var q = new SCFile("contacts");
if ((q.doSelect('contact.name # "B"')) == RC_SUCCESS)
{
print(q.getText());
}
else
{
print("Return code is: " + q.RCtoString);
}
33
XML
The XML() constructor, new XML(), creates an empty XML object where you can store and manipulate
XML documents.
This object's methods do not use the Service Manager-defined global return codes. The XML
JavaScript object is unique to Service Manager. No properties are defined for the method, and it
accepts no arguments. The following methods are valid for this object.
Note: Detailed instructions for these methods can be found in the section JavaScript methods for the
XML object.
addAttribute Inserts an XML attribute and attribute value into the current element.
getDocumentElement Creates an XML object containing the document element and all child elements from an
XML object or XML string.
getFirstAttribute Returns an XML object representing the first attribute of the current node.
getFirstChildElement Returns an XML object representing the first child node of the current node.
getName Returns a string representing the name of the current element or attribute.
getNextAttribute Returns an XML object representing the next attribute of the current node.
getNextSiblingElement Returns an XML object representing the next node at the same level in the Document
Object Model (DOM) tree as the current node.
getNodeName Returns a string representing the name of the current element or attribute.
getNodeType Evaluates an XML object and returns an integer representing the XML Document Object
Model (DOM) type of the current element or attribute.
getParentNode Returns an XML object representing the parent node of the current node.
getPrefix Returns a string representing the namespace value of the current element or attribute.
getQualifiedName Returns a string representing the name of the current element or attribute including any
namespace value.
isDocumentElement Returns true if the current element is the Document Object Model (DOM) document
element.
34
Method Name Description
Example
/* Instantiate an empty XML object */
var xmlObj = new XML();
/* Use setContent to make the XML object read and parse the XML file
* If the setContent method fails, print an error message */
if ( ! xmlObj.setContent( xmlFile, true ) )
{
print( "setContent failed. Unable to parse xml: " + xmlFile );
}
XMLDate
The XMLDate JavaScript object is unique to Service Manager. It has no arguments, and the
XMLDate() constructor,
new XMLDate()
creates an empty XMLDate object.
When used with a DateObject argument, the XMLDate() constructor,
new XMLDate(DateObject)
converts a JavaScript date object to an XMLDate object.
When used with an ISO8601DateTimeOrDurationString argument, the XMLDate() constructor,
new XMLDate(ISO8601DateTimeOrDurationString)
converts an XML schema date object to an XMLDate object.
When used with a DateTimeDatum argument, the XMLDate() constructor,
new XMLDate(DateTimeDatum)
converts a Service Manager date object to an XMLDate object.
This object's methods use the Service Manager-defined global return codes. The following arguments
are valid for this object:
ISO8601DateTimeOrDurationString XML schema date Passes an XML schema date, time, datetime, or duration
string to the XMLDate constructor.
Note: Some of the JavaScript date object times / days start with 0 instead of 1; or the year starts
with 1900. For example, using the getMonth, getDate and getYear methods, December 31st 2005
would be represented as 11-31-105.
35
Value Integer
Hours 0 through 23
No properties are defined for the XMLDate object. The following methods are valid for it:
Note: Detailed instructions for these methods can be found in the section JavaScript methods for the
XMLDate object.
addDuration(iso8601durationstring) Adds the indicated duration to the contained value in the XMLDate
object.
getGMTSCDateTimeString Returns the Greenwich Mean Time (GMT) date time in Service
Manager format.
Example
/* Instantiate a new SCFile object with records of the cm3r table */
var changeRequest = new SCFile("cm3r");
36
theXMLDate.addDuration('P7D');
var nextWeeksDate = theXMLDate.getDatum();
changeRequest.header.planned_end = nextWeeksDate;
changeRequest.doInsert();
doAction( docEngineAction ).
docEngineAction String Specifies the Document Engine action you want the script to execute on the object. Must
contain a valid Service Manager Document Engine action appropriate for the Service
Manager object.
Example
This example creates a new incident record from variable values, and resolves the incident record. It
requires that the "Use Resolved Status?" option be enabled in the Incident Management Environment
record; and that a valid value (such as "IM11112") populate the number field.
function insertIncident( num, name, cat, desc )
{
print( "Creating new incident record..." );
var newIncident = new SCFile( "probsummary" );
newIncident.number = num;
newIncident.callback_contact = name;
newIncident.category = cat;
newIncident.description = desc;
var rc = newIncident.doInsert();
if ( rc == RC_SUCCESS )
{
print( "Success. Created new record " +
newIncident.getText() );
return newIncident.number;
}
else
{
print( "Could not create record. " + RCtoString( rc ) );
return null;
}
}
37
var f = findIncident.doSelect( "number=\"" + id + "\"" );
if ( f == RC_SUCCESS )
{
print( "Success. Found iteraction record..." );
findIncident.resolution_code = rescode;
findIncident.resolution = res;
var a = findIncident.doAction( action );
print( "The resolve Incident return value is " +
RCtoString( a ) );
print( "The incident record is " + findIncident.getText() );
print( "The value of the status field is: " +
findIncident.problem_status );
return findIncident;
}
else
{
print( "Could not find record. " + RCtoString( f ) );
return null;
}
}
SCFile.doDelete()
This method removes a Service Manager record with any new field values defined in a Service
Manager file object. It requires that you define both a Service Manager file object and new values
for fields. It is a synonym of the doRemove() method.
The method returns RC_SUCCESS if the method successfully removes a record; or returns one of the
error global return code values if the method cannot remove the record.
The syntax for this method is
doDelete()
Example
This example searches the probsummary table for any interaction record you define in the search
variable, and removes the interaction record. It requires as sample data a valid value such as
"IM11111" in the number field.
function removeInteraction( num )
{
print( "Removing interaction record..." );
var interactionRecord = new SCFile( "probsummary" );
var findRecord = interactionRecord.doSelect( "number=\"" + num +
"\"");
print( "The interaction record is " + interactionRecord );
var rc = interactionRecord.doDelete();
38
if ( rc == RC_SUCCESS )
{
print( "Success. Removed record " + interactionRecord.getText() );
return interactionRecord;
}
else
{
print( "Could not remove record. " + RCtoString( rc ) );
return null;
}
}
var numberValue = "IM11111";
removeInteraction( numberValue );
SCFile.doInsert()
This method creates a Service Manager record with any new field values defined in a Service
Manager file object. It requires that you define both a Service Manager file object and new values
for fields. The syntax for this method is
doInsert()
Example
This example searches the probsummary table for any incident record you define in the search
variable, and displays the new incident record as a text string.
This example requires the following sample data:
A valid value for the number field (for example, "IM11111")
A valid value for the callback.contact field (for example, "FALCON, JENNIFER")
A valid value for the category field (for example, "network")
39
var callbackContact = "FALCON, JENNIFER";
var categoryValue = "network";
var insertContact( numberValue, callbackContact, categoryValue,
descriptionValue );
SCFile.doRemove()
This method removes a Service Manager record with any new field values defined in a Service
Manager file object. It requires that you define both a Service Manager file object and new values
for fields. The syntax for this method is
doRemove()
Example
This example searches the probsummary table for an interaction record you define in the search
variable, and removes the interaction record. It requires a valid value such as "IM11111" for the
number field as sample data:
function removeInteraction( num )
{
print( "Removing interaction record..." );
var interactionRecord = new SCFile( "probsummary" );
var findRecord = interactionRecord.doSelect( "number=\"" + num +
"\"");
print( "The interaction record is " + interactionRecord );
var rc = interactionRecord.doRemove();
if ( rc == RC_SUCCESS )
{
print( "Success. Removed record " +
interactionRecord.getText() );
return interactionRecord;
}
else
{
print( "Could not remove record. " + RCtoString( rc ) );
return null;
}
}
SCFile.doSave()
This method adds to or updates the Service Manager database with any new field values defined in a
Service Manager file object. It requires that you define both a Service Manager file object and new
values for fields.
The syntax is
doSave()
40
The method returns RC_SUCCESS if the method successfully updates a record; or returns one of the
error global return code values if the method cannot update the record.
Example
This example does the following:
Searches the contacts table for a contact name you define in the search variable.
Displays the contact record as a text string.
Updates the value of the user.type field.
Saves the Service Manager record.
SCFile.doSelect(“query”)
This method runs a specified query and returns a list of records that match the query's selection
criteria.
The method returns an SCFile object containing the records matching the query, and a global return
code value of RC_SUCCESS; or returns one of the error global return code values if the method
cannot return any records. The SCFile object that is returned after successful query execution has the
following format:
41
table={ ["field value",{"array value_1","array value_2",,.array value_n..} ] }
The syntax is
doSelect( "query" )
query String Specifies the query you want to use to search for Service Manager records. Precede special
characters such as quotation marks with a backslash (\), which acts as an escape character.
Example
This example searches the contacts table for any contact name you define in the search variable and
displays the contact record as a text string.
This example requires the following sample data:
A valid contact name (for example, "FALCON, JENNIFER")
A invalid contact name (for example, "NOT A, CONTACT")
SCFile.doUpdate()
This method updates a Service Manager record with any new field values defined in a Service
Manager file object. This method requires that you define both a Service Manager file object and
new values for fields.
The syntax for this method is
doUpdate()
42
The method returns RC_SUCCESS if the method successfully updates a record; or returns one of the
error global return code values if the method cannot update the record.
Example
This example searches the contacts table for any contact name you define in the search variable, and
displays the contact record as a text string.
This example requires the following sample data:
A valid contact name (for example, "FALCON, JENNIFER")
A valid field value update (for example, set the user.type field to "site")
SCFile.getFirst()
This method returns the first record in a record list stored in a SCFile object. It requires that you use
the other SCFile methods to create a record list.
The syntax for the method is
getFirst()
Example
This example does the following:
Queries the contacts table for any contact name you define in the search variable.
43
Displays the last record in the record list.
Displays the previous record in the record list.
Displays the first contact in the record list.
SCFile.getLast()
This method returns the last record in a record list stored in a SCFile object. It requires the use of the
other SCFile methods to create a record list.
The syntax of this method is getLast(). No arguments are passed. The method returns a SCFile object
containing the last record in a record list, and a global return code value of RC_SUCCESS; or returns
one of the error global return code values if the method cannot find the last record.
Example
This example does the following:
Queries the Contacts table for any contact name you define in the search variable.
Displays the first contact in the record list.
Displays the last record in the record list.
44
print( "Searching for contacts starting with " + query + "..." );
var contactFile = new SCFile( "contacts" );
var findContact = contactFile.doSelect( "contact.name#\""+ query +
"\"" );
if ( findContact == RC_SUCCESS )
{
print( "Success. Found contacts starting with " + query + ". The
first record is:\n" + contactFile );
var findLastRecord = contactFile.getLast();
print( "The last record is:\n" + contactFile );
return contactFile;
}
else
{
print( "Could not find contacts starting with " + query + ". " +
RCtoString( findContact ) );
return null;
}
}
var contactQuery = "H";
findLastContact( contactQuery );
contactQuery = "F";
findLastContact( contactQuery );
SCFile.getNext()
This method returns the next record in a record list stored in a SCFile object. It requires the use of the
other SCFile methods to create a record list. The syntax of this method is
getNext()
Example
This example does the following:
Queries the Contacts table for any contact name you define in the search variable.
Displays the first contact in the record list.
Displays the next record in the record list.
45
var findNextRecord = contactFile.getNext();
print( "The next record is:\n" + contactFile.getText() );
return contactFile;
}
else
{
print( "Could not find contact " + query + ". " + RCtoString(
findContact ) );
return null;
}
}
var contactQuery = "B";
findNextContact( contactQuery );
contactQuery = "F";
findNextContact( contactQuery );
SCFile.getPrev()
This method returns the previous record in a record list stored in an SCFile object. It requires that you
use the other SCFile methods to create a record list. The syntax is getPrev(). No arguments are
passed.
The method returns a SCFile object containing the previous record in a record list and a global return
code value of RC_SUCCESS; or returns one of the error global return code values if the method
cannot find the previous record.
Example
This example does the following:
Queries the contacts table for any contact name you define in the search variable.
Displays the first contact in the record list.
Displays the last record in the record list.
Displays the previous record in the record list.
This example requires a contact query that produces a record list (such as contact names starting with
“H”), and it requires appropriate sample data.
function findPrevContact( query )
{
print( "Searching for contacts starting with " + query + "..." );
var contactFile = new SCFile( "contacts" );
var findContact = contactFile.doSelect( "contact.name#\""+ query +
"\"" );
if ( findContact == RC_SUCCESS )
{
print( "Success. Found contacts starting with " + query + ". The
first record is:\n" + contactFile );
var findLastRecord = contactFile.getLast();
print( "The last record is:\n" + contactFile );
var findPrevRecord = contactFile.getPrev();
print( "The previous record is:\n" + contactFile );
}
else
{
print( "Could not find contacts starting with " + query + ". " +
RCtoString( findContact ) );
return null;
}
}
46
var contactQuery = "H";
findPrevContact( contactQuery );
SCFile.getSize()
This method returns the number of array elements in an array stored in a Service Manager SCFile
object. You can use this method to return the length of Service Manager array fields, which are
always stored as SCFile objects. To query a particular array field in a SCFile object, you can use the
following format:
SCFile_object.array_field_name.getSize()
Replace any periods in the name of array_field_name with underscores. For example, you convert
the Service Manager array field update.action to "update_action" when querying it from JavaScript.
The syntax is:
Datum_object.getSize().
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Attempts to get the size of the returned SCFile object (the result is always zero).
Displays the contents of the action field (the action field contains Service Manager array data).
Displays the size of the action field using the Service Manager getSize() method.
Converts the SCFile object into a JavaScript array using the Service Manager toArray() method.
Displays the size of the new JavaScript array using the core JavaScript length property.
This example requires as sample data a valid incident record number, such as "IM1005".
function findIncidents( query )
{
print( "Searching for incident records starting with " + query + "..."
);
var incidentFile = new SCFile( "probsummary" );
var findIncident = incidentFile.doSelect( "number#\""+ query + "\"" );
if ( findIncident == RC_SUCCESS )
{
print( "Success. Found incident records starting with " + query +
". The first record is:\n" + incidentFile );
var objectSize = incidentFile.getSize();
print( "Running the getSize() method on the returned SCFile object
produces the following result: " + objectSize );
var actionText = incidentFile.action;
print( "The contents of the action field is:\n" + actionText );
var actionSize = incidentFile.action.getSize();
print( "The size of the action field is: " + actionSize );
print( "Converting the SCFile object to a JavaScript array..." );
var incidentArray = incidentFile.toArray();
print( "The new JavaScript array is:\n" + incidentArray );
var arraySize = incidentArray.length;
47
print( "The size of the converted array is: " + arraySize );
return incidentFile;
}
else
{
print( "Could not find incident records starting with " + query +
". " + RCtoString( findIncident ) );
return null;
}
}
SCFile.getText()
This method returns a text string of the current SCFile object. The text string has the following format:
getText()
Example
This example searches the contacts table for any contact name you define in the search variable, and
displays the contact record as a text string. It requires the following sample data:
A valid contact name (for example, "FALCON, JENNIFER")
A invalid contact name (for example, "NOT A, CONTACT")
48
findContactName( contactName );
SCFile.getType()
This method returns the data type of Service Manager SCFile objects such as arrays and structured
arrays. It fails on any scalar fields within file records, such as number, date, string, and Boolean
fields. To determine the type of scalar fields you can use, use the core JavaScript ".type" property.
The syntax for this method is
getType()
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Displays the contents of the incident record object.
Returns the data type of the incident record object using the getType() method.
Displays the contents of the action field object.
Returns the data type of the action field object using the getType() method.
Displays the contents of the category field.
Displays the contents of the category field.
This example requires a valid incident record (such as "IM1001") for sample data:
49
}
SCFile.getXML()
This method returns an XML object representation of the current SCFile object. The XML object has the
following format, which is compatible with the Service Manager Systems Web Services API:
getXML()
Example
This example searches the contacts table for a contact name you define in the search variable, and
displays the contact record as an XML object.
This example requires the following sample data:
A valid contact name (for example, "FALCON, JENNIFER")
A invalid contact name (for example, "NOT A, CONTACT")
SCFile.join()
This method returns as a string the elements of either a Service Manager SCFile array object or a
JavaScript array.
50
Note: This method does not use the Service Manager global return code values.
The syntax is:
join()
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Displays the new incident record as a text string.
Displays the contents of the action field using the join() method.
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" );
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText()
);
print( "Displaying the contents of the action field as an object: "
+ incidentFile.action );
print( "Displaying the contents of the action field with join()
method: " + incidentFile.action.join() );
return incidentFile;
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null;
}
}
SCFile.JSDate(dataType)
This method, which was deprecated as of version 6.1 with the introduction of the SCFile object,
converts Service Manager date/time data into JavaScript date/time objects. The SCFile object now
automatically converts Service Manager date/time data into JavaScript date/time objects.
Alternatively, you can now use the XMLDate object and its methods to convert between date/time
formats.
The syntax is:
JSDate( dataType )
This method does not have any return values. The following argument is valid for this method:
51
Argument Data type Description
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Displays the incident record and the value of the open.time field.
Creates an SCFile object containing the number of milliseconds you want to convert.
Converts the open.time field into an SCFile object. (By default the open.time field data is in the
Service Manager date/time data type.)
Converts the SCFile object into a JavaScript date/time object.
This example requires a valid incident record with a value in the open.time field (for example,
"IM1010") as sample data:
function findIncident( id )
{
print( "Searching for incident: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var f = incidentFile.doSelect( "number=\""+ id + "\"" );
if ( f == RC_SUCCESS )
{
print( "Success. found " + id + " in incident record:\n" +
incidentFile.getText() );
print( "The value of the open.time field is: " +
incidentFile.open_time );
print( "Converting open.time to an SCFile object..." );
var dat = new SCFile( incidentFile.open_time );
print( "The new SCFile object is: " + dat );
print( "Converting the SCFile object to a JSDate..." );
var j = dat.JSDate();
print( "The converted SCFile object is: " + j );
return incidentFile;
}
else
{
print( "Could not find incident record. " + RCtoString( f ) );
return null;
}
}
SCFile.length()
This method returns the number of array elements in an array stored in a Service Manager SCFile
object. You can use this method to return the length of Service Manager array fields, which are
always stored as SCFile objects. To query a particular array field in a SCFile object, you can use the
following format:
SCFile_object.array_field_name.length()
Replace any periods in the name of array_field_name with underscores. For example, convert the
Service Manager array field update.action to update_action when querying it from JavaScript.
52
The syntax for the method is
array_field_name.length()
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Attempts to get the size of the returned SCFile object (the result is always zero).
Displays the contents of the action field (the action field contains Service Manager array data).
Displays the size of the action field using the Service Manager length() method.
Converts the SCFile object into a JavaScript array using the Service Manager toArray() method.
Displays the size of the new JavaScript array using the core JavaScript length property.
53
SCFile.pop()
This method removes the last element from a JavaScript array and returns the element removed as a
string. The syntax for the method is
pop()
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Displays the new incident record as a text string.
Converts the action field into a JavaScript array.
Adds an item to the end of the array and displays the total number of elements in the array.
Removes an item from the end of the array and displays the array item removed
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" )
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText()
);
print( "Converting the action field to a JavaScript array..." );
var a = incidentFile.action.toArray();
print( "The action field array contains the following: " + a );
print( "Pushing new array entry..." );
var addOne = a.push( "First array item" );
print( "The number of items in the array are: " + addOne );
print( "The action field array contains the following: " + a );
print( "Popping new array entry..." );
var removeOne = a.pop();
print( "The array item removed was: " + removeOne );
print( "The action field array contains the following: " + a );
return incidentFile;
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null;
}
}
54
SCFile.push(arrayItem)
This method adds an entry to the end of a JavaScript array and returns the total number of entries in
the array. If you apply this method to a Service Manager array object, then it adds the item but does
not return the number of entries in the array.
Note: This method does not use the Service Manager global return code values.
The syntax is:
push( arrayItem )
arrayItem String Specifies the array item you want to add to a JavaScript array.
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Displays the new incident record as a text string.
Converts the contents of the action field into a JavaScript array.
Adds an item to the end of the JavaScript array and prints the total number of items in the array.
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" );
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText()
);
print( "Converting the action field to a JavaScript array..." );
var a = incidentFile.action.toArray();
print( "The action field array contains the following: " + a );
print( "Pushing new array entry..." );
var addOne = a.push( "First array item" );
print( "The number of items in the array are: " + addOne );
print( "The action field array contains the following: " + a );
print( "Pushing new array entry..." );
var addTwo = a.push( "Second array item" );
print( "The number of items in the array are: " + addTwo );
print( "The action field array contains the following: " + a );
return incidentFile;
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null;
}
}
var incidentID = "IM1010";
55
findIncident( incidentID );
SCFile.setValue(newValue)
This method adds or updates a Service Manager record with a specified new field value.
Note: This method does not use the Service Manager global return codes and does not return any
value.
The syntax is setValue( newValue ). The following argument is valid for this method:
newValue String Specifies the new value for the Service Manager object. Precede special characters
such as quotation marks with a backslash (\), which acts as an escape character..
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Displays the current value of the action field.
Sets the value of the action field to any value you define in the input variable.
SCFile.shift()
This method removes the first element from a JavaScript array and returns the removed element as a
string.
56
Note: This method does not use the Service Manager global return code values.
The syntax is:
shift()
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Displays the new incident record as a text string.
Converts the action field into a JavaScript array.
Adds an item to the end of the array and displays the total number of elements in the array.
Removes an item from the beginning of the array and displays the array item removed.
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" );
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText()
);
print( "Converting the action field to a JavaScript array..." );
var a = incidentFile.action.toArray();
print( "The action field array contains the following: " + a );
print( "Pushing new array entry..." );
var addOne = a.push( "First array item" );
print( "The number of items in the array are: " + addOne );
print( "The action field array contains the following: " + a );
print( "Shifting array one entry..." );
var removeOne = a.shift();
print( "The array item removed was: " + removeOne );
print( "The action field array contains the following: " + a );
return incidentFile;
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null;
}
}
SCFile.toArray()
This method converts a Service Manager Datum object into a JavaScript array.
57
The syntax for this method is:
toArray()
Example
This example does the following:
Searches the probsummary table for any Incident record you define in the search variable.
Displays the Incident record as a text string.
Converts the contents of the action field into a JavaScript array.
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" );
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText()
);
print( "Converting the action field to a JavaScript array..." );
var a = incidentFile.action.toArray();
print( "The action field contains the following " + a );
return incidentFile;
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null;
}
}
SCFile.unshift(arrayItem)
This method adds an entry to the beginning of a JavaScript array and returns the total number of
entries in the array. If you apply this method to a Service Manager array object, then it adds the item
but does not return the number of entries in the array.
Note: This method does not use the Service Manager global return code values.
The syntax for this method is
unshift( arrayItem )
58
arrayItem String Specifies the array item you want to add to a JavaScript array.
Example
This example does the following:
Searches the probsummary table for any incident record you define in the search variable.
Displays the new incident record as a text string.
Converts the contents of the action field into a JavaScript array.
Adds an item to the beginning of the JavaScript array and prints the total number of items in the
array.
function findIncident( id )
{
print( "Searching for Incident record: " + id + "..." );
var incidentFile = new SCFile( "probsummary" );
var rc = incidentFile.doSelect( "number=\"" + id + "\"" )
if ( rc == RC_SUCCESS )
{
print( "Success. found Incident record:\n" + incidentFile.getText()
);
print( "Converting the action field to a JavaScript array..." );
var a = incidentFile.action.toArray();
print( "The action field array contains the following: " + a );
print( "Unshifting array one entry..." );
var unshifting = a.unshift( "First array item" );
print( "The number of items in the array are: " + unshifting );
print( "The action field array contains the following: " + a );
return incidentFile;
}
else
{
print( "Could not find Incident record. " + RCtoString( rc ) );
return null;
}
}
59
Argument Data type Description
AttributeName String Specifies the text string you want the script to use as the XML attribute name. Must contain
characters valid for an XML element (for example, the string cannot include the characters
< or >).
AttributeValue String Specifies the text string you want the script to use as the XML attribute value. Must contain
characters valid for an XML element (for example, the string cannot include the characters
< or >).
Example
This example adds a new attribute and an attribute value to an element you select from an XML
document.
This example requires a local XML file, such as a file called C:\test02.xml containing the
following sample data:
"<document><parent1>value1</parent1><parent2></parent2></document>"
/* Create variables to store XML objects and strings.
* The script assigns values to these variables later on:
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString. */
60
/* Create a function to print the target element and search results */
XML.addElement(String)
This method inserts an XML element as a child of the current element. It returns an XML object
containing the new XML element; or returns null if the method cannot add the element. Use the
XML.getxxx methods to navigate through an XML document.
The syntax for this method is:
addElement( String )
String String Specifies the text string you want the script to use as the XML element name. Must contain
characters valid for an XML element (for example, the string cannot include the characters < or
>).
Example
This example adds a child element to any element you select in an XML document. It requires a local
XML file, such as a file called C:\test02.xml containing the following sample data:
"<document><parent1>value1</parent1><parent2></parent2></document>"
/* Create variables to store XML objects and strings.
61
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString.
* The script assigns values to the empty variables later on */
62
return searchResult;
}
else
{
print( "Cannot find " + target );
return null;
}
}
XML.appendNode(name)
This method inserts an XML node into an XML object. It returns an XML object containing the new
XML node; or returns null if the method cannot append the node to the current target node. This
method requires an existing XML object with a document element, but it does not update the existing
XML object.
The syntax is
appendNode( name )
name String Specifies the XML node name you want to append to the target XML object. Must
contain characters valid for XML (for example, the string cannot include the characters
< or > except as XML entities such as < and >).
Example
This example appends an XML node to an XML source object. It requires an XML object containing
sample data such as: "<document> </document>"
function findTargetElement( node, targetElem )
{
while (node != null && node.getNodeName() != targetElem )
{
var childNode = node.getFirstChildElement();
if (childNode == null)
{
childNode = node.getNextSiblingElement();
while (childNode == null)
{
node = node.getParentNode();
if ( node == null )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
63
{
node = childNode;
}
}
return node;
}
type Integer Specifies the XML DOM node type for the node you want the script to create. This method
accepts only XML DOM types 1, 2, and 3. See the W3C Web site for a complete listing of
XML DOM node-types by integer.
name String Specifies the text string you want the script to add as the XML node name. Must contain
characters valid for XML (for example, the string cannot include the characters < or > except as
XML entities such as < and >).
value String Specifies the text string you want the script to add as the XML node value. Must contain
characters valid for XML (for example, the string cannot include the characters < or > except as
XML entities such as < and >).
Example
This example creates an XML node from an XML source object. It requires as sample data an XML
object, such as an object containing: "<document> </document>"
var XMLObject = new XML();
var NewNodeName;
var NewNodeValue;
var NewNodeType;
64
XMLObject = XMLObject.setContent( "<document> </document>" );
NewNodeType = 1;
NewNodeName = "node";
NewNodeValue = "test";
createNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject );
NewNodeType = 2;
NewNodeName = "id";
NewNodeValue = "test";
createNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject );
NewNodeType = 3;
NewNodeName = null;
NewNodeValue = "Text node";
createNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject );
XML.getAttributeNode(Attribute)
This method returns an XML object containing the target attribute the current element; or returns null if
the method cannot find the target attribute in the current element. Use the other XML.getxxx methods
to navigate through an XML document.
The syntax is:
getAttributeNode( Attribute )
Attribute String Specifies the XML attribute you want the script to return.
Example
This example searches for a particular attribute of any given element in an XML document. It requires
a local XML file, such as a file called C:\test.xml containing the following sample data:
65
function findTargetElement( node, targetElem )
{
while (node != null && node.getNodeName() != targetElem )
{
var childNode = node.getFirstChildElement();
if (childNode == null)
{
childNode = node.getNextSiblingElement();
while (childNode == null)
{
node = node.getParentNode();
if ( node == null )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
66
return null;
}
}
/* Run functions */
XML.getAttributeValue(Attribute)
This method returns the string value of the target attribute; or returns null if the method cannot find an
attribute value. Use the other XML.getxxx methods to navigate through an XML document.
The syntax is:
getAttributeValue( Attribute )
Attribute String Specifies the XML attribute whose value you want the method to return.
Example
This example searches for the attribute value of any given element in an XML document. It requires as
sample data a local XML file, such as a file called C:\test.xml containing:
67
while (node != null && node.getNodeName() != targetElem )
{
var childNode = node.getFirstChildElement();
if (childNode == null)
{
childNode = node.getNextSiblingElement();
while (childNode == null)
{
node = node.getParentNode();
if ( node == null )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
68
/* Set variable values for XMLFile and TargetNode. Run functions */
print( "Processing XML from XMLFile... \n" );
TargetNode = "child1";
XMLSource = XMLFile;
TargetAttribute = "attribute1";
searchResults = findTargetElement( XMLSource, TargetNode );
printFindResults( TargetNode, searchResults, TargetAttribute );
XML.getDocumentElement()
This method searches an XML object for the DOM document element (or "root" node). If successful, it
returns an XML object containing the document element and all of its child elements. It returns null if
applied to an empty or invalid XML object.
Important: You cannot use this method on objects that you have converted using the toXMLString()
method.
The syntax is
getDocumentElement()
Example
This example displays the XML document element from four different input sources. It requires the
following sample data:
A valid XML object, such as the list of currently logged on users stored in system.users
A valid XML string, such as:
"<document1><parent1/></document1><document2><parent2/></document2>"
An empty XML object
69
/* Create a function to execute the getDocumentElement method on the
document argument. */
XML.getFirstAttribute(Element)
The method returns an object representing the first attribute of the current node or returns null if the
XML object has no attributes.
The syntax is getFirstAttribute(); or getFirstAttribute(Element). The following argument is valid for this
method:
Element String Contains the name of the element you want the method to use as the starting position
when searching for the first attribute.
Example
This example displays the first attribute of any element you select. It allows you to select an element
from two different input sources. It requires the following sample data:
A local XML file, such as a file called C:\test.xml containing the following sample data:
70
"<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1>
<parent2 /></document>"
* This function assumes that there is only one instance of the target
* element in the source data. If it finds more than one element in
* the data it only returns the first instance of the element. */
71
"\n" );
return searchResult;
}
else
{
print( "Cannot find " + target );
return null;
}
}
72
XML.getFirstChildElement(Element)
The method returns an object representing the first child node of the current node; or returns null if the
XML object has no child node.
The syntax is:
getFirstChildElement()
Or
getFirstChildElement(Element).
The following argument is valid for this method:
Element String Contains the name of the element you want the method to use as the starting position when
searching for the first child element.
Example
This example displays the first child element of any element you select. It allows you to select an
element from two different input sources. It requires the following sample data:
A local XML file, such as a file called C:\test.xml containing the following sample data:
73
while (node != null && node.getNodeName() != targetElem )
{
var childNode = node.getFirstChildElement();
if (childNode == null)
{
childNode = node.getNextSiblingElement();
while (childNode == null)
{
node = node.getParentNode();
if ( node == null )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
/* Create a function to print the target element and search results */
74
function printChildResults( target, searchResult )
{
if ( searchResult != null )
{
var childName = searchResult.getNodeName();
print( "The first child element of " + target + " is: " + childName
);
}
else
{
print( "There are no child elements of " + target );
}
}
/* Set variable values for XMLFile and TargetNode. Run functions */
XML.getName()
The method, which is a synonym for getNodeName(), returns a string representing the name of the
current element or attribute; or returns null if the current node has no name. Use the other XML.getxxx
methods to navigate through an XML document.
The syntax is:
getName()
Example
This example displays the names of the elements and attributes in an XML document. It requires the
following sample data:
A local XML file, such as a file called C:\test.xml containing the following sample data:
"<document><parent1><child1>0123</child1></parent1></document>"
75
/* Create variables to store XML objects and strings.
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString.
* The script assigns values to the empty variables later on */
XML.getNextAttribute(Element)
The method returns an object representing the first attribute of the current node; or returns null if the
XML object has no attributes.
The syntax is either getNextAttribute() without arguments, or getNextAttribute(Element). The following
argument is valid for this method:
Element String Contains the name of the element you want the method to use as the starting position when
searching for the first attribute.
76
Example
This example displays the first attribute of any element you select. It allows you to select an element
from two different input sources. It requires the following sample data:
A local XML file, such as a file called C:\test.xml containing the following sample data:
"<document><parent1><child1 />
<child2 attribute2=\"b\" attribute3=\"c\" /></parent1><parent2 /></document>"
77
}
return node;
}
78
while ( nextAttribute != null )
{
var attributeName = nextAttribute.getNodeName();
print( "The next attribute of " + targetNode + " is: " +
attributeName );
nextAttribute = nextAttribute.getNextAttribute();
}
print( "There are no more attributes of " + targetNode );
return targetNode;
}
else
{
return null;
}
}
XML.getNextSiblingElement(Element)
The method returns an object representing the next node at the same level in the Document Object
Model (DOM) tree as the current node; or returns null if the XML object has no sibling node.
The syntax is either:
getNextSiblingElement()
Or
getNextSiblingElement(Element).
Element String Contains the name of the element you want the method to use as the starting position
when searching for the next sibling element.
79
Example
This example displays the next sibling element of any element you select. It allows you to select an
element from two different input sources. It requires the following sample data:
A local XML file, such as a file called C:\test.xml containing the following sample data:
80
}
return node;
}
/* Create a function to print the target element and search results */
81
printFindResults( TargetNode, searchResults );
siblingResults = findNextSibling( XMLSource, TargetNode );
printSiblingResults( TargetNode, siblingResults );
XML.getNodeName()
This method returns a string representing the name of the current element or attribute; or returns null if
the current node has no name. Use the other XML getxxx methods to navigate through an XML
document.
The syntax is:
getNodeName()
Example
This example displays the names of the elements and attributes in an XML document. It requires the
following sample data:
A local XML file, such as a file called C:\test.xml containing the following sample data:
"<document><parent1><child1>0123</child1></parent1></document>"
82
while( node != null )
{
var attrName = node.getNodeName();
var attrValue = node.getNodeValue();
print( "Attribute " + attrName + " = " + attrValue );
node = elem.getNextAttribute();
}
var nodeValue = elem.getNodeValue();
if ( typeof nodeValue == "string" && nodeValue.length > 0 )
{
print( "Element value of " + elem.getNodeName() + " is: " +
nodeValue );
}
XML.getNodeType()
This method evaluates an XML object and returns an integer representing the XML Document Object
Model (DOM) type of the current element or attribute; or returns null if the method cannot determine
the XML DOM type. (See the W3C Web site (http://www.w3c.org) for a complete listing of XML
DOM node types by integer.) This method returns a type error if applied to anything other than an
XML object. This limits this method to elements and attributes because the Service Manager XML
object cannot represent element values as an XML object. Use the other XML.getxxx methods to
navigate through an XML document.
The syntax is
getNodeType()
Example
This example displays the XML DOM types of the elements and attributes in an XML document. It
requires a local XML file, such as a file called C:\test.xml containing the following sample data:
83
/* Print attributes for this element */
var node = elem.getFirstAttribute();
while( node != null )
{
var attrName = node.getQualifiedName();
var attrValue = node.getNodeValue();
print( "Attribute " + attrName + "=" + attrValue + " and is of type
" + node.getNodeType() );
node = elem.getNextAttribute();
}
/* Print possible element value */
var nodeValue = elem.getNodeValue();
if ( typeof nodeValue == "string" && nodeValue.length > 0 )
{
print( "Element value is " + nodeValue + " and is of type " +
elem.getNodeType() );
}
/* Now print child elements */
var child = elem.getFirstChildElement();
while( child != null )
{
var nodeName = child.getNodeName();
var nodeValue = child.getNodeValue();
visitElement( child );
child = child.getNextSiblingElement();
}
}
var xmlObj = new XML();
xmlObj.setContent( "c:\\test.xml", true );
visitElement( xmlObj.getDocumentElement() );
XML.getNodeValue()
The method returns a string representing the value of the current XML element; or returns null if the
current node has no value. This method requires you use the other XML get methods to navigate
through an XML document.
The syntax is:
getNodeValue()
Example
This example displays the value of the elements in an XML document. It requires a local XML file,
such as a file called C:\test02.xml containing the following sample data:
"<document><parent1>value1</parent1><parent2></parent2></document>"
/* Create variables to store XML objects and strings.
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString.
* The script assigns values to the empty variables later on */
84
/* Create a function that searches an XML object (node) for a
* particular element (targetElem) and returns an XML object
* containing the element.
* This function assumes that there is only one instance of the target
* element in the source data. If it finds more than one element in
* the data, it returns only the first instance of the element. */
85
{
print( "The value of " + targetNode + " is: " + valueFound );
return valueFound;
}
else
{
print( "There is no value for " + targetNode );
valueFound = null;
return valueFound;
}
}
XML.getParentNode(Element)
This method returns an XML object representing the parent node of the current node; or returns null if
the XML object has no parent node.
The syntax is:
getParentNode()
Or
getParentNode(Element)
Node String Contains the name of the element you want the method to use as the starting position
when searching for the parent node element.
Example
This example displays the parent node element of any element you select. The example allows you to
select an element from two different input sources. It requires the following sample data:
A local XML file, such as a file called C:\test.xml containing the following sample data:
86
"<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1>
<parent2 /></document>"
87
print( "Found element " + elementName + " in: \n" + searchResult +
"\n" );
return searchResult;
}
else
{
print( "Cannot find " + target );
return null;
}
}
88
TargetNode = "child1";
XMLSource = XMLString;
print( "The target element we are looking for is: " + TargetNode );
searchResults = findTargetElement( XMLSource, TargetNode );
printFindResults( TargetNode, searchResults );
parentResults = findParent( XMLSource, TargetNode );
printParentResults( TargetNode, parentResults );
XML.getPrefix()
This method returns a string representing the namespace value of the current node (element or
attribute); or returns null if the current node has no namespace value.. Use the other XML.getxxx
methods to navigate through an XML document.
The syntax is:
getPrefix()
Example
This example displays the namespace value of the elements and attributes in an XML document. It
requires a local XML file, such as a file called C:\namespace.xml containing the following sample
data:
89
{
node = node.getParentNode();
if ( node == null )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
/* Create a function to print the target element and search results */
90
if ( firstAttribute != null )
{
var attributeName = firstAttribute.getNodeName();
print( "The first attribute of " + targetNode + " is: " +
attributeName );
findPrefix( firstAttribute, targetNode );
return firstAttribute;
}
else
{
print( "There are no attributes of " + targetNode );
return null;
}
}
XML.getQualifiedName()
This method, which is a synonym for getNodeName(), returns a string representing the name of the
current element or attribute; or returns null if the current node has no name. Use the other XML.getxxx
methods to navigate through an XML document.
91
The syntax for this method is:
getQualifiedName()
Example
This example displays the names of the elements and attributes in an XML document. It requires a
local XML file, such as a file called C:\namespace.xml containing the following sample data:
92
print( "Attribute " + attrName + " = " + attrValue );
node = elem.getNextAttribute();
}
var nodeValue = elem.getNodeValue();
if ( typeof nodeValue == "string" && nodeValue.length > 0 )
{
print( "Element value of " + elem.getName() + " is: " + nodeValue
);
}
XML.getText()
This method, which is a synonym for getNodeValue(), returns a string representing the value of the
current XML element; or returns null if the current node has no value. Use the other XML.getxxx
methods to navigate through an XML document.
The syntax is:
getText()
Example
This example displays the value of the elements in an XML document. It requires a local XML file,
such as a file called "C:\test02.xml" containing the following sample data:
"<document><parent1>value1</parent1><parent2></parent2></document>"
/* Create variables to store XML objects and strings.
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString.
* The script assigns values to the empty variables later on */
93
/* Create a function that searches an XML object (node) for a
* particular element (targetElem) and returns an XML object
* containing the element.
* This function assumes that there is only one instance of the target
* element in the source data. If it finds more than one element in
* the data, it returns only the first instance of the element. */
94
return valueFound;
}
else
{
print( "There is no value for " + targetNode );
valueFound = null;
return valueFound;
}
}
XML.getValue()
This method, which is a synonym for getNodeValue(), returns a string representing the value of the
current XML element; or returns null if the current node has no value. Use the other XML.getxxx
methods to navigate through an XML document.
The syntax is:
getValue()
Example
This example displays the value of the elements in an XML document. It requires a local XML file,
such as a file called "C:\test02.xml" containing the following as sample data:
"<document><parent1>value1</parent1><parent2></parent2></document>"
/* Create variables to store XML objects and strings.
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString.
* The script assigns values to the empty variables later on */
95
function findTargetElement( node, targetElem )
{
while (node != null && node.getNodeName() != targetElem )
{
var childNode = node.getFirstChildElement();
if (childNode == null)
{
childNode = node.getNextSiblingElement();
while (childNode == null)
{
node = node.getParentNode();
if ( node == null )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
96
return valueFound;
}
}
XML.importNode(name)
This method returns an XML object containing a copy of the source XML node; or returns null if the
method cannot import a copy of the node. It requires two existing XML objects with document
elements: one is the source XML object and the other is the target XML document. This method does
not update either the source or the target XML object. Instead, you use the appendNode method to
add the imported node into the target XML document.
The syntax is:
importNode( name )
name String Specifies the XML node name you want to copy from the source XML object. Must contain
characters valid for XML (for example, the string cannot include the characters < or > except as
XML entities such as < and >).
Example
This example imports an XML node from one XML object to another. It requires the following sample
data:
A local XML file, such as a file called "C:\test.xml" containing:
"<document> </document>"
97
if (childNode == null)
{
childNode = node.getNextSiblingElement();
while (childNode == null)
{
node = node.getParentNode();
if ( node == null )
{
return null;
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
98
XML.isDocumentElement()
This method returns true if the current element is the Document Object Model (DOM) document
element (the "root" node of the XML document); and returns false if it is not. Use the XML.getxxx
methods to navigate through an XML document.
The syntax is:
isDocumentElement()
Example
This example checks whether the selected element is the DOM document element. It requires a local
XML file, such as a file called C:\test02.xml containing:
"<document><parent1>value1</parent1><parent2></parent2></document>"
/* Create variables to store XML objects and strings.
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString.
* The script assigns values to the empty variables later on */
99
return node;
}
XML.setAttributeValue(AttributeName, AttributeValue)
This method adds or updates the attribute value of the target attribute. Use the XML.getxxx methods
to navigate through an XML document. This method does not return any values.
100
The syntax is:
AttributeName String The XML attribute whose value you want the script to add or update.
AttributeValue String Specifies the text string you want the script to use as the XML attribute value. Must contain
characters valid for an XML element (for example, the string cannot include the characters
< or >).
Example
This example adds or updates the attribute value of any given element in an XML document. It
requires a local XML file, such as a file called C:\test.xml containing the following sample data:
101
node = childNode;
}
}
return node;
}
/* Create a function to print the target element and search results */
function printFindResults( target, searchResult, attributeName,
attributeValue )
{
print( "The target element we are looking for is: " + target );
if ( searchResult != null )
{
var elementName = searchResult.getNodeName();
print( "Found element " + elementName + " in: \n" + searchResult +
"\n" );
var attributeSet = setAttributeValue( searchResult, attributeName,
attributeValue );
print( "The XML object is " + searchResult );
return attributeSet;
}
else
{
print( "Cannot find " + target );
return null;
}
}
102
XML.setContent(String) or XML.setContent("FilePath", IsFile)
This method creates an XML object, either from a string or the contents of an external file object, if it
was able to successfully parse the XML input. It always creates a valid XML document with a
document element, and removes any values outside the document element.
This method returns null if applied to an existing XML object because the header information ([C++
object XML] @nnnnnnnnnn - ) is not valid XML. Use the toXMLString method to convert an XML object
to an XML string.
The syntax is:
setContent( String )
Or
String String Specifies the text string you want the script to parse as on XML object. Must contain a valid
XML document with a document element.
FilePath String Specifies the path to the XML document you want the script to parse an XML object. To indicate
that the String argument is a file path and not a string value, enclose the FilePath argument in
quotation marks, and set the IsFile argument to true.
IsFile Boolean Specifies whether the String argument is a string or a file path. A true value indicates the String
argument is a file path. Any other value, including omitting the second argument, indicates that
the String argument is a text string.
Example
This example attempts to create an XML object from five different sources. It requires the following
sample data:
A valid XML string, such as:
103
function setXML( source, isFile )
{
var xmlObj = new XML();
/* Note: You can omit the isFile argument when the content source is
* an XML string.
* See the xmlString example below. */
print( "Testing setting content to a valid XML string...\n" );
setXML( xmlString );
print( "Testing setting content to an XML string with more than one
document element...\n" );
print( "The non-compliant XML string before conversion is: \n" + xmlBad
);
setXML( xmlBad );
print( "Testing setting content to an XML file...\n" );
setXML( xmlFile, true );
print( "Testing setting content to an existing XML object...\n" );
setXML( xmlObject, false );
print( "Testing setting content to an existing XML object converted to an
XML string...\n" );
setXML( xmlObjectConverted, false );
XML.setNodeValue(String)
This method is used to add or update the value of the current element. It returns an XML object
containing the new value of the current element; or returns null if the method cannot set a value for the
element. Use the XML.getxxx methods to navigate through an XML document.
104
The syntax is:
setNodeValue( String )
String String Specifies the text string you want the script to add as the XML element value. Must contain
characters valid for XML (for example, the string cannot include the characters < or > except as
XML entities such as < and >).
Example
This example sets the value of the elements in an XML document. It requires a local XML file, such as
C:\test03.xml containing:
"<document><parent1></parent1><parent2></parent2></document>"
/* Create variables to store XML objects and strings.
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString.
* The script assigns values to the empty variables later on */
105
}
return node;
}
TargetNode = "parent1";
TargetValue = "1234";
findElement = findTargetElement( XMLFile, TargetNode );
setElementValue( findElement, TargetNode, TargetValue );
XML.setText(String)
This method, which is a synonym for setNodeValue(), is used to add or update the value of the current
element. It returns an XML object containing the new value of the current element; or returns null if the
method cannot set a value for the element. Use the XML.getxxx methods to navigate through an XML
document.
The syntax is:
setText( String )
String String Specifies the text string you want the method to add as the XML element value. Must
contain characters valid for XML (for example, the string cannot include the characters
< or > except as XML entities such as < and >).
Example
This example sets the value of the elements in an XML document. It requires a local XML file, such as
C:\test03.xml containing
"<document><parent1></parent1><parent2></parent2></document>"
/* Create variables to store XML objects and strings.
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString.
* The script assigns values to the empty variables later on */
106
XMLFile = XMLFile.setContent( "C:\\test03.xml", true );
var TargetNode;
var TargetValue;
var findElement;
TargetNode = "parent1";
TargetValue = "1234";
107
findElement = findTargetElement( XMLFile, TargetNode );
setElementValue( findElement, TargetNode, TargetValue );
XML.setValue(String)
This method, which is a synonym for setNodeValue(), is used to add or update the value of the current
element. It returns an XML object containing the new value of the current element; or returns null if the
method cannot set a value for the element. Use the XML.getxxx methods to navigate through an XML
document.
The syntax is:
setValue( String )
String String Specifies the text string you want the method to add as the XML element value. Must
contain characters valid for XML (for example, the string cannot include the characters
< or > except as XML entities such as < and >).
Example
This example sets the value of the elements in an XML document. It requires as sample data a local
XML file, such as a file called C:\test03.xml containing:
"<document><parent1></parent1><parent2></parent2></document>"
/* Create variables to store XML objects and strings.
* Use XMLObject to store a valid XML object such as an XML file.
* Use sourceXMLString to store a valid XML string.
* The script sets the content of XMLString to sourceXMLString.
* The script assigns values to the empty variables later on */
108
}
childNode = node.getNextSiblingElement();
}
node = childNode;
}
else
{
node = childNode;
}
}
return node;
}
/* Create a function to print the target element and search results */
function setElementValue( searchResult, targetNode, newValue )
{
print( "The target element we are looking for is: " + targetNode );
if ( searchResult != null )
{
var elementName = searchResult.getNodeName();
print( "Found element " + elementName + " in: \n" + searchResult +
"\n" );
searchResult.setValue( newValue );
print( "The new value of " + targetNode + " is: " + searchResult );
return searchResult;
}
else
{
print( "Cannot find " + targetNode );
return null;
}
}
TargetNode = "parent1";
TargetValue = "1234";
findElement = findTargetElement( XMLFile, TargetNode );
setElementValue( findElement, TargetNode, TargetValue );
XML.toXMLString()
This method converts an XML object into a valid XML string; or returns null if the current node is not an
XML object. Use the XML.getxxx methods to navigate through an XML document.
The syntax for use is:
toXMLString()
Example
This example converts an XML object into a valid XML document. It requires as sample data an
existing XML object, such as the list of currently logged on users stored in system.users.
var xmlObject = system.users;
print( "This is the original XML object:\n" + xmlObject );
var xmlString = xmlObject.toXMLString();
print( "This is the XML object after conversion to a string:\n" +
xmlString );
109
JavaScript methods for the XMLDate object
XMLDate.addDuration(duration)
This method returns an XMLDate object containing the new date/time after adding the duration from
the duration argument; or returns null if the conversion fails.
The syntax is:
addDuration( duration )
duration ISO 8601 duration Yes Contains the ISO 8601 duration string or variable value you want the
string script to add to an XMLDate object.
Example
This example creates a new XMLDate object containing today's date; adds 1 year, 2 months, 3 days,
and 4 hours to the XMLDate object; and then displays the result
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Adding 1 year, 2 months, 3 days, and 4 hours to date..." );
var dur = d.addDuration( "P1Y2M3DT4H" );
print( "The value of the new XMLDate object is: " + dur );
XMLDate.getDate()
This method returns a JavaScript date/time object as a string; or null if the conversion fails. The
syntax is:
getDate()
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
JavaScript date/time object; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Converting the XMLDate to a JavaScript object..." );
var js = d.getDate();
print( "The JavaScript date/time object is: " + js );
XMLDate.getDatum()
The method returns a Service Manager-formatted date/time Datum object in a string; or returns null if
the conversion fails.
The syntax is:
getDatum()
110
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
Service Manager-formatted date/time Datum object; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Converting the XMLDate to a Service Manager Datum..." );
var sm = d.getDatum();
print( "The Service Manager Datum object is: " + sm );
XMLDate.getGMTSCDateTimeString()
The method returns a Service Manager-formatted date/time string; or returns null if the conversion
fails. The syntax is:
getSCDateTimeString()
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
Service Manager-formatted date/time string; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print("Converting the XMLDate to a Service Manager date/time string...");
var sm = d.getGMTSCDateTimeString();
print( "The Service Manager GMT date/time string is: " + sm );
XMLDate.getISODate()
The getISODate() method returns a string containing the date portion of a date/time object in ISO
format; or returns null if the conversion fails. The syntax is:
getISODate()
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
an ISO date; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Converting the XMLDate to ISO format..." );
var ISO = d.getISODate();
print( "The ISO date is: " + ISO );
XMLDate.getISODateTimeString()
This method returns a string containing the date and time portion of date/time object in ISO format;
or returns null if the conversion fails. The syntax is:
getISODateTimeString()
111
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
an ISO date and time; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Converting the XMLDate to ISO format..." );
var ISO = d.getISODateTimeString();
print( "The ISO date and time is: " + ISO );
XMLDate.getISODay()
This method returns a string containing the day portion of date/time object in ISO format; or returns
null if the conversion fails. The syntax is:
getISODay()
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
an ISO day; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Converting the XMLDate to ISO format..." );
var ISO = d.getISODay();
print( "The ISO day is: " + ISO );
XMLDate.getISOMonth()
This method returns a string containing the month portion of date/time object in ISO format; or returns
null if the conversion fails. The syntax is:
getISOMonth()
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
an ISO month; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Converting the XMLDate to ISO format..." );
var ISO = d.getISOMonth();
print( "The ISO month is: " + ISO );
XMLDate.getISOTime()
This method returns a string containing the time portion of date/time object in ISO format; or returns
null if the conversion fails. The syntax is:
getISOTime()
112
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
an ISO time; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Converting the XMLDate to ISO format..." );
var ISO = d.getISOTime();
print( "The ISO time is: " + ISO );
XMLDate.getISOYear()
This method returns a string containing the year portion of date/time object in ISO format; or returns
null if the conversion fails. The syntax is:
getISOYear()
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
an ISO year; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Converting the XMLDate to ISO format..." );
var ISO = d.getISOYear();
print( "The ISO year is: " + ISO );
XMLDate.getSCDateTimeString()
This method returns a Service Manager-formatted date/time string; or returns null if the conversion
fails. The syntax is:
getSCDateTimeString()
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
Service Manager-formatted date/time string; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print("Converting the XMLDate to a Service Manager date/time string...");
var sm = d.getSCDateTimeString();
print( "The Service Manager date/time string is: " + sm );
XMLDate.JSDate()
This method, which is an alias of the getDate() method, returns a JavaScript date/time object; or
returns null if the conversion fails. The syntax is:
JSDate()
113
Example
This example creates a new XMLDate object containing today's date; converts the XMLDate object to
a JavaScript date/time object; and then displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( new Date() );
print( "The value of the new XMLDate object is: " + d );
print( "Converting the XMLDate to a JavaScript object..." );
var js = d.JSDate();
print( "The JavaScript date/time object is: " + js );
XMLDate.toSCDuration(duration)
This method returns a string containing the new Service Manager duration converted from an ISO
8601 duration; or returns null if the conversion fails.
The syntax is:
toSCDuration( duration )
duration ISO 8601 duration Yes Contains the ISO 8601 duration string or variable value you want
string the method to convert to a Service Manager duration.
Example
This example creates a new XMLDate object containing a hard-coded ISO date; converts the ISO
date/time to a Service Manager duration; and displays the result.
print( "Creating XMLDate object..." );
var d = new XMLDate( "P01DT12H01M01S" );
print( "The value of the new XMLDate object is: " + d );
print( "Converting " + d.toString() + " to a SC duration..." );
var smDur = d.toSCDuration();
print( "The Service Manager duration is: " + smDur );
114
Cross-reference: Index of methods and functions by task
Array handling
Service Manager arrays are held in SCFile objects. They have to be converted to a JavaScript array
by using the toArray() method. As an example, the following code shows how to check and fill an
array:
CI=new SCFile("device")
var array_incidents = new Array();
var ind = 0;
while(CI.array_incidents[ind] != null)
{
array_incidents[ind]=CI.array_incidents[ind];
ind++;
}
/*
**********************************************************************
The following statement achieves the same results as the above while-
loop:
array_incidents=CI.array_incidents.toArray()
**********************************************************************
*/
var j=0;
/*
**********************************************************************
Since indexOf is not available on Arrays, the array has to be converted
to a string before using this function to find if a single element is
part of the array.
**********************************************************************
*/
var temp_string = array_incidents.toString();
var i = temp_string.indexOf(incNumber);
/*
**********************************************************************
the next set of statements can be replaced by the push() method. The
lines of code would be as follows:
if (i<0)
{
var newArrayLength = array_incidents.push( incNumber );
**********************************************************************
*/
if (i < 0)
{
if (array_incidents == null)
{
j=0;
}
else
{
j=array_incidents.length;
}
array_incidents[j] = incNumber;
}
115
Topic Page Description
SCFile 32 Creates a SCFile object containing the provided record, structure, or array.
SCFile.join() 50 Returns the elements of either a Service Manager Datum array object or a
JavaScript array as a string.
SCFile.pop() 54 Removes the last element from a JavaScript array and returns the element
removed as a string.
SCFile.push() 55 Adds an entry to the end of a JavaScript array and returns the total number
of entries in the array.
SCFile.shift() 56 Removes the first element from a JavaScript array and returns the element
removed as a string.
SCFile.unshift() 58 Adds an entry to the beginning of a JavaScript array and returns the total
number of entries in the array.
Date/Time handling
Topic Page Description
XMLDate.addDuration() 110 Returns an XMLDate object containing the new date/time after
adding the duration from the duration argument.
XMLDate.getISODate() 111 Returns a string containing the date portion of a date/time object in
ISO format.
XMLDate.getISODateTimeString() 111 Returns a string containing the date and time portion of date/time
object in ISO format.
XMLDate.getISODay() 112 Returns a string containing the day portion of date/time object in
ISO format.
XMLDate.getISOMonth() 112 Returns a string containing the month portion of date/time object in
ISO format.
XMLDate.getISOTime() 112 Returns a string containing the time portion of date/time object in
ISO format.
XMLDate.getISOYear() 113 Returns a string containing the year portion of date/time object in
ISO format.
XMLDate.toSCDuration() 114 Returns a string containing the new Service Manager duration
converted from an ISO 8601 duration.
116
Database or file manipulation
Topic Page Description
SCFile 32 Creates an SCFile object containing the provided record, structure, or array.
SCFile.doSelect() 41 Runs the specified query and returns a list of records matching the query..
SCFile.isRecord() Error! Verifies that the query or query condition returns a Service Manager record.
Bookmar
k not
defined.
SCFile.setValue() 56 Adds or updates a Service Manager record with the new field value defined in the
newValue argument.
writeFile 23 Writes the contents of the object parameter to the file specified in the path
parameter.
readFile 23 Reads the contents of a local file and returns a string object with the contents of
that file.
Basic functionality
Topic Page Description
system.sysinfo 20 Calls an XML list of properties about the Service Manager server.
system.threads 21 Calls an XML list of the current Service Manager threads into memory.
system.user 21 Calls an XML list of properties of the currently logged on Service Manager user.
117
Topic Page Description
system.users 22 Calls an XML list of the currently logged on Service Manager users into memory.
JavaScript return 12 Integer values to test the values returned by the methods of objects.
code properties
print 22 Displays the contents of the method argument in the client Messages view and also
prints it in the Service Manager log file.
Quit 24 Stops the processing of JavaScript from the point it is called and returns a failure return
code.
doSOAPRequest 26 Issues a SOAP request to a remote server specified by an URL and returns the SOAP
response in a string or an error message.
RCtoString 29 Converts a Service Manager global return code value into a localized text string.
Conversions
Topic Page Description
SCFile.JSDate() 51 Converted Service Manager date/time data into JavaScript date/time objects
(SCFile now automatically converts Service Manager date/time data into
JavaScript date/time objects).
SCFile.setType() Error! Set the data type of Service Manager datum objects (SCFile now automatically
Bookmar converts Service Manager data types into JavaScript data types).
k not
defined.
XML
Topic Page Description
system.sysinfo 20 Calls an XML list of properties about the Service Manager server.
system.threads 21 Calls an XML list of the current Service Manager threads into memory.
118
Topic Page Description
system.user 21 Calls an XML list of properties of the currently logged on Service Manager
user.
system.users 22 Calls an XML list of the currently logged on Service Manager users into
memory.
XML 34 Creates an empty XML object where you can store and manipulate XML
documents.
XML.addAttribute() 59 Inserts an attribute and attribute value into the current element.
XML.getAttributeNode() 65 Returns an XML object containing the target attribute the current element.
XML.getDocumentElement() 69 Searches an XML object for the DOM document element (or "root" node).
XML.getFirstAttribute() 70 Returns an object representing the first attribute of the current node.
XML.getFirstChildElement() 73 Returns an object representing the first child node of the current node.
XML.getNextAttribute() 76 Returns an object representing the first attribute of the current node.
XML.getNextSiblingElement() 79 Returns an object representing the next node at the same level in the DOM
tree as the current node.
XML.getNodeName() 82 Returns a string representing the name of the current element or attribute.
XML.getNodeType() 83 Evaluates an XML object and returns an integer representing the XML DOM
type of the current element or attribute.
XML.getNodeValue() 84 Returns a string representing the value of the current XML element.
XML.getParentNode() 86 Returns an XML object representing the parent node of the current node.
XML.getPrefix() 89 Returns a string representing the namespace value of the current node
(element or attribute).
XML.getQualifiedName() 91 Returns a string representing the name of the current element or attribute.
XML.getText() 93 Returns a string representing the value of the current XML element (alias for
getNodeValue).
XML.getValue() 95 Returns a string representing the value of the current XML element (alias for
getNodeValue).
XML.importNode() 97 Returns an XML object containing a copy of the source XML node.
XML.isDocumentElement() 99 Returns the Boolean value of true if the current element is the DOM document
element (the "root" node of the XML document) or false if it is not.
XML.setAttributeValue() 100 Adds or updates the attribute value of the target attribute.
XML.setContent() 103 Creates an XML object from a string or the contents of an external file object
119
Topic Page Description
if it was able to successfully parse the XML input.
XML.setText() 106 Adds or updates the value of the current element (alias for setNodeValue).
XML.setValue() 108 Adds or updates the value of the current element (alias for setNodeValue).
XMLDate.addDuration() 110 Returns an XMLDate object containing the new date/time after adding the
duration from the duration argument.
XMLDate.getISODate() 111 Returns a string containing the date portion of a date/time object in ISO
format
XMLDate.getISODateTimeStri 111 Returns a string containing the date and time portion of date/time object in
ng() ISO format
XMLDate.getISODay() 112 Returns a string containing the day portion of date/time object in ISO format
XMLDate.getISOMonth() 112 Returns a string containing the month portion of date/time object in ISO
format
XMLDate.getISOTime() 112 Returns a string containing the time portion of date/time object in ISO format
XMLDate.getISOYear() 113 Returns a string containing the year portion of date/time object in ISO format
XMLDate.toSCDuration() 114 Returns a string containing the new Service Manager duration converted from
an ISO 8601 duration
120
For more information
Please visit the HP OpenView support web site at:
http://www.hp.com/managementsoftware/support
This web site provides contact information and details about the products, services, and support that
HP OpenView offers.
HP OpenView online software support provides customer self-solve capabilities. It provides a fast and
efficient way to access interactive technical support tools needed to manage your business. As a
valuable support customer, you can benefit by being able to:
Search for knowledge documents of interest
Submit and track progress on support cases
Submit enhancement requests online
Download software patches
Manage a support contract
Look up HP support contacts
Review information about available services
Enter discussions with other software customers
Research and register for software training
Note: Most of the support areas require that you register as an HP Passport user and sign in. Many
also require an active support contract.
To find more information about support access levels, go to the following URL:
http://www.hp.com/managementsoftware/access_level
© 2008 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
The only warranties for HP products and services are set forth in the express warranty statements accompanying such
products and services. Nothing herein should be construed as constituting an additional warranty. HP shall not be liable for
technical or editorial errors or omissions contained herein.
HP and Service Manager are registered trademarks of Hewlett-Packard Development Company, L.P. Verity is a registered
trademark of Autonomy Corporation plc and its affiliates. JavaScript is a registered trademark of Sun Microsystems, Inc. in
the United States and other countries.
05/2008