blib/lib/ServiceNow/SOAP.pm

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