blib/lib/ServiceNow/SOAP.pm

filter: Statementstmt 21.9% 109 / 496 Branchbran 9.7% 16 / 164 Conditioncond 14.2% 3 / 21 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 30.0% 21 / 70 Podpod 100% 1 / 1 totaltotal 19.6% 150 / 765 CC 94 SCAR 28.6
CC
94
Cov
19%
attachFile
72.0
call
56.0
query
42.0
CRAP 17.5
↑ Summary
1 package ServiceNow::SOAP;
2  
3 24 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 24 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 24 require Exporter;
6 24 our @ISA = qw(Exporter);
7 24 our @EXPORT = qw(ServiceNow);
8  
9 24 ▶use SOAP::Lite;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 24 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 24 ▶use HTTP::Cookies;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 24 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 24 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 24 ▶use XML::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 24 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 24 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 24 our $VERSION = '0.15';
19  
20 =head1 NAME
21  
22 ServiceNow::SOAP - A better Perl API for ServiceNow
23  
24 =head1 SYNOPSIS
25  
26 # return a reference to a session object
27 $sn = ServiceNow($instancename, $username, $password);
28
29 # return a reference to a table object
30 $table = $sn->table($tablename);
31  
32 # count records
33 $count = $table->count(%parameters);
34
35 # return a list of sys_ids
36 @keys = $table->getKeys(%parameters);
37
38 # return a single record as a hash
39 $rec = $table->get(sys_id => $sys_id);
40
41 # return a set of records as an array of hashes
42 @recs = $table->getRecords(%parameters);
43  
44 # call getKeys and return a query object
45 $qry = $table->query(%parameters);
46
47 # fetch the next chunk of records
48 @recs = $qry->fetch($numrecs);
49  
50 # retrieve a record based on a unique key other than sys_id
51 $rec = $table->getRecord($name => $value);
52
53 # insert a record
54 $sys_id = $table->insert(%parameters);
55
56 # insert multiple records
57 @results = $table->insert(@records);
58
59 # update a record
60 $table->update(%parameters);
61
62 =head1 EXAMPLES
63  
64 Create session and table objects.
65  
66 use ServiceNow::SOAP;
67
68 my $sn = ServiceNow("mycompany", $username, $password);
69
70 my $computer_tbl = $sn->table("cmdb_ci_computer");
71 my $incident_tbl = $sn->table("incident");
72  
73 Retrieve a small number of records.
74
75 my @recs = $computer_tbl->getRecords(
76 "location.name" => "London",
77 "operational_status" => "1",
78 __order_by => "name",
79 __limit => 500);
80 foreach my $rec (@recs) {
81 print $rec->{name}, "\n";
82 }
83
84 Count records.
85
86 my $count = $computer_tbl->count(
87 "location.name" => "London",
88 "operational_status" => "1");
89
90 Retrieve records in chunks.
91
92 my $qry = $computer_tbl->query(
93 "location.name" => "London",
94 "operational_status" => "1",
95 __order_by => "name");
96 while (@recs = $qry->fetch(200)) {
97 foreach my $rec (@recs) {
98 print $rec->{name}, "\n";
99 }
100 }
101
102 Retrieve all the records in a large table.
103
104 my @recs = $computer_tbl->query()->fetchAll();
105
106 Insert a record.
107  
108 my $sys_id = $incident_tbl->insert(
109 assignment_group => "Network Support",
110 short_description => $short_description,
111 impact => 2);
112  
113 Retrieve a single record based on sys_id.
114  
115 my $rec = $incident_tbl->get($sys_id);
116 print "number=", $rec->{number}, "\n";
117  
118 Retrieve a single record based on number.
119  
120 my $rec = $incident_tbl->getRecord(number => $number);
121 print "sys_id=", $rec->{sys_id}, "\n";
122
123 Update a record.
124  
125 $incident_tbl->update($sys_id,
126 assigned_to => "Fred Luddy",
127 incident_state => 2);
128
129 =head1 DESCRIPTION
130  
131 This module provides access to ServiceNow via SOAP Web Services.
132  
133 Features of this module include:
134  
135 =over
136  
137 =item *
138  
139 Support for both Direct Web Services and Scripted Web Services.
140  
141 =item *
142  
143 Simplified API which closely mirrors ServiceNow's
144 L<Direct Web Services API|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API>
145 documentation.
146  
147 =item *
148  
149 Robust methods for reading large amounts of data
150 which adhere to ServiceNow's L<best practice recommendations|http://wiki.servicenow.com/index.php?title=Web_Services_Integrations_Best_Practices#Queries>.
151  
152 =back
153  
154 =cut
155  
156 24 our $XMLNS = 'http://www.glidesoft.com/';
157 24 our $context; # global variable points to current session
158  
159 sub SOAP::Transport::HTTP::Client::get_basic_credentials {
160 0 ▶ my $user = $context->{user};
Subroutine get_basic_credentials: not called CC=2 SCAR=17.9
161 0 my $pass = $context->{pass};
162 0 ▶ warn "Username is null" unless $user;
Branch: 1 branch
BranchTrueFalseTotal
unless $user 0 0 0
163 # warn "Password is null" unless $pass;
164 0 return $user => $pass;
165 }
166  
167 # Convert a list of parameters to SOAP::Data
168 sub _params {
169 1 ▶ my @params;
Subroutine _params: called CC=5 SCAR=18.9
170 # if there are at least 2 parameters then they must be name/value pairs
171 1 ▶ while (scalar(@_) > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ > 1) 1 1 2
172 1 my $name = shift;
173 1 my $value = shift;
174 1 ▶ warn "Parameter name appears to be a sys_id"
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /^[0-9A-Fa-f]{32}$/ 0 1 1
175 if $name =~ /^[0-9A-Fa-f]{32}$/;
176 1 push @params, SOAP::Data->name($name, $value)->type('string');
177 }
178 1 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 1 1
179 # there is one parameter left
180 0 $_ = shift;
181 0 ▶ if (/^[0-9A-Fa-f]{32}$/) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^[0-9A-Fa-f]{32}$/) { } 0 0 0
182 # it looks like a sys_id
183 0 push @params, SOAP::Data->name(sys_id => $_);
184 }
185 else {
186 # assume any left over unnamed param is an encoded query
187 0 push @params, SOAP::Data->name(__encoded_query => $_)
188 }
189 }
190 1 return @params;
191 }
192  
193 # print for debugging
194 sub _trace {
195 0 ▶ print @_;
Subroutine _trace: not called CC=1 SCAR=6.9
196 }
197  
198 sub ServiceNow {
199 2 ▶ return ServiceNow::SOAP::Session->new(@_);
Subroutine ServiceNow: called CC=1 SCAR=0.0
Pod documented
200 }
201  
202 =head1 EXPORTED FUNCTIONS
203  
204 =head2 ServiceNow
205  
206 This C<ServiceNow> function
207 (which is essentially an alias for C<ServiceNow::SOAP::Session-E<gt>new()>)
208 is used to obtain a reference to a Session object.
209 The Session object essentially holds the URL and
210 connection credentials for your ServiceNow instance,
211 and the L<SOAP::Lite> object.
212  
213 The first argument to this function is the instance,
214 which can be either a fully qualified URL
215 (I<e.g.> C<"https://mycompanydev.service-now.com">)
216 or an instance name (I<e.g.> C<"mycompanydev">).
217 The second argument is the user name.
218 The third argument is the password.
219  
220 Various options can be specified as
221 name value pairs following the password.
222 For a list of options refer to L</set>.
223  
224 B<Syntax>
225  
226 my $sn = ServiceNow($instance, $username, $password, %options);
227
228 B<Examples>
229  
230 The following two statements are equivalent.
231  
232 my $sn = ServiceNow("https://mycompanydev.service-now.com", "soap.perl", $password);
233 my $sn = ServiceNow("mycompanydev", "soap.perl", $password);
234  
235 Various options can be specified as name/value pairs following the password.
236 Refer to L</set> for details.
237  
238 my $sn = ServiceNow("mycompanydev", $username, $password,
239 query => 100000, trace => 1);
240
241 =head1 ServiceNow::SOAP::Session
242  
243 =cut
244  
245 package ServiceNow::SOAP::Session;
246  
247 sub new {
248 3 ▶ my ($pkg, $url, $user, $pass, @options) = @_;
Subroutine new: called CC=7 SCAR=20.0
249 3 ▶ Carp::croak "Missing instance" unless $url;
Branch: 1 branch
BranchTrueFalseTotal
unless $url 0 3 3
250 3 ▶ Carp::carp "Username is blank" unless $user;
Branch: 1 branch
BranchTrueFalseTotal
unless $user 0 3 3
251 3 ▶ Carp::carp "Password is blank" unless $pass;
Branch: 1 branch
BranchTrueFalseTotal
unless $pass 0 3 3
252 # strip off any trailing slash
253 3 $url =~ s/\/$//;
254 # append '.service-now.com' unless the URL contains a '.'
255 3 ▶ $url = $url . '.service-now.com' unless $url =~ /\./;
Branch: 1 branch
BranchTrueFalseTotal
unless $url =~ /\./ 3 0 3
256 # prefix with 'https://' unless the URL already starts with https:
257 3 ▶ $url = 'https://' . $url unless $url =~ /^http[s]?:/;
Branch: 1 branch
BranchTrueFalseTotal
unless $url =~ /^http[s]?:/ 3 0 3
258 # This endpoint is a stub. Endpoint will be changed before each call.
259 3 my $endpoint = "$url/sys_user.do?SOAP";
260 3 my $cookiejar = HTTP::Cookies->new(ignore_discard => 1);
261 3 my @params = (cookie_jar => $cookiejar);
262 3 my $client = SOAP::Lite->proxy($endpoint, @params);
263 3 my $session = {
264 url => $url,
265 user => $user,
266 pass => $pass,
267 trace => 0,
268 dv => 0,
269 fetch => 250,
270 query => 0,
271 client => $client,
272 cookiejar => $cookiejar,
273 private => {}
274 };
275 3 bless $session, $pkg;
276 3 $session->set(@options);
277 3 my $trace = $session->{trace};
278 3 ▶ $session->trace("url=$url; user=$user") if $trace;
Branch: 1 branch
BranchTrueFalseTotal
if $trace 0 3 3
279 3 $context = $session;
280 3 return $session;
281 }
282  
283 #
284 # private method to return a private table for use by this module
285 #
286 sub private {
287 0 ▶ my ($session, $tablename) = @_;
Subroutine private: not called CC=2 SCAR=17.9
288 0 my $table = $session->{private}{$tablename};
289 0 ▶ if (!$table) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($table) 0 0 0
290 0 $table = $session->table($tablename);
291 0 $session->{private}{$tablename} = $table;
292 }
293 # make sure DV is always false for private tables
294 0 $table->setDV(0);
295 0 return $table;
296 }
297  
298 24 our $startTime;
299  
300 sub trace {
301 0 ▶ my ($session, $message) = @_;
Subroutine trace: not called CC=2 SCAR=17.9
302 0 ▶ ServiceNow::SOAP::_trace $message, "\n" if $message;
Branch: 1 branch
BranchTrueFalseTotal
if $message 0 0 0
303 }
304  
305 sub traceBefore {
306 0 ▶ my ($session, $methodname) = @_;
Subroutine traceBefore: not called CC=2 SCAR=17.9
307 0 my $trace = $session->{trace};
308 0 ▶ return unless $trace;
Branch: 1 branch
BranchTrueFalseTotal
unless $trace 0 0 0
309 0 my $tablename = $session->{name};
310 0 $| = 1;
311 0 ServiceNow::SOAP::_trace "$methodname...";
312 0 $startTime = Time::HiRes::time();
313 }
314  
315 sub traceAfter {
316 0 ▶ my ($session, $message) = @_;
Subroutine traceAfter: not called CC=3 SCAR=24.8
317 0 my $trace = $session->{trace};
318 0 ▶ return unless $trace;
Branch: 1 branch
BranchTrueFalseTotal
unless $trace 0 0 0
319 0 my $finishTime = Time::HiRes::time();
320 0 my $elapsed = $finishTime - $startTime;
321 0 ▶ ServiceNow::SOAP::_trace sprintf(" %.2fs", $elapsed),
Branch: 1 branch
BranchTrueFalseTotal
$message ? : 0 0 0
322 $message ? " $message\n" : "\n";
323 }
324  
325 sub traceContent {
326 0 ▶ my ($session, $content) = @_;
Subroutine traceContent: not called CC=4 SCAR=30.0
327 0 my $trace = $session->{trace};
328 0 ▶ return unless $trace > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $trace > 1 0 0 0
329 0 ▶ $content = $session->{client}->transport()->http_response()->content()
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 0 0
330 unless defined $content;
331 0 ▶ ServiceNow::SOAP::_trace $content, "\n" if $content;
Branch: 1 branch
BranchTrueFalseTotal
if $content 0 0 0
332 }
333  
334 =head2 call
335  
336 This method calls a
337 L<Scripted Web Service|http://wiki.servicenow.com/index.php?title=Scripted_Web_Services>.
338 The input parameters can be passed in as list of key/value pairs
339 or as a hash reference.
340 In a list context this method will return a list of key/value pairs.
341 In a scalar context it will return a hash reference.
342  
343 Use of this method requires the C<soap_script> role and activation of the
344 "Web Services Provider - Scripted" plugin.
345  
346 B<Syntax>
347  
348 my %outputs = $sn->call($name, %inputs);
349 my $outputs = $sn->call($name, $inputs); # $inputs must be a hash reference
350  
351 B<Example>
352  
353 my %outputs = $sn->call('OrderBlackBerry',
354 phone_number => '555-555-5555',
355 requested_for => 'Fred Luddy');
356 print "created request ", $outputs{request_number}, "\n";
357  
358 =cut
359  
360 sub call {
361 0 ▶ my $session = shift;
Subroutine call: not called CC=7 SCAR=40.3
362 0 my $function = shift;
363 0 my $trace = $session->{trace};
364 0 my $baseurl = $session->{url};
365 0 my $endpoint = "$baseurl/$function.do?SOAP";
366 0 my $client = $session->{client};
367 my @params =
368 (@_ && ref $_[0] eq 'HASH') ?
369 0 ▶ ServiceNow::SOAP::_params(%{$_[0]}) :
Branch: 1 branch
BranchTrueFalseTotal
@_ && ref $_[0] eq 'HASH' ? : 0 0 0
Condition0%0/3
@_ and ref $_[0] eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
@_ and ref $_[0] eq "HASH"
@_ ref $_[0] eq "HASH"
Truth table0%0/3
A and B
A= @_B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
370 ServiceNow::SOAP::_params(@_);
371 0 $session->traceBefore($function);
372 0 $context = $session;
373 0 my $som = $client->endpoint($endpoint)->call('execute' => @params);
374 0 ▶ Carp::croak $som->faultdetail if $som->fault;
Branch: 1 branch
BranchTrueFalseTotal
if $som->fault 0 0 0
375 0 $session->traceAfter('');
376 0 my $response = $som->body->{executeResponse};
377 0 ▶ if (ref $response eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $response eq 'HASH') { } 0 0 0
378 0 ▶ return wantarray ? %{$response} : $response;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
379 }
380 else {
381 0 ▶ return wantarray ? () : undef;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
382 }
383 }
384  
385 =head2 connect
386  
387 Use of this method is optional, but sometimes you want to know up front
388 whether your connection credentials are valid.
389 This method tests them by attempting to get the user's profile
390 from C<sys_user> using C<getRecords>, and trapping the error.
391 If successful, the session object is returned.
392 If unsuccessful, null is returned and the error message is in $@.
393  
394 B<Syntax>
395  
396 my $sn = ServiceNow($instancename, $username, $password)->connect()
397 or die "Unable to connect to $instancename: $@";
398  
399 =cut
400  
401 sub connect {
402 1 ▶ my $session = shift;
Subroutine connect: called CC=8 SCAR=28.2
403 1 my $trace = $session->{trace};
404 1 my $username = $session->{user};
405 1 my $user_tbl = $session->table('sys_user');
406 1 my @recs;
407 1 eval { @recs = $user_tbl->getRecords(user_name => $username) };
408 1 ▶ if ($@ or scalar(@recs) != 1 or
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or scalar @recs != 1 or $recs[0]{"user_name"} ne $username) 0 0 0
Condition33%2/6
$@ or scalar @recs != 1 or $recs[0]{"user_name"} ne $username
l!l&&r!l&&!r
100
$@ or scalar @recs != 1
l!l&&r!l&&!r
100
MC/DC0%0/3
$@ or scalar @recs != 1 or $recs[0]{"user_name"} ne $username
$@ scalar @recs != 1 $recs[0]{"user_name"} ne $username
Truth table25%1/4
A or B or C
A= $@B= scalar @recs != 1C= $recs[0]{"user_name"} ne $username
ABCresult
1XX1
01X1
0011
0000
409 $recs[0]->{user_name} ne $username) {
410 1 my $trace = $session->{trace};
411 1 ▶ $session->trace("connect failed") if $trace;
Branch: 1 branch
BranchTrueFalseTotal
if $trace 0 1 1
412 }
413
414 1 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 0 1
415 0 ▶ return 0 unless scalar(@recs) == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @recs == 1 0 0 0
416 0 my $rec = $recs[0];
417 0 ▶ return 0 unless $rec->{user_name} eq $username;
Branch: 1 branch
BranchTrueFalseTotal
unless $rec->{"user_name"} eq $username 0 0 0
418 0 return $session;
419 }
420  
421 =head2 loadSession
422  
423 This method loads the session information (I<i.e.> cookies) from a file.
424 This may be required if you are running the same perl script multiple times
425 (each time in a separate process)
426 and you do not want to establish a separate ServiceNow session
427 each time the script is run.
428 Use L</saveSession> to save the session identifier to a file
429 and this method to load the session identifier from the file.
430  
431 B<Syntax>
432  
433 $sn->loadSession($filename);
434
435 =cut
436
437 sub loadSession {
438 0 ▶ my ($self, $filename) = @_;
Subroutine loadSession: not called CC=1 SCAR=6.9
439 0 my $cookiejar = $self->{cookiejar};
440 0 $cookiejar->load($filename);
441 }
442  
443 =head2 saveSession
444  
445 This method saves the session information (I<i.e.> cookies) to a file.
446 For usage notes refer to L</loadSession> above.
447  
448 B<Syntax>
449  
450 $sn->saveSession($filename);
451
452 =cut
453  
454 sub saveSession {
455 0 ▶ my ($self, $filename) = @_;
Subroutine saveSession: not called CC=1 SCAR=6.9
456 0 my $cookiejar = $self->{cookiejar};
457 0 $cookiejar->save($filename);
458 }
459  
460 =head2 set
461  
462 This method permits assignment of various default values and processing options.
463 The same options can also be specified
464 following the password argument of L</ServiceNow>.
465  
466 The following options may be specified.
467  
468 =over
469  
470 =item *
471  
472 C<dv> - Specify a default value for Display Values.
473 This can be overridden at the Table level by L</setDV>.
474 For an explanation of values see L</setDV>.
475 This option is only effective if it is changed
476 prior to calling the L</table> method.
477  
478 =item *
479  
480 C<fetch> - Specify default number of records to be retrieved
481 by L</fetch>. Default is 250.
482 This option will be ignored if it is overridden
483 by a parameter to L</fetch> or L</fetchAll>.
484  
485 =item *
486  
487 C<query> - Specify the number of keys to be retrieved by
488 L</query> in each call to L</getKeys>.
489 The default is 0,
490 which causes all keys to be retrieved
491 in a single call.
492  
493 =item *
494  
495 C<timeout> - Specify a
496 SOAP::Transport::HTTP::Client timeout value.
497  
498 =item *
499  
500 C<trace> - Specify a trace level.
501 Refer to L</DIAGNOSTICS> below.
502 Default is 0.
503  
504 =back
505  
506 B<Syntax>
507  
508 $sn->set(%options);
509
510 B<Example>
511  
512 $sn->set(query => 100000, trace => 1);
513  
514 =cut
515  
516 sub set {
517 3 ▶ my $self = shift;
Subroutine set: called CC=7 SCAR=35.7
518 3 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 3 3
519 0 my $key = shift;
520 0 my $value = shift;
521 0 ▶ Carp::croak '"fetch" must be greater than 0'
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "fetch" and $value < 1 0 0 0
Condition0%0/3
$key eq "fetch" and $value < 1
!ll&&!rl&&r
000
MC/DC0%0/2
$key eq "fetch" and $value < 1
$key eq "fetch" $value < 1
Truth table0%0/3
A and B
A= $key eq "fetch"B= $value < 1
ABresult
0X0
100
111
522 if $key eq "fetch" and $value < 1;
523 0 ▶ Carp::croak "option \"$key\" not recognized"
Branch: 1 branch
BranchTrueFalseTotal
unless $key =~ /^(dv|fetch|query|timeout|trace)$/ 0 0 0
524 unless $key =~ /^(dv|fetch|query|timeout|trace)$/;
525 0 $self->{$key} = $value;
526 0 ▶ if ($key eq 'timeout' and $value > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "timeout" and $value > 0) 0 0 0
Condition0%0/3
$key eq "timeout" and $value > 0
!ll&&!rl&&r
000
MC/DC0%0/2
$key eq "timeout" and $value > 0
$key eq "timeout" $value > 0
Truth table0%0/3
A and B
A= $key eq "timeout"B= $value > 0
ABresult
0X0
100
111
527 0 $self->{client}->transport->timeout($value);
528 }
529 }
530 3 return $self;
531 }
532  
533 sub setTrace {
534 0 ▶ my ($self, $trace) = @_;
Subroutine setTrace: not called CC=1 SCAR=6.9
535 0 $self->{trace} = $trace;
536 0 return $self;
537 }
538  
539 =head2 soap
540  
541 This method returns a reference to the underlying
542 L<SOAP::Lite> object.
543  
544 =cut
545  
546 sub soap {
547 0 ▶ my $self = shift;
Subroutine soap: not called CC=1 SCAR=6.9
548 0 return $self->{client};
549 }
550  
551 =head2 table
552  
553 Used to obtain a reference to a Table object.
554 The Table object is subsequently used for
555 L</ServiceNow::SOAP::Table> methods described below.
556  
557 B<Syntax>
558  
559 $table = $sn->table($tablename);
560  
561 B<Example>
562  
563 my $computer_tbl = $sn->table("cmdb_ci_computer");
564
565 =cut
566  
567 sub table {
568 1 ▶ my ($self, $name) = @_;
Subroutine table: called CC=2 SCAR=7.0
569 1 my $table = ServiceNow::SOAP::Table->new($self, $name);
570 1 ▶ $table->setTrace($self->{trace}) if $self->{trace};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"trace"} 0 1 1
571 1 return $table;
572 }
573  
574 =head1 ServiceNow::SOAP::Table
575  
576 Table objects are used for ServiceNow's
577 L<Direct Web Services API|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API>.
578  
579 To obtain a Table object,
580 use the L</table> method describe above.
581  
582 The following Table object methods provide access to Direct Web Services API methods of the same name:
583 L</deleteRecord>,
584 L</get>,
585 L</getKeys>,
586 L</getRecords>,
587 L</insert>,
588 L</insertMultiple>,
589 L</update>.
590  
591 =cut
592  
593 package ServiceNow::SOAP::Table;
594  
595 # utility function to return true if argument is a sys_id
596 sub _isGUID {
597 0 ▶ return $_[0] =~ /^[0-9A-Fa-f]{32}$/;
Subroutine _isGUID: not called CC=1 SCAR=6.9
598 }
599  
600 # utility function to truncate a string
601 24 our $TRACE_LENGTH = 100;
602 sub _trunc {
603 0 ▶ my ($str, $len) = @_;
Subroutine _trunc: not called CC=3 SCAR=24.8
604 0 ▶ $len = $TRACE_LENGTH unless $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $len 0 0 0
605 0 ▶ return length($str) < $len ? $str : substr($str, 0, $len - 2) . "..";
Branch: 1 branch
BranchTrueFalseTotal
length $str < $len ? : 0 0 0
606 }
607  
608 sub _params {
609 1 ▶ return ServiceNow::SOAP::_params @_;
Subroutine _params: called CC=1 SCAR=0.0
610 }
611  
612 sub new {
613 1 ▶ my ($pkg, $session, $name) = @_;
Subroutine new: called CC=1 SCAR=0.0
614 1 $context = $session;
615 1 my $baseurl = $session->{url};
616 1 my $endpoint = "$baseurl/$name.do?SOAP";
617 my $new = bless {
618 session => $session,
619 name => $name,
620 endpoint => $endpoint,
621 dv => $session->{dv},
622 trace => $session->{trace}
623 1 }, $pkg;
624 1 return $new;
625 }
626  
627 sub callMethod {
628 1 ▶ my $self = shift;
Subroutine callMethod: called CC=4 SCAR=16.3
629 1 my $methodname = shift;
630 1 my $tablename = $self->{name};
631 1 my $session = $self->{session};
632 1 my $client = $session->{client};
633 1 my $baseurl = $session->{url};
634 1 my $endpoint = "$baseurl/$tablename.do?SOAP";
635 1 ▶ if ($methodname =~ /^(get|getRecords|aggregate)$/ && $self->{dv}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($methodname =~ /^(get|getRecords|aggregate)$/ and $self->{"dv"}) 0 1 1
Condition33%1/3
$methodname =~ /^(get|getRecords|aggregate)$/ and $self->{"dv"}
!ll&&!rl&&r
010
MC/DC0%0/2
$methodname =~ /^(get|getRecords|aggregate)$/ and $self->{"dv"}
$methodname =~ /^(get|getRecords|aggregate)$/ $self->{"dv"}
Truth table33%1/3
A and B
A= $methodname =~ /^(get|getRecords|aggregate)$/B= $self->{"dv"}
ABresult
0X0
100
111
636 0 my $dv = $self->{dv};
637 0 $endpoint = "$baseurl/$tablename.do?displayvalue=" . $dv . "&SOAP";
638 }
639 1 $context = $self->{session};
640 1 my $method = SOAP::Data->name($methodname)->attr({xmlns => $XMLNS});
641 # my @params = ServiceNow::SOAP::_params(@_);
642 1 my $som = $client->endpoint($endpoint)->call($method => @_);
643 0 ▶ Carp::croak $som->faultdetail if $som->fault;
Branch: 1 branch
BranchTrueFalseTotal
if $som->fault 0 0 0
644 0 return $som;
645 }
646  
647 sub traceBefore {
648 1 ▶ my ($table, $methodname) = @_;
Subroutine traceBefore: called CC=2 SCAR=7.9
649 1 my $session = $table->{session};
650 1 my $trace = $session->{trace};
651 1 ▶ return unless $trace;
Branch: 1 branch
BranchTrueFalseTotal
unless $trace 1 0 1
652 0 my $tablename = $table->{name};
653 0 $session->traceBefore("$methodname $tablename");
654 }
655  
656 sub traceAfter {
657 0 ▶ my ($table, $message, $content) = @_;
Subroutine traceAfter: not called CC=4 SCAR=30.0
658 0 my $session = $table->{session};
659 0 my $trace = $session->{trace};
660 0 ▶ return unless $trace;
Branch: 1 branch
BranchTrueFalseTotal
unless $trace 0 0 0
661 0 ▶ $session->traceAfter($message ? $message : '');
Branch: 1 branch
BranchTrueFalseTotal
$message ? : 0 0 0
662 0 ▶ return if $trace < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $trace < 2 0 0 0
663 0 $session->traceContent($content);
664 }
665  
666 =head2 addComment
667  
668 This method adds a comment to a task.
669  
670 See also: L</getComments>, L</getJournalEntries>
671  
672 B<Syntax>
673  
674 $table->addComment($sys_id, $comment);
675
676 =cut
677  
678 sub addComment {
679 0 ▶ my ($self, $sysid, $comment) = @_;
Subroutine addComment: not called CC=1 SCAR=6.9
680 0 $self->update($sysid, 'comments' => $comment);
681 0 return $self;
682 }
683  
684 =head2 addWorkNote
685  
686 This method adds a work note to a task.
687  
688 See also: L</getWorkNotes>, L</getJournalEntries>
689  
690 B<Syntax>
691  
692 $table->addWorkNote($sys_id, $work_note);
693
694 =cut
695  
696 sub addWorkNote {
697 0 ▶ my ($self, $sysid, $note) = @_;
Subroutine addWorkNote: not called CC=1 SCAR=6.9
698 0 $self->update($sysid, 'work_notes' => $note);
699 0 return $self;
700 }
701  
702 =head2 asQuery
703  
704 This method creates a new L<Query|/ServiceNow::SOAP::Query> object
705 from a list of keys.
706 It does not make any Web Services calls.
707 It simply makes a copy of the list.
708 Each item in the list must be a sys_id for the respective table.
709  
710 B<Syntax>
711  
712 $query = $table->asQuery(@keys);
713  
714 B<Example>
715  
716 In this example, we assume that C<@incRecs> contains an array of C<incident> records
717 from a previous query.
718 We need an array of C<sys_user_group> records
719 for all referenced assignment groups.
720 We use C<map> to extract a list of assignment group keys from the C<@incRecs>;
721 C<grep> to discard the blanks; and C<uniq> to discard the duplicates.
722 C<@grpKeys> contains the list of C<sys_user_group> keys.
723 This array is then used to construct a new Query using L</asQuery>.
724 L</fetchAll> is used to retrieve the records.
725  
726 use List::MoreUtils qw(uniq);
727  
728 my @grpKeys = uniq grep { !/^$/ } map { $_->{assignment_group} } @incRecs;
729 my @grpRecs = $sn->table("sys_user_group")->asQuery(@grpKeys)->fetchAll();
730
731 =cut
732  
733 sub asQuery {
734 0 ▶ my $self = shift;
Subroutine asQuery: not called CC=1 SCAR=6.9
735 0 my $query = ServiceNow::SOAP::Query->new($self);
736 0 my @keys = @_;
737 0 $query->{keys} = \@keys;
738 0 $query->{count} = scalar(@keys);
739 0 $query->{params} = {};
740 0 $query->{index} = 0;
741 0 return $query;
742 }
743
744 =head2 attachFile
745  
746 If you are using Perl to create incident tickets,
747 then you may have a requirement to attach files to those tickets.
748  
749 This method implements the
750 L<attachment creator API|http://wiki.servicenow.com/index.php?title=AttachmentCreator_SOAP_Web_Service>.
751 The method requires C<soap_ecc> role.
752  
753 When you attach a file to a ServiceNow record,
754 you can optionally specify an attachment name
755 which is different from the actual file name.
756 If no attachment name is specified,
757 this function will
758 assume that the attachment name is the
759 the file name stripped of any directory.
760  
761 You can also optionally specify a MIME type.
762 If no type is specified,
763 the function will use L<MIME::Types>
764 to infer the type.
765  
766 This function will die if the file cannot be read.
767  
768 B<Syntax>
769  
770 $table->attachFile($sys_id, $filepath);
771 $table->attachFile($sys_id, $filepath, $attachment_name, $mime_type);
772  
773 B<Example>
774  
775 $incident_tbl->attachFile($sys_id, "screenshot.png");
776
777 =cut
778  
779 sub attachFile {
780 0 ▶ my $self = shift;
Subroutine attachFile: not called CC=8 SCAR=42.8
781 0 my $session = $self->{session};
782 0 my $tablename = $self->{name};
783 0 my ($sysid, $filepath, $attachname, $mimetype) = @_;
784 0 ▶ Carp::croak "attachFile: No such record" unless $self->get($sysid);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->get($sysid) 0 0 0
785 0 my ($parsename, $parsepath, $suffix ) =
786 File::Basename::fileparse($filepath, "\.[^.]*");
787 0 ▶ if (!$attachname) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($attachname) 0 0 0
788 0 $attachname = $parsename . $suffix;
789 }
790 0 ▶ if (!$mimetype) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($mimetype) 0 0 0
791 0 require MIME::Types;
792 0 my $typer = MIME::Types->new;
793 0 $mimetype = $typer->mimeTypeOf($suffix);
794 }
795 0 ▶ Carp::croak "Unable to read file \"$filepath\"" unless -r $filepath;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $filepath 0 0 0
796 0 my $ecc_queue = $session->private('ecc_queue');
797 0 ▶ open my $fh, '<', $filepath
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $filepath or die qq[Unable to open "$filepath"\n$!] 0 0 0
798 or die "Unable to open \"$filepath\"\n$!";
799 0 binmode $fh;
800 0 my ($buf, $base64);
801 # encode in multiples of 57 bytes to ensure no padding in the middle
802 0 ▶ while (read $fh, $buf, 60*57) {
Branch: 1 branch
BranchTrueFalseTotal
if (read $fh, $buf, 3420) 0 0 0
803 0 $base64 .= MIME::Base64::encode_base64($buf);
804 }
805 0 close $fh;
806 0 my $len = length($base64);
807 0 print "attachment name=$attachname:$mimetype len=$len\n";
808 0 my $ecc_id = $ecc_queue->insert(
809 topic => 'AttachmentCreator',
810 name => "$attachname:$mimetype",
811 source => "$tablename:$sysid",
812 payload => $base64
813 );
814 0 ▶ die "attachFile failed" unless $ecc_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $ecc_id 0 0 0
815 }
816  
817 =head2 columns
818  
819 This method returns a list of the columns in a table.
820 The list is retrieved from the WSDL.
821  
822 B<Syntax>
823  
824 @columns = $table->columns();
825
826 =cut
827  
828 sub columns {
829 0 ▶ my $self = shift;
Subroutine columns: not called CC=2 SCAR=17.9
830 0 ▶ return @{$self->{columns}} if $self->{columns};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"columns"} 0 0 0
831 0 my %fields = $self->getFields();
832 0 my @columns = sort keys %fields;
833 0 $self->{columns} = \@columns;
834 0 return @columns;
835 }
836  
837 =head2 count
838  
839 This method counts the number of records in a table,
840 or the number of records that match a set of parameters.
841  
842 This method requres installation of the
843 L<Aggregate Web Service plugin|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API#aggregate>.
844  
845 See also: L</countBy>
846  
847 B<Syntax >
848  
849 $count = $table->count();
850 $count = $table->count($encodedQuery);
851 $count = $table->count(%parameters);
852  
853 B<Examples>
854  
855 Count the total number of users:
856  
857 my $count = $sn->table("sys_user")->count();
858
859 Count the number of active users:
860  
861 my $count = $sn->table("sys_user")->count(active => true);
862
863 =cut
864  
865 sub count {
866 0 ▶ my $self = shift;
Subroutine count: not called CC=1 SCAR=6.9
867 0 my @params = (COUNT => 'sys_id', @_);
868 0 $self->traceBefore('aggregate count');
869 0 my $som = $self->callMethod('aggregate' => _params(@params));
870 0 my $count = $som->body->{aggregateResponse}{aggregateResult}{COUNT};
871 0 $self->traceAfter("count=$count");
872 0 return $count;
873 }
874  
875 =head2 countBy
876  
877 This method counts the number of records in a table
878 using a GROUP_BY parameter,
879 which must be the name of a column in the table.
880 As with L</count>,
881 an encoded query or set of filter parameters can be specified.
882 The method returns a list of name/value pairs.
883  
884 This method requres installation of the
885 L<Aggregate Web Service plugin|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API#aggregate>.
886  
887 See also: L</count>
888  
889 B<Syntax>
890  
891 %counts = $table->countBy($groupByColumn);
892 %counts = $table->countBy($groupByColumn, $encodedQuery);
893 %counts = $table->countBy(%groupByColumn, %parameters);
894  
895 B<Example>
896  
897 my %counts = $sn->table("incident")->countBy("category");
898 foreach my $key (keys %counts) {
899 my $count = $counts{$key};
900 print "category: $key, count: $count\n";
901 }
902  
903 =cut
904  
905 sub countBy {
906 0 ▶ my $self = shift;
Subroutine countBy: not called CC=3 SCAR=24.8
907 0 my $groupby = shift;
908 0 ▶ Carp::croak "countBy missing groupby field" unless $groupby;
Branch: 1 branch
BranchTrueFalseTotal
unless $groupby 0 0 0
909 0 my @params = (COUNT => 'sys_id', GROUP_BY => $groupby, @_);
910 0 $self->traceBefore('aggregate count');
911 0 my $som = $self->callMethod('aggregate' => _params(@params));
912 0 my @aggResults = @{$som->body->{aggregateResponse}{aggregateResult}};
913 0 my $rows = @aggResults;
914 0 $self->traceAfter("rows=$rows");
915 0 my %results;
916 0 foreach my $agg (@aggResults) {
917 0 my $key = $agg->{$groupby};
918 0 my $count = $agg->{COUNT};
919 0 $results{$key} = $count;
920 }
921 0 return %results;
922 }
923  
924 =head2 deleteRecord
925  
926 This method deletes a record using the sys_id.
927 For information on available parameters
928 refer to the ServiceNow documentation on the
929 L<"deleteRecord" Direct SOAP API method|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API#deleteRecord>.
930  
931 B<Syntax>
932  
933 $table->deleteRecord(sys_id => $sys_id);
934 $table->deleteRecord($sys_id);
935  
936 =cut
937  
938 sub deleteRecord {
939 0 ▶ my $self = shift;
Subroutine deleteRecord: not called CC=2 SCAR=17.9
940 0 ▶ if (_isGUID($_[0])) { unshift @_, 'sys_id' };
Branch: 1 branch
BranchTrueFalseTotal
if (_isGUID($_[0])) 0 0 0
941 0 my %values = @_;
942 0 my $sysid = $values{sys_id};
943 0 $self->traceBefore("deleteRecord $sysid");
944 0 my $som = $self->callMethod('deleteRecord', _params(@_));
945 0 $self->traceAfter();
946 0 return $self;
947 }
948  
949 =head2 except
950  
951 This method returns a list of all columns in the table
952 B<except> those in the argument list.
953 The argument(s) to this method can be either a string
954 containing a comma separated list of names
955 or a list of names (I<i.e.> C<qw>).
956 This method returns a string containing a comma separated list of names.
957  
958 The [only useful] purpose of this function
959 is to that you can pass the result back in as an
960 C<__exclude_columns>
961 L<extended query parameter|http://wiki.servicenow.com/index.php?title=Direct_Web_Services#Extended_Query_Parameters>.
962  
963 See also: L</exclude>, L</include>
964  
965 B<Syntax>
966  
967 $names = $table->except(@list_of_columns);
968 $names = $table->except($comma_separated_list_of_columns);
969
970 B<Example>
971  
972 This example retrieves the columns sys_id, number and description
973 from the incident table.
974 In other words,
975 the result excludes all columns B<except> sys_id, number and description.
976  
977 my $incident_tbl = $sn->table("incident");
978 my @recs = $incident_tbl->getRecords(
979 __encoded_query => "sys_created_on>=$datetime",
980 __exclude_columns =>
981 $incident_tbl->except("sys_id,number,description"),
982 __limit => 250);
983
984 =cut
985  
986 sub except {
987 0 ▶ my $self = shift;
Subroutine except: not called CC=1 SCAR=6.9
988 0 my %names = map { $_ => 1 } split /,/, join(',', @_);
989 0 my @excl = grep { !$names{$_} } $self->columns();
990 0 return join(',', @excl);
991 }
992 =head2 get
993  
994 This method retrieves a single record based on sys_id.
995 The result is returned as a reference to a hash.
996  
997 If no matching record is found then null is returned.
998  
999 For additional information refer to the ServiceNow documentation on the
1000 L<"get" Direct SOAP API method|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API#get>.
1001  
1002 B<Syntax>
1003  
1004 $rec = $table->get(sys_id => $sys_id);
1005 $rec = $table->get($sys_id);
1006  
1007 B<Example>
1008
1009 my $rec = $table->get($sys_id);
1010 print $rec->{name};
1011
1012 =cut
1013  
1014 sub get {
1015 0 ▶ my $self = shift;
Subroutine get: not called CC=4 SCAR=30.0
1016 0 my $tablename = $self->{name};
1017 0 ▶ Carp::croak("get $tablename: missing argument") unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 0 0
1018 0 ▶ if (_isGUID($_[0])) { unshift @_, 'sys_id' };
Branch: 1 branch
BranchTrueFalseTotal
if (_isGUID($_[0])) 0 0 0
1019 0 $self->traceBefore('get');
1020 0 my $som = $self->callMethod('get' => _params(@_));
1021 0 my $result = $som->body->{getResponse};
1022 0 ▶ $self->traceAfter($result ? 'ok' : 'fail');
Branch: 1 branch
BranchTrueFalseTotal
$result ? : 0 0 0
1023 0 return $result;
1024 }
1025  
1026 =head2 getComments
1027  
1028 This method retrieves all comments for a task.
1029 It returns an array of records, each of which contains a C<value> field.
1030  
1031 See also: L</addComment>, L</getJournalEntries>
1032  
1033 B<Example>
1034  
1035 my @comments = $incident_tbl->getComments($sys_id);
1036 foreach my $comment (@comments) {
1037 print $comment->{value}, "\n";
1038 }
1039
1040 =cut
1041  
1042 sub getComments {
1043 0 ▶ my ($self, $sysid) = @_;
Subroutine getComments: not called CC=1 SCAR=6.9
1044 0 return $self->getJournalEntries($sysid, 'comments');
1045 }
1046  
1047 =head2 getJournalEntries
1048  
1049 This method retrieves journal fields
1050 (I<i.e.> Work Notes, Comments) for a ticket.
1051  
1052 See also: L</getComments>, L</getWorkNotes>
1053  
1054 B<Syntax>
1055  
1056 @notes = $table->getJournalEntries($sys_id, $fieldname);
1057
1058 B<Example>
1059  
1060 my @notes = $incident_tbl->getJournalEntries($sys_id, 'work_notes');
1061 foreach my $note (@notes) {
1062 print $note->{value}, "\n";
1063 }
1064
1065 =cut
1066  
1067 sub getJournalEntries {
1068 0 ▶ my ($self, $sysid, $fieldname) = @_;
Subroutine getJournalEntries: not called CC=3 SCAR=24.8
1069 0 my $session = $self->{session};
1070 0 my $sys_journal_field = $session->private('sys_journal_field');
1071 0 ▶ $fieldname = 'work_notes' unless $fieldname;
Branch: 1 branch
BranchTrueFalseTotal
unless $fieldname 0 0 0
1072 0 my @params = (element_id => $sysid);
1073 0 ▶ push @params, 'element' => $fieldname if $fieldname;
Branch: 1 branch
BranchTrueFalseTotal
if $fieldname 0 0 0
1074 0 push @params, '__limit' => 1000;
1075 0 my @recs = $sys_journal_field->getRecords(@params);
1076 0 return @recs;
1077 }
1078  
1079 =head2 getKeys
1080  
1081 This method returns a list of keys.
1082  
1083 Note that this method returns a list of keys, B<NOT> a comma delimited string.
1084  
1085 For additional information on available parameters
1086 refer to the ServiceNow documentation on the
1087 L<"getKeys" Direct SOAP API method|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API#getKeys>.
1088  
1089 B<Syntax>
1090  
1091 @keys = $table->getKeys(%parameters);
1092 @keys = $table->getKeys($encodedquery);
1093  
1094 B<Examples>
1095  
1096 my $cmdb_ci_computer = $sn->table("cmdb_ci_computer");
1097
1098 my @keys = $cmdb_ci_computer->getKeys(operational_status => 1, virtual => "false");
1099 # or
1100 my @keys = $cmdb_ci_computer->getKeys("operational_status=1^virtual=false");
1101
1102 =cut
1103  
1104 sub getKeys {
1105 0 ▶ my $self = shift;
Subroutine getKeys: not called CC=1 SCAR=6.9
1106 0 $self->traceBefore('getKeys');
1107 0 my $som = $self->callMethod('getKeys', _params(@_));
1108 0 my @keys = split /,/, $som->result;
1109 0 my $count = @keys;
1110 0 $self->traceAfter("$count keys");
1111 0 return @keys;
1112 }
1113  
1114 =head2 getRecord
1115  
1116 This method returns a single qualifying records.
1117 The method returns null if there are no qualifying records.
1118 The method will B<die> if there are multiple qualifying records.
1119  
1120 This method is typically used to retrieve a record
1121 based on number or name.
1122  
1123 B<Syntax>
1124  
1125 $rec = $table->getRecord(%parameters);
1126 $rec = $table->getRecord($encodedquery);
1127
1128 B<Example>
1129  
1130 This example retrieves a B<change_request> record based on B<number>.
1131  
1132 my $chgRec = $sn->table("change_request")->getRecord(number => $number);
1133 if ($chgRec) {
1134 print "Short description = ", $chgRec->{short_description}, "\n";
1135 }
1136 else {
1137 print "$number not found\n";
1138 }
1139  
1140 The following two equivalent examples
1141 illustrate the relationship between
1142 L</getRecord> and L</getRecords>.
1143  
1144 my @recs = $table->getRecords(%parameters);
1145 die "Too many records" if scalar(@recs) > 1;
1146 my $rec = $recs[0];
1147  
1148 my $rec = $table->getRecord(%parameters);
1149  
1150 =cut
1151  
1152 sub getRecord {
1153 0 ▶ my $self = shift;
Subroutine getRecord: not called CC=2 SCAR=17.9
1154 0 my $tablename = $self->{name};
1155 0 my @recs = $self->getRecords(@_);
1156 0 ▶ Carp::croak("get $tablename: multiple records returned") if @recs > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @recs > 1 0 0 0
1157 0 return $recs[0];
1158 }
1159  
1160 =head2 getRecords
1161  
1162 This method returns a list of records. Actually, it returns a list of hash references.
1163 You may pass this method either a single encoded query string,
1164 or a list of name/value pairs.
1165  
1166 For additional information on available parameters
1167 refer to the ServiceNow documentation on the
1168 L<"getRecords" Direct SOAP API method|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API#getRecords>.
1169  
1170 B<Important Note>: This method will return at most 250 records, unless
1171 you specify a C<__limit> parameter as documented in the ServiceNow wiki under
1172 L<Extended Query Parameters|http://wiki.servicenow.com/index.php?title=Direct_Web_Services#Extended_Query_Parameters>.
1173 For reading large amounts of data,
1174 it is recommended that you use the
1175 L<Query Object|/ServiceNow::SOAP::Query>
1176 described below.
1177  
1178 B<Syntax>
1179  
1180 @recs = $table->getRecords(%parameters);
1181 @recs = $table->getRecords($encodedquery);
1182  
1183 B<Example>
1184  
1185 my $sys_user_group = $sn->table("sys_user_group");
1186 my @grps = $sys_user_group->getRecords(
1187 active => true, __limit => 500, __order_by => "name");
1188 foreach my $grp (@grps) {
1189 print $grp->{name}, "\n";
1190 }
1191
1192 =cut
1193  
1194 sub getRecords {
1195 1 ▶ my $self = shift;
Subroutine getRecords: called CC=5 SCAR=30.8
1196 1 $self->traceBefore('getRecords');
1197 1 my $som = $self->callMethod('getRecords', _params(@_));
1198 0 my $response = $som->body->{getRecordsResponse};
1199 0 ▶ unless (ref $response eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $response eq "HASH") 0 0 0
1200 0 $self->traceAfter("0 records");
1201 0 return ();
1202 }
1203 0 my $result = $response->{getRecordsResult};
1204 0 my $type = ref($result);
1205 0 ▶ die "getRecords: Unexpected $type"
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "ARRAY" or $type eq "HASH" 0 0 0
Condition0%0/3
$type eq "ARRAY" or $type eq "HASH"
l!l&&r!l&&!r
000
MC/DC0%0/2
$type eq "ARRAY" or $type eq "HASH"
$type eq "ARRAY" $type eq "HASH"
Truth table0%0/3
A or B
A= $type eq "ARRAY"B= $type eq "HASH"
ABresult
1X1
011
000
1206 unless ($type eq 'ARRAY' || $type eq 'HASH');
1207 0 ▶ my @records = ($type eq 'ARRAY') ? @{$result} : ($result);
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'ARRAY' ? : 0 0 0
1208 0 my $count = @records;
1209 0 $self->traceAfter("$count records");
1210 0 return @records;
1211 }
1212  
1213 =head2 getName
1214  
1215 This method returns the name of this table from L</table>.
1216  
1217 =cut
1218  
1219 sub getName {
1220 0 ▶ return shift->{name};
Subroutine getName: not called CC=1 SCAR=6.9
1221 }
1222  
1223 =head2 getVariables
1224  
1225 This method returns a list of hashes
1226 of the variables attached to a Requested Item (RITM).
1227  
1228 B<Note>: This function currently works only for the C<sc_req_item> table.
1229 This function requires read access to the three tables
1230 C<item_option_new>,
1231 C<sc_item_option> and
1232 C<sc_item_option_mtom>.
1233  
1234 Each hash contains the following four fields:
1235  
1236 =over
1237  
1238 =item *
1239  
1240 name - Name of the variable.
1241  
1242 =item *
1243  
1244 question - The question text.
1245  
1246 =item *
1247  
1248 reference - If the variable is a reference, then the name of the table.
1249 Otherwise blank.
1250  
1251 =item *
1252  
1253 value - Value of the question response.
1254 If the variable is a reference, then value will contain a sys_id.
1255  
1256 =item *
1257  
1258 order - Order (useful for sorting).
1259  
1260 =back
1261  
1262 B<Syntax>
1263  
1264 $sc_req_item = $sn->table("sc_req_item");
1265 @vars = $sc_req_item->getVariables($sys_id);
1266
1267 B<Example>
1268  
1269 my $sc_req_item = $sn->table("sc_req_item");
1270 my $ritmRec = $sc_req_item->getRecord(number => $ritm_number);
1271 my @vars = $sc_req_item->getVariables($ritmRec->{sys_id});
1272 foreach my $var (sort { $a->{order} <=> $b->{order} } @vars) {
1273 my $name = $var->{name};
1274 my $value = $var->{value};
1275 print "$name = $value\n";
1276 }
1277  
1278 =cut
1279  
1280 sub getVariables {
1281 0 ▶ my $self = shift;
Subroutine getVariables: not called CC=5 SCAR=34.0
1282 0 ▶ Carp::croak "getVariables: invalid table" unless $self->{name} eq 'sc_req_item';
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"name"} eq "sc_req_item" 0 0 0
1283 0 my $sysid = shift;
1284 0 ▶ Carp::croak "getVariables: invalid sys_id: $sysid" unless _isGUID($sysid);
Branch: 1 branch
BranchTrueFalseTotal
unless _isGUID($sysid) 0 0 0
1285 0 my $session = $self->{session};
1286 0 my $sc_item_option = $session->private('sc_item_option');
1287 0 my $sc_item_option_mtom = $session->private('sc_item_option_mtom');
1288 0 my $item_option_new = $session->private('item_option_new');
1289 0 my @vmtom = $sc_item_option_mtom->getRecords('request_item', $sysid);
1290 0 my $vrefkeys = join ',', map { $_->{sc_item_option} } @vmtom;
1291 0 my @vref = $sc_item_option->getRecords('sys_idIN' . $vrefkeys);
1292 0 my $vvalkeys = join ',', map { $_->{item_option_new} } @vref;
1293 0 my @vval = $item_option_new->getRecords('sys_idIN' . $vvalkeys);
1294 0 my %vvalhash = map { $_->{sys_id} => $_ } @vval;
1295 0 my @result;
1296 0 foreach my $v (@vref) {
1297 0 ▶ next unless _isGUID($v->{item_option_new});
Branch: 1 branch
BranchTrueFalseTotal
unless _isGUID($v->{"item_option_new"}) 0 0 0
1298 0 my $n = $vvalhash{$v->{item_option_new}};
1299 my $var = {
1300 name => $n->{name},
1301 reference => $n->{reference},
1302 question => $n->{question_text},
1303 value => $v->{value},
1304 order => $n->{order}
1305 0 };
1306 0 push @result, $var;
1307 }
1308 0 return @result;
1309 }
1310  
1311 =head2 getWorkNotes
1312  
1313 This method retrieves all work notes for a task.
1314 It returns an array of records, each of which contains a C<value> field.
1315  
1316 See also: L</addWorkNote>, L</getJournalEntries>
1317  
1318 B<Example>
1319  
1320 my @notes = $incident_tbl->getWorkNotes($sys_id);
1321 foreach my $note (@notes) {
1322 print $note->{value}, "\n";
1323 }
1324
1325 =cut
1326  
1327 sub getWorkNotes {
1328 0 ▶ my ($self, $sysid) = @_;
Subroutine getWorkNotes: not called CC=1 SCAR=6.9
1329 0 return $self->getJournalEntries($sysid, 'work_notes');
1330 }
1331  
1332 =head2 insert
1333  
1334 This method inserts a record.
1335 In a scalar context, this method returns a sys_id only.
1336 In a list context, this method returns a list of name/value pairs.
1337  
1338 For information on available parameters
1339 refer to the ServiceNow documentation on the
1340 L<"insert" Direct SOAP API method|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API#insert>.
1341  
1342 B<Syntax>
1343  
1344 $sys_id = $table->insert(%values);
1345 %result = $table->insert(%values);
1346
1347 B<Examples>
1348  
1349 my $incident_tbl = $sn->table("incident");
1350  
1351 In a scalar context, the function returns a sys_id.
1352  
1353 my $sys_id = $incident_tbl->insert(
1354 short_description => $short_description,
1355 assignment_group => "Network Support",
1356 impact => 3);
1357 print "sys_id=", $sys_id, "\n";
1358  
1359 In a list context, the function returns a list of name/value pairs.
1360  
1361 my %result = $incident_tbl->insert(
1362 short_description => $short_description,
1363 assignment_group => "Network Support",
1364 impact => 3);
1365 print "number=", $result{number}, "\n";
1366 print "sys_id=", $result{sys_id}, "\n";
1367  
1368 You can also call it this way:
1369  
1370 my %rec;
1371 $rec{short_description} = $short_description;
1372 $rec{assignment_group} = "Network Support";
1373 $rec{impact} = 3;
1374 my $sys_id = $incident_tbl->insert(%rec);
1375  
1376 Note that for reference fields (e.g. assignment_group, assigned_to)
1377 you may pass in either a sys_id or a display value.
1378  
1379 =cut
1380  
1381 sub insert {
1382 0 ▶ my $self = shift;
Subroutine insert: not called CC=2 SCAR=17.9
1383 0 $self->traceBefore('insert');
1384 0 my $som = $self->callMethod('insert', _params(@_));
1385 0 my $response = $som->body->{insertResponse};
1386 0 my $sysid = $response->{sys_id};
1387 0 $self->traceAfter();
1388 0 ▶ return wantarray ? %{$response} : $sysid;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
1389 }
1390  
1391 =head2 insertMultiple
1392  
1393 This method inserts multiple records.
1394 The input is an array of hash references.
1395 It returns an array of hash references.
1396  
1397 This method requires installation of the
1398 L<ServiceNow Insert Multiple Web Services Plugin|http://wiki.servicenow.com/index.php?title=Web_Service_Import_Sets#Inserting_Multiple_Records>.
1399  
1400 For additional information
1401 refer to the ServiceNow documentation on the
1402 L<"insertMultiple" Direct SOAP API method|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API#insertMultiple>.
1403  
1404 B<Syntax>
1405  
1406 @results = $table->insertMultiple(@records);
1407  
1408 B<Example>
1409  
1410 my $incident_tbl = $sn->table("incident");
1411 my @allrecs;
1412 foreach my $descr (@descriptions) {
1413 my $newrec = {
1414 short_description => $desc,
1415 assignment_group => $groupName,
1416 description => $desc,
1417 impact => 3};
1418 push @allrecs, $newrec;
1419 }
1420 my @results = $incident_tbl->insertMultiple(@allrecs);
1421 foreach my $result (@results) {
1422 print "inserted ", $result->{number}, "\n";
1423 }
1424  
1425 =cut
1426  
1427 sub insertMultiple {
1428 0 ▶ my $self = shift;
Subroutine insertMultiple: not called CC=3 SCAR=24.8
1429 0 $self->traceBefore('insertMultiple');
1430 0 my @params;
1431 0 foreach my $rec (@_) {
1432 0 ▶ Carp::croak "Expected array of hashs" unless ref $rec eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rec eq "HASH" 0 0 0
1433 0 push @params, SOAP::Data->name('record' => $rec);
1434 }
1435 0 my $som = $self->callMethod('insertMultiple', @params);
1436 0 my $response = $som->body->{insertMultipleResponse};
1437 0 my $insertResponse = $response->{insertResponse};
1438 0 my @status = @{$insertResponse};
1439 0 my $count = scalar(@status);
1440 0 $self->traceAfter("$count records inserted");
1441 0 return @status;
1442 }
1443  
1444 =head2 query
1445  
1446 This method creates a new L<Query|/ServiceNow::SOAP::Query> object
1447 by calling L</getKeys>.
1448 You can then use L</fetch> or L</fetchAll>
1449 to retrieve the actual record.
1450  
1451 This method normally fetches all keys using a single
1452 call to L</getKeys>.
1453 However, if the number of keys is too large you may
1454 encounter timeout errors. In this situation the recommendation
1455 is to fetch the keys in chunks by specifying
1456 a C<query> option in the L</ServiceNow> function.
1457 The suggested initial setting is C<query =E<gt> 100000>.
1458 If timeouts are still a problem then reduce the value further.
1459  
1460 B<Syntax>
1461  
1462 $query = $table->query(%parameters);
1463 $query = $table->query($encodedquery);
1464
1465 B<Example>
1466  
1467 The following example builds a list of all Incidents
1468 created between 1/1/2014 and 2/1/2014 sorted by creation date/time.
1469 The L</fetchAll> method fetches chunks of records
1470 until all records have been retrieved.
1471  
1472 my $filter = "sys_created_on>=2014-01-01^sys_created_on<2014-02-01";
1473 my $qry = $sn->table("incident")->query(
1474 __encoded_query => $filter,
1475 __order_by => "sys_created_on");
1476 my @recs = $qry->fetchAll();
1477  
1478 The following example retrieves all keys for the C<cmdb_ci>
1479 table in chunks of 100,000 at a time.
1480  
1481 my $sn = ServiceNow($instance, $user, $pass, query => 100000);
1482 my $cmdb_ci_tbl = $sn->table("cmdb_ci");
1483 my $qry = $cmdb_ci_tbl->query();
1484  
1485 =cut
1486  
1487 sub query {
1488 0 ▶ my $table = shift;
Subroutine query: not called CC=6 SCAR=37.4
1489 0 my $session = $table->{session};
1490 0 my $limit = $session->{query};
1491 0 my $query = ServiceNow::SOAP::Query->new($table);
1492 # if there is a single parameter it must be an encoded query
1493 0 ▶ if (@_ == 1) { unshift @_, '__encoded_query' };
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1) 0 0 0
1494 0 my %params = @_;
1495 0 my @keys;
1496 0 ▶ if ($limit) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit) { } 0 0 0
1497 0 my $first = 0;
1498 0 my $last = $limit;
1499 0 ▶ while ($first <= @keys) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first <= @keys) 0 0 0
1500 0 my %p = %params;
1501 0 $p{__first_row} = $first;
1502 0 $p{__last_row} = $last;
1503 0 my @k = $table->getKeys(%p);
1504 0 push @keys, @k;
1505 0 $first += $limit;
1506 0 $last = $first + $limit;
1507 }
1508 }
1509 else {
1510 0 @keys = $table->getKeys(%params);
1511 }
1512 # parameters which affect order or columns must be preserved
1513 # so that they can be passed to getRecords
1514 0 for my $k (keys %params) {
1515 0 ▶ delete $params{$k} unless $k =~ /^(__order|__exclude|__use_view)/;
Branch: 1 branch
BranchTrueFalseTotal
unless $k =~ /^(__order|__exclude|__use_view)/ 0 0 0
1516 }
1517 0 $query->{keys} = \@keys;
1518 0 $query->{count} = scalar(@keys);
1519 0 $query->{params} = \%params;
1520 0 $query->{index} = 0;
1521 0 return $query;
1522 }
1523  
1524 =head2 setDV
1525  
1526 Used to enable (or disable) display values in queries.
1527 All subsequent calls to L</get>, L</getRecords> or L</getRecord>
1528 for this table will be affected.
1529 This method returns the modified Table object.
1530  
1531 For additional information regarding display values refer to the ServiceNow documentation on
1532 L<"Return Display Value for Reference Variables"|http://wiki.servicenow.com/index.php?title=Direct_Web_Services#Return_Display_Value_for_Reference_Variables>.
1533  
1534 B<Syntax>
1535  
1536 $table->setDv(""); # return sys_id only (default)
1537 $table->setDV("true"); # return display value instead of sys_id
1538 $table->setDV("all"); # return both sys_id and display value
1539 $table->setDV(0); # same as ""
1540 $table->setDV(1); # same as "true"
1541 $table->setDV(2); # same as "all"
1542  
1543 B<Examples>
1544  
1545 C<setDV("true")> causes display values to be returned
1546 for all fields instead of original values.
1547  
1548 my $sys_user_group = $sn->table("sys_user_group")->setDV("true");
1549 my $grp = $sys_user_group->getRecord(name => "Network Support");
1550 print "manager=", $grp->{manager}, "\n";
1551  
1552 C<setDV("all")> causes display values to be returned
1553 in addition to original values.
1554 Display value fields have a "dv_" prefix.
1555  
1556 my $sys_user_group = $sn->table("sys_user_group")->setDV("all");
1557 my $grp = $sys_user_group->getRecord(name => "Network Support");
1558 print "manager=", $grp->{dv_manager}, "\n";
1559  
1560 Note that L</setDV> is a Table method, B<not> a Query method.
1561  
1562 @recs = $table->setDV(1)->query()->fetchAll(); # Correct
1563 @recs = $table->query()->setDV(1)->fetchAll(); # INCORRECT!
1564
1565 =cut
1566  
1567 sub setDV {
1568 0 ▶ my ($self, $dv) = @_;
Subroutine setDV: not called CC=4 SCAR=30.0
1569 0 ▶ if ($dv eq '0') { $dv = '' }
Branch: 3 branches
BranchTrueFalseTotal
if ($dv eq '0') { } 0 0 0
elsif ($dv eq '1') { } 0 0 0
elsif ($dv eq '2') { } 0 0 0
1570 0 elsif ($dv eq '1') { $dv = 'true' }
1571 0 elsif ($dv eq '2') { $dv = 'all' };
1572 0 $self->{dv} = $dv;
1573 0 return $self;
1574 }
1575  
1576 sub getSession {
1577 0 ▶ return $_[0]->{session};
Subroutine getSession: not called CC=1 SCAR=6.9
1578 }
1579  
1580 sub setTrace {
1581 0 ▶ my ($self, $trace) = @_;
Subroutine setTrace: not called CC=1 SCAR=6.9
1582 0 $self->{trace} = $trace;
1583 0 return $self;
1584 }
1585  
1586 sub getSchema {
1587 0 ▶ my $self = shift;
Subroutine getSchema: not called CC=3 SCAR=24.8
1588 0 ▶ return $self->{wsdl} if $self->{wsdl};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"wsdl"} 0 0 0
1589 0 my $session = $self->{session};
1590 0 my $user = $session->{user};
1591 0 my $pass = $session->{pass};
1592 0 my $baseurl = $session->{url};
1593 0 my $host = $baseurl; $host =~ s!^https?://!!;
1594 0 my $useragent = LWP::UserAgent->new();
1595 0 $useragent->credentials("$host:443", "Service-now", $user, $pass);
1596 0 my $tablename = $self->{name};
1597 0 $self->traceBefore('wsdl');
1598 0 my $response = $useragent->get("$baseurl/$tablename.do?WSDL");
1599 0 ▶ die $response->status_line unless $response->is_success;
Branch: 1 branch
BranchTrueFalseTotal
unless $response->is_success 0 0 0
1600 0 $self->traceAfter('', $response->content);
1601 0 my $wsdl = XML::Simple::XMLin($response->content);
1602 0 $self->{wsdl} = $wsdl;
1603 0 return $wsdl;
1604 }
1605  
1606 sub getFields {
1607 0 ▶ my ($self, $schematype) = @_;
Subroutine getFields: not called CC=2 SCAR=17.9
1608 0 my $wsdl = $self->getSchema();
1609 0 ▶ $schematype = 'getResponse' unless $schematype;
Branch: 1 branch
BranchTrueFalseTotal
unless $schematype 0 0 0
1610 my $elements = $wsdl->
1611 {'wsdl:types'}{'xsd:schema'}{'xsd:element'}{$schematype}
1612 0 {'xsd:complexType'}{'xsd:sequence'}{'xsd:element'};
1613 0 my %result = map { $_ => $elements->{$_}{'type'} } keys %{$elements};
1614 0 return %result;
1615 }
1616  
1617
1618 =head2 update
1619  
1620 This method updates a record.
1621 For information on available parameters
1622 refer to the ServiceNow documentation on the
1623 L<"update" Direct SOAP API method|http://wiki.servicenow.com/index.php?title=SOAP_Direct_Web_Service_API#update>.
1624  
1625 B<Syntax>
1626  
1627 $table->update($sys_id, %parameters);
1628 $table->update(%parameters);
1629  
1630 Note:
1631 If the first syntax is used, then the C<sys_id>
1632 must be the first parameter.
1633 If the second syntax is used,
1634 then the C<sys_id> must be included among the parameters.
1635  
1636 For reference fields (I<e.g.> assignment_group, assigned_to)
1637 you may pass in either a sys_id or a display value.
1638  
1639 B<Examples>
1640  
1641 The following three examples are equivalent.
1642  
1643 $incident_tbl->update(
1644 sys_id => $sys_id,
1645 assigned_to => "5137153cc611227c000bbd1bd8cd2005",
1646 incient_state => 2);
1647
1648 $incident_tbl->update(
1649 sys_id => $sys_id,
1650 assigned_to => "Fred Luddy",
1651 incident_state => 2);
1652
1653 $incident_tbl->update($sys_id,
1654 assigned_to => "Fred Luddy",
1655 incident_state => 2);
1656  
1657 =cut
1658  
1659 sub update {
1660 0 ▶ my $self = shift;
Subroutine update: not called CC=2 SCAR=17.9
1661 0 ▶ if (_isGUID($_[0])) { unshift @_, 'sys_id' };
Branch: 1 branch
BranchTrueFalseTotal
if (_isGUID($_[0])) 0 0 0
1662 0 my %values = @_;
1663 0 my $sysid = $values{sys_id};
1664 0 $self->traceBefore("update");
1665 0 my $som = $self->callMethod('update', _params(@_));
1666 0 $self->traceAfter();
1667 0 return $self;
1668 }
1669  
1670 package ServiceNow::SOAP::Query;
1671  
1672 =head1 ServiceNow::SOAP::Query
1673
1674 Query objects and the related functions implement the ServiceNow's
1675 L<best practice recommendation|http://wiki.servicenow.com/index.php?title=Web_Services_Integrations_Best_Practices#Queries>
1676 for using Web Services to retrieve a large number of records.
1677  
1678 A Query object is essentially a list of keys (sys_ids) for a particular table,
1679 and a pointer to the current position in that list. To construct a new Query object use the L</query> or L</asQuery> Table method.
1680  
1681 =over
1682  
1683 =item *
1684  
1685 L</query> makes a Web Services call (L</getKeys>) to retrieve a list of keys.
1686  
1687 =item *
1688  
1689 L</asQuery> simply converts an exsiting list of keys into a Query object.
1690  
1691 =back
1692  
1693 Once the Query is constructed, the L</fetch> and L</fetchAll> functions
1694 can be used to get the actual records in chunks.
1695  
1696 B<Example>
1697  
1698 This example illustrates the use of Query objects to traverse
1699 the C<cmdb_rel_ci> table.
1700 The example involves two tables:
1701 C<cmdb_ci> and C<cmdb_rel_ci>.
1702  
1703 my $cmdb_ci_tbl = $sn->table("cmdb_ci");
1704 my $cmdb_rel_ci_tbl = $sn->table("cmdb_rel_ci");
1705
1706 We assume that C<$parentKey> is the sys_id of a known configuration item.
1707 The objective is to print a list of all other configuration items
1708 on which this item immediately depends.
1709 In otherwords, all items which are one level downstream.
1710  
1711 First we query C<cmdb_rel_ci> to retrieve a list of
1712 records for which this item is the parent.
1713 C<@relData> is this list of C<cmdb_rel_ci> records.
1714 If there are more than 250 records, C<fetchAll> will loop internally
1715 until all records have been retrieved.
1716  
1717 my @relData = $cmdb_rel_ci_tbl->query(parent => $parentKey)->fetchAll();
1718  
1719 Next we extract the C<child> field from each of these C<cmdb_rel_ci>
1720 records to create a new list of sys_ids.
1721  
1722 my @childKeys = map { $_->{child} } @relData;
1723  
1724 C<@childKeys> now contains a lists of sys_ids for configuration items.
1725 We convert this list of keys into a query object
1726 and fetch the records from the C<cmdb_ci> table.
1727
1728 @childRecs = $cmdb_ci_tbl->asQuery(@childKeys)->fetchAll();
1729 foreach my $childRec (@childRecs) {
1730 print $childRec->{name}, "\n";
1731 }
1732  
1733 =cut
1734  
1735 sub new {
1736 0 ▶ my ($pkg, $table) = @_;
Subroutine new: not called CC=1 SCAR=6.9
1737 0 my $session = $table->{session};
1738 0 return bless {
1739 table => $table,
1740 count => 0,
1741 index => 0
1742 }, $pkg;
1743 }
1744  
1745 =head2 exclude
1746  
1747 This method will affect any subsequent calls to L</fetch>.
1748 Any columns not specified in the argument(s)
1749 will be excluded from the returned result.
1750 By excluding unneeded columns from the query result,
1751 it is possible to significantly improve the performance of large queries.
1752 For a simpler way to achieve this objective, refer to the L</include> method below.
1753  
1754 You may pass this method either a list of column names,
1755 or a string containing a comma delimited list of names.
1756 It will override any prior calls to L</exclude> or L</include>.
1757 It returns a reference to the modified Query object.
1758  
1759 See also: L</except>, L</include>
1760  
1761 B<Syntax>
1762  
1763 $query->exclude(@list_of_columns);
1764 $query->exclude($comma_delimited_list_of_columns);
1765
1766 =cut
1767  
1768 sub exclude {
1769 0 ▶ my $self = shift;
Subroutine exclude: not called CC=1 SCAR=6.9
1770 0 my $table = $self->{table};
1771 0 my $excl = join(',', @_);
1772 0 $self->{params}{__exclude_columns} = $excl;
1773 0 return $self;
1774 }
1775  
1776 =head2 fetch
1777  
1778 Fetch the next chunk of records from a table.
1779 Returns a list of hash references.
1780  
1781 This method calls L</getRecords> to retrieve the records.
1782 An optional parameter allows specification of the number of records to be retrieved.
1783 If not specified, then the number of records will be based on
1784 the default chunk size for this Query object.
1785 If there are no remaining records, then an empty list will be returned.
1786  
1787 B<Syntax>
1788
1789 @recs = $query->fetch();
1790 @recs = $query->fetch($numrecs);
1791  
1792 B<Example>
1793  
1794 This example prints the names of all active users.
1795 Each call to L</getRecords> returns up to 100 users.
1796  
1797 my $sys_user = $sn->table("sys_user);
1798 $sys_user->query(active => "true", __order_by => "name");
1799 while (@recs = $query->fetch(100)) {
1800 foreach my $rec (@recs) {
1801 print $rec->{name}, "\n";
1802 }
1803 }
1804  
1805 =cut
1806  
1807 sub fetch {
1808 0 ▶ my ($self, $chunk) = @_;
Subroutine fetch: not called CC=5 SCAR=34.0
1809 0 my $table = $self->{table};
1810 0 my $session = $table->{session};
1811 0 ▶ $chunk = $session->{fetch} unless $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless $chunk 0 0 0
1812 0 my @result;
1813 0 my $first = $self->{index};
1814 0 my $count = $self->{count};
1815 0 ▶ if ($first < $count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first < $count) 0 0 0
1816 0 my $last = $first + $chunk - 1;
1817 0 my %params = %{$self->{params}};
1818 0 ▶ $params{__limit} = $chunk if $chunk;
Branch: 1 branch
BranchTrueFalseTotal
if $chunk 0 0 0
1819 0 ▶ $last = $count - 1 if $last >= $count;
Branch: 1 branch
BranchTrueFalseTotal
if $last >= $count 0 0 0
1820 0 my $encodedquery = "sys_idIN" . join(",", @{$self->{keys}}[$first .. $last]);
1821 0 @result = $table->getRecords(__encoded_query => $encodedquery, %params);
1822 0 $self->{index} = $last + 1;
1823 }
1824 0 return @result;
1825 }
1826  
1827 =head2 fetchAll
1828  
1829 This method fetches all the records in a Query by calling L</fetch> repeatedly
1830 until there are no more records.
1831 It takes an optional argument which is the number of records
1832 to be retrieved B<per fetch>.
1833 It returns a list of hash references.
1834  
1835 B<Syntax>
1836  
1837 @recs = $query->fetchAll();
1838 @recs = $query->fetchAll($numrecs);
1839
1840 B<Example>
1841  
1842 This example prints the names of all active users.
1843 Each call to L</getRecords> returns up to 250 records
1844 since no fetch size was specified and 250 is the default.
1845  
1846 my $sys_user = $sn->table("sys_user);
1847 my @recs = $sys_user->query(active => "true", __order_by => "name")->fetchAll();
1848 foreach my $rec (@recs) {
1849 print $rec->{name}, "\n";
1850 }
1851  
1852 =cut
1853  
1854 sub fetchAll {
1855 0 ▶ my ($self, $chunk) = @_;
Subroutine fetchAll: not called CC=2 SCAR=17.9
1856 0 my @result = ();
1857 0 ▶ while (my @recs = $self->fetch($chunk)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@recs) = $self->fetch($chunk)) 0 0 0
1858 0 push @result, @recs;
1859 }
1860 0 return @result;
1861 }
1862  
1863 =head2 getCount
1864  
1865 This method returns the total number of keys in the Query.
1866  
1867 =cut
1868  
1869 sub getCount {
1870 0 ▶ my $self = shift;
Subroutine getCount: not called CC=1 SCAR=6.9
1871 0 return $self->{count};
1872 }
1873  
1874 =head2 getKeys
1875  
1876 This method returns a list of the keys included in the Query.
1877  
1878 B<Example>
1879  
1880 The following example calls L</getKeys> to create a new query,
1881 and then makes of copy of the query using the same list of keys.
1882  
1883 my $query1 = $table->query($encoded_query);
1884 my $query2 = $table->asQuery($query1->getKeys());
1885  
1886 =cut
1887  
1888 sub getKeys {
1889 0 ▶ my $self = shift;
Subroutine getKeys: not called CC=1 SCAR=6.9
1890 0 return @{$self->{keys}};
1891 }
1892  
1893 =head2 include
1894  
1895 This method will affect any subsequent calls to L</fetch>
1896 by limiting which columns are returned.
1897 This method utilizes the L</except> method documented above.
1898 By including only the needed columns in the query result,
1899 it is possible to significantly improve the performance of large queries.
1900  
1901 You may pass this method either a list of column names,
1902 or a string containing a comma delimited list of names.
1903 It will override any prior calls to L</exclude> or L</include>.
1904 It returns a reference to the modified Query object.
1905  
1906 For some reason the Direct Web Services API allows you to specify a
1907 list of columns to be excluded from the query result,
1908 but there is no similar out-of-box capability
1909 to specify only the columns to be included.
1910 This function implements the more obviously needed behavior
1911 by inverting the list.
1912 It uses the WSDL to generate a list of columns returned by L</getRecords>,
1913 and subtracts the specified names to create an C<"__exclude_columns">
1914 extended query parameter.
1915  
1916 See also: L</except>, L</exclude>
1917  
1918 B<Syntax>
1919  
1920 $query->include(@list_of_columns);
1921 $query->include($comma_delimited_list_of_columns);
1922
1923 B<Example>
1924  
1925 This example returns a list of all records in the C<cmdb_ci_computer> table,
1926 but only 5 columns are returnd.
1927  
1928 my $tbl = $sn->table("cmdb_ci_computer");
1929 my $qry = $tbl->query()->include(
1930 qw(sys_id name sys_class_name operational_status sys_updated_on));
1931 my @recs = $qry->fetchAll();
1932  
1933 =cut
1934  
1935 sub include {
1936 0 ▶ my $self = shift;
Subroutine include: not called CC=1 SCAR=6.9
1937 0 my $table = $self->{table};
1938 0 my $excl = $table->except(split /,/, join(',', @_));
1939 0 $self->exclude($excl);
1940 0 return $self;
1941 }
1942  
1943 sub setIndex {
1944 0 ▶ my $self = shift;
Subroutine setIndex: not called CC=1 SCAR=6.9
1945 0 $self->{index} = shift;
1946 0 return $self;
1947 }
1948  
1949 24 1;
1950  
1951 =head1 PROXY
1952  
1953 You may have trouble using the SOAP API if you are running Perl behind
1954 a proxy server.
1955 The easiest solution is to configure the proxy with environment variables
1956 as in this example.
1957  
1958 use ServiceNow::SOAP;
1959 $ENV{HTTP_PROXY} = "http://my.proxy.server";
1960 $ENV{HTTPS_PROXY} = $ENV{HTTP_PROXY};
1961 $ENV{PERL_LWP_ENV_PROXY} = 1;
1962 my $sn = ServiceNow($instance, $username, $password);
1963  
1964 This works because ServiceNow::SOAP is built on top of SOAP::Lite
1965 which is built on top of LWP.
1966 For more information refer to:
1967 L<http://search.cpan.org/dist/libwww-perl/lib/LWP.pm#ENVIRONMENT>
1968  
1969 =head1 DIAGNOSTICS
1970  
1971 Sometimes, when you are developing a new script,
1972 it seems to hang at a certain point,
1973 and you just want to know what it is doing.
1974 You can enable tracing of Web Service calls
1975 by setting the C<trace> option
1976 in the L</ServiceNow> function as follows.
1977  
1978 my $sn = ServiceNow($instance, $username, $password, trace => 1);
1979  
1980 Set trace to 1 to print a single line for each Web Services call.
1981 Set trace to 2 to print the complete XML result for each call.
1982  
1983 If you want even more, then add the following to your code.
1984 This will cause L<SOAP::Lite> to dump the HTTP headers
1985 and content for all messages, both sent and received.
1986  
1987 SOAP::Lite->import(+trace => 'debug');
1988  
1989 =head1 AUTHOR
1990  
1991 Giles Lewis <gflewis@cpan.org>
1992  
1993 =head1 ACKNOWLEDGEMENTS
1994  
1995 Greg George, author of L<ServiceNow::Simple>,
1996 from which a number of ideas were sourced.
1997  
1998 =head1 LICENSE
1999  
2000 This program is free software; you can redistribute it and/or modify it
2001 under the terms of the the Artistic License (2.0). You may obtain a
2002 copy of the full license at:
2003  
2004 L<http://www.perlfoundation.org/artistic_license_2_0>
2005  
2006 Any use, modification, and distribution of the Standard or Modified
2007 Versions is governed by this Artistic License. By using, modifying or
2008 distributing the Package, you accept this license. Do not use, modify,
2009 or distribute the Package, if you do not accept this license.
2010  
2011 If your Modified Version has been derived from a Modified Version made
2012 by someone other than you, you are nevertheless required to ensure that
2013 your Modified Version complies with the requirements of this license.
2014  
2015 This license does not grant you the right to use any trademark, service
2016 mark, tradename, or logo of the Copyright Holder.
2017  
2018 This license includes the non-exclusive, worldwide, free-of-charge
2019 patent license to make, have made, use, offer to sell, sell, import and
2020 otherwise transfer the Package with respect to any patent claims
2021 licensable by the Copyright Holder that are necessarily infringed by the
2022 Package. If you institute patent litigation (including a cross-claim or
2023 counterclaim) against any party alleging that the Package constitutes
2024 direct or contributory patent infringement, then this Artistic License
2025 to you shall terminate on the date that such litigation is filed.
2026  
2027 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
2028 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
2029 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
2030 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
2031 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
2032 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
2033 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
2034 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2035  
2036 =cut
↑ Summary