blib/lib/LabKey/Query.pm

filter: Statementstmt 20.8% 46 / 221 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 38 MC/DCmcdc 0.0% 0 / 21 Subroutinesub 51.8% 14 / 27 Podpod 100% 5 / 5 totaltotal 16.6% 65 / 390 CC 59 SCAR 62.0
CC
59
Cov
14%
_readrc
1190.0
_getServerContext
72.0
selectRows
42.0
CRAP 490.5
↑ Summary
1 #!/usr/bin/perl
2  
3 =head1 NAME
4  
5 LabKey::Query - For interacting with data in LabKey Server
6  
7 =head1 SYNOPSIS
8  
9 use LabKey::Query;
10 my $results = LabKey::Query::selectRows(
11 -baseUrl => 'http://labkey.com:8080/labkey/',
12 -containerPath => 'myFolder/',
13 -schemaName => 'lists',
14 -queryName => 'mid_tags',
15 );
16
17 =head1 ABSTRACT
18  
19 For interacting with data in LabKey Server
20  
21 =head1 DESCRIPTION
22  
23 This module is designed to simplify querying and manipulating data in LabKey Server. It should more or less replicate the javascript APIs of the same names.
24  
25 After the module is installed, if you need to login with a specific user you
26 will need to create a L<.netrc|https://www.labkey.org/Documentation/wiki-page.view?name=netrc>
27 file in the home directory of the user running the perl script.
28  
29 In API versions 0.08 and later, you can specify the param '-loginAsGuest'
30 which will query the server without any credentials. The server must permit
31 guest to that folder for this to work though.
32  
33 =cut
34  
35 package LabKey::Query;
36  
37 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 6 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 6 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 6 ▶use FileHandle;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 6 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 6 ▶use File::HomeDir;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 6 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
45  
46  
47 # Force all SSL connections to use TLSv1 or greater protocol. This is required for
48 # MacOSX and older Windows workstations.
49 #
50 # Credit to @chrisrth on stackoverflow (http://stackoverflow.com/a/20305596)
51 # See https://www.labkey.org/issues/home/Developer/issues/details.view?issueId=22146
52 # for more information.
53 #
54 6 ▶use IO::Socket::SSL;
Subroutine BEGIN: called CC=1 SCAR=0.0
55 6 my $context = new IO::Socket::SSL::SSL_Context(
56 SSL_version => 'tlsv1'
57 );
58 6 IO::Socket::SSL::set_default_context($context);
59  
60 6 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
61 6 ▶use HTTP::Cookies;
Subroutine BEGIN: called CC=1 SCAR=0.0
62 6 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
63 6 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
64  
65  
66 6 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
67  
68 6 our $VERSION = "1.07";
69  
70  
71  
72 =head1 FUNCTIONS
73  
74 =head2 selectRows()
75  
76 selectRows() can be used to query data from LabKey server
77  
78 The following are the minimum required params:
79
80 my $results = LabKey::Query::selectRows(
81 -baseUrl => 'http://labkey.com:8080/labkey/',
82 -containerPath => 'myFolder/',
83 -schemaName => 'lists',
84 -queryName => 'mid_tags',
85 );
86  
87 The following are optional:
88  
89 -viewName => 'view1',
90 -filterArray => [
91 ['file_active', 'eq', 1],
92 ['species', 'neq', 'zebra']
93 ], #allows filters to be applied to the query similar to the labkey Javascript API.
94 -parameters => [
95 ['enddate', '2011/01/01'],
96 ['totalDays', 15]
97 ], #allows parameters to be applied to the query similar to the labkey Javascript API.
98 -maxRows => 10 #the max number of rows returned
99 -sort => 'ColumnA,ColumnB' #sort order used for this query
100 -offset => 100 #the offset used when running the query
101 -columns => 'ColumnA,ColumnB' #A comma-delimited list of column names to include in the results.
102 -containerFilterName => 'currentAndSubfolders'
103 -debug => 1, #will result in a more verbose output
104 -loginAsGuest => #will not attempt to lookup credentials in netrc
105 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
106 -requiredVersion => 9.1 #if 8.3 is selected, it will use LabKey's pre-9.1 format for returning the data. 9.1 is the default. See documentation of LABKEY.Query.ExtendedSelectRowsResults for more detail here:
107 https://www.labkey.org/download/clientapi_docs/javascript-api/symbols/LABKEY.Query.html
108 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
109 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
110
111 =head3 NOTE
112  
113 In version 1.0 and later of the perl API, the default result format is 9.1. This is different from the LabKey JS, which defaults to the earlier format for legacy purposes.
114  
115 =cut
116  
117 0 ▶sub selectRows {
Subroutine selectRows: not called CC=6 SCAR=37.4
Pod documented
118 0 my %args = @_;
119  
120 0 my @required = ('-queryName', '-schemaName');
121 0 _checkRequiredParams(\%args, \@required);
122  
123 0 my $ctx = _getServerContext(%args);
124  
125 my $data = {
126 'schemaName' => $args{'-schemaName'},
127 'query.queryName' => $args{'-queryName'},
128 0 ▶ 'apiVersion' => $args{'-requiredVersion'} || 9.1
Condition0%0/2
$args{'-requiredVersion'} || 9.1
l!l
00
MC/DC0%0/1
$args{'-requiredVersion'} || 9.1
$args{'-requiredVersion'}
Truth table0%0/2
A
A= $args{'-requiredVersion'}
Aresult
11
00
129 };
130  
131 0 foreach (@{$args{-filterArray}}) {
132 0 $$data{'query.' . @{$_}[0] . '~' . @{$_}[1]} = @{$_}[2];
133 }
134  
135 0 foreach (@{$args{-parameters}}) {
136 0 $$data{'query.param.' . @{$_}[0]} = @{$_}[1];
137 }
138
139 0 foreach ('viewName', 'offset', 'sort', 'maxRows', 'columns', 'containerFilterName') {
140 0 ▶ if ($args{'-' . $_}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'-' . $_}) 0 0 0
141 0 $$data{'query.' . $_} = $args{'-' . $_};
142 }
143 }
144
145 0 return _postData($ctx, _buildURL($ctx, 'query', 'getQuery.api'), $data);
146 }
147  
148  
149 =head2 insertRows()
150  
151 insertRows() can be used to insert records into a LabKey table
152  
153 The following are the minimum required params:
154  
155 my $insert = LabKey::Query::insertRows(
156 -baseUrl => 'http://labkey.com:8080/labkey/',
157 -containerPath => 'myFolder/',
158 -schemaName => 'lists',
159 -queryName => 'backup',
160 -rows => [{
161 "JobName" => 'jobName',
162 "Status" => $status,
163 "Log" => $log,
164 "Date" => $date
165 }],
166 );
167
168 The following are optional:
169  
170 -debug => 1, #will result in a more verbose output
171 -loginAsGuest => #will not attempt to lookup credentials in netrc
172 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
173 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
174 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
175  
176 =cut
177  
178 0 ▶sub insertRows {
Subroutine insertRows: not called CC=1 SCAR=6.9
Pod documented
179 0 my %args = @_;
180  
181 0 my @required = ('-queryName', '-schemaName', '-rows');
182 0 _checkRequiredParams(\%args, \@required);
183  
184 0 my $ctx = _getServerContext(%args);
185  
186 my $data = {
187 "schemaName" => $args{'-schemaName'},
188 "queryName" => $args{'-queryName'},
189 0 "rows" => $args{'-rows'}
190 };
191  
192 0 return _postData($ctx, _buildURL($ctx, 'query', 'insertRows.api'), $data);
193 }
194  
195  
196 =head2 updateRows()
197  
198 updateRows() can be used to update records in a LabKey table
199  
200 The following are the minimum required params:
201  
202 my $update = LabKey::Query::updateRows(
203 -baseUrl => 'http://labkey.com:8080/labkey/',
204 -containerPath => 'myFolder/',
205 -schemaName => 'lists',
206 -queryName => 'backup',
207 -rows => [{
208 "JobName" => 'jobName',
209 "Status" => $status,
210 "Log" => $log,
211 "Date" => $date
212 }],
213 );
214
215 The following are optional:
216  
217 -debug => 1, #will result in a more verbose output
218 -loginAsGuest => #will not attempt to lookup credentials in netrc
219 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
220 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
221 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
222  
223 =cut
224  
225 0 ▶sub updateRows {
Subroutine updateRows: not called CC=1 SCAR=6.9
Pod documented
226 0 my %args = @_;
227  
228 0 my @required = ('-queryName', '-schemaName', '-rows');
229 0 _checkRequiredParams(\%args, \@required);
230  
231 0 my $ctx = _getServerContext(%args);
232  
233 my $data = {
234 "schemaName" => $args{'-schemaName'},
235 "queryName" => $args{'-queryName'},
236 0 "rows" => $args{'-rows'}
237 };
238  
239 0 return _postData($ctx, _buildURL($ctx, 'query', 'updateRows.api'), $data);
240 }
241  
242  
243 =head2 deleteRows()
244  
245 deleteRows() can be used to delete records in a LabKey table
246  
247 The following are the minimum required params:
248  
249 my $update = LabKey::Query::deleteRows(
250 -baseUrl => 'http://labkey.com:8080/labkey/',
251 -containerPath => 'myFolder/',
252 -schemaName => 'lists',
253 -queryName => 'backup',
254 -rows => [{
255 "Key" => '12',
256 }],
257 );
258
259 The following are optional:
260  
261 -debug => 1, #will result in a more verbose output
262 -loginAsGuest => #will not attempt to lookup credentials in netrc
263 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
264 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
265 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
266  
267 =cut
268  
269 0 ▶sub deleteRows {
Subroutine deleteRows: not called CC=1 SCAR=6.9
Pod documented
270 0 my %args = @_;
271  
272 0 my @required = ('-queryName', '-schemaName', '-rows');
273 0 _checkRequiredParams(\%args, \@required);
274  
275 0 my $ctx = _getServerContext(%args);
276  
277 my $data = {
278 "schemaName" => $args{'-schemaName'},
279 "queryName" => $args{'-queryName'},
280 0 "rows" => $args{'-rows'}
281 };
282  
283 0 return _postData($ctx, _buildURL($ctx, 'query', 'deleteRows.api'), $data);
284 }
285  
286  
287 =head2 executeSql()
288  
289 executeSql() can be used to execute arbitrary SQL
290  
291 The following are the minimum required params:
292  
293 my $result = LabKey::Query::executeSql(
294 -baseUrl => 'http://labkey.com:8080/labkey/',
295 -containerPath => 'myFolder/',
296 -schemaName => 'study',
297 -sql => 'select MyDataset.foo, MyDataset.bar from MyDataset',
298 );
299
300 The following are optional:
301  
302 -maxRows => 10 #the max number of rows returned
303 -sort => 'ColumnA,ColumnB' #sort order used for this query
304 -offset => 100 #the offset used when running the query
305 -containerFilterName => 'currentAndSubfolders'
306 -debug => 1, #will result in a more verbose output
307 -loginAsGuest => #will not attempt to lookup credentials in netrc
308 -netrcFile => optional. the location of a file to use in place of a .netrc file. see also the environment variable LABKEY_NETRC.
309 -useragent => an instance of LWP::UserAgent (if not provided, a new instance will be created)
310 -timeout => timeout in seconds (used when creating a new LWP::UserAgent)
311  
312 =cut
313  
314 0 ▶sub executeSql {
Subroutine executeSql: not called CC=3 SCAR=24.8
Pod documented
315 0 my %args = @_;
316  
317 0 my @required = ('-schemaName', '-sql');
318 0 _checkRequiredParams(\%args, \@required);
319  
320 0 my $ctx = _getServerContext(%args);
321  
322 my $data = {
323 "schemaName" => $args{'-schemaName'},
324 0 "sql" => $args{'-sql'}
325 };
326
327 0 foreach ('offset', 'sort', 'maxRows', 'containerFilterName') {
328 0 ▶ if ($args{'-' . $_}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'-' . $_}) 0 0 0
329 0 $$data{$_} = $args{'-' . $_};
330 }
331 }
332
333 0 return _postData($ctx, _buildURL($ctx, 'query', 'executeSql.api'), $data);
334 }
335  
336  
337 # NOTE: this code adapted from Net::Netrc module. It was changed so alternate locations could be supplied for a .netrc file
338 0 ▶sub _readrc {
Subroutine _readrc: not called CC=34 SCAR=70.8
339  
340 0 ▶ my $host = shift || 'default';
Condition0%0/2
shift() || 'default'
l!l
00
MC/DC0%0/1
shift() || 'default'
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
341 0 my $file = shift;
342  
343 #allow user to supply netrc location
344 0 ▶ if(!$file || !-e $file){
Branch: 1 branch
BranchTrueFalseTotal
unless ($file and -e $file) 0 0 0
Condition0%0/3
$file and -e $file
!ll&&!rl&&r
000
MC/DC0%0/2
$file and -e $file
$file -e $file
Truth table0%0/3
A and B
A= $fileB= -e $file
ABresult
0X0
100
111
345 0 $file = File::Spec->catfile( File::HomeDir::home(), '.netrc' );
346 }
347 0 ▶ if ( !-e $file ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $file) 0 0 0
348 0 $file = File::Spec->catfile( File::HomeDir::home(), '_netrc' );
349 }
350  
351 0 my %netrc = ();
352 0 my $fh;
353 0 local $_;
354  
355 0 $netrc{default} = undef;
356  
357 # OS/2 and Win32 do not handle stat in a way compatable with this check :-(
358 0 ▶ unless ( $^O eq 'os2'
Branch: 1 branch
BranchTrueFalseTotal
unless ($^O eq "os2" or $^O eq "MSWin32" or $^O eq "MacOS" or $^O eq "darwin" or $^O =~ /^cygwin/) 0 0 0
Condition0%0/12
$^O eq "os2" or $^O eq "MSWin32" or $^O eq "MacOS" or $^O eq "darwin" or $^O =~ /^cygwin/
l!l&&r!l&&!r
000
$^O eq "os2" or $^O eq "MSWin32" or $^O eq "MacOS" or $^O eq "darwin"
l!l&&r!l&&!r
000
$^O eq "os2" or $^O eq "MSWin32" or $^O eq "MacOS"
l!l&&r!l&&!r
000
$^O eq "os2" or $^O eq "MSWin32"
l!l&&r!l&&!r
000
MC/DC0%0/5
$^O eq "os2" or $^O eq "MSWin32" or $^O eq "MacOS" or $^O eq "darwin" or $^O =~ /^cygwin/
$^O eq "os2" $^O eq "MSWin32" $^O eq "MacOS" $^O eq "darwin" $^O =~ /^cygwin/
Truth table0%0/6
A or B or C or D or E
A= $^O eq "os2"B= $^O eq "MSWin32"C= $^O eq "MacOS"D= $^O eq "darwin"E= $^O =~ /^cygwin/
ABCDEresult
1XXXX1
01XXX1
001XX1
0001X1
000011
000000
359 || $^O eq 'MSWin32'
360 || $^O eq 'MacOS'
361 || $^O eq 'darwin'
362 || $^O =~ /^cygwin/ )
363 {
364 0 my @stat = stat($file);
365  
366 0 ▶ if (@stat) {
Branch: 1 branch
BranchTrueFalseTotal
if (@stat) 0 0 0
367 0 ▶ if ( $stat[2] & 077 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stat[2] & 63) 0 0 0
368 0 carp "Bad permissions: $file";
369 0 return;
370 }
371 0 ▶ if ( $stat[4] != $< ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stat[4] != $<) 0 0 0
372 0 carp "Not owner: $file";
373 0 return;
374 }
375 }
376 }
377  
378 0 ▶ if ( $fh = FileHandle->new( $file, "r" ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fh = "FileHandle"->new($file, "r")) 0 0 0
379 0 my ( $mach, $macdef, $tok, @tok ) = ( 0, 0 );
380  
381 0 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 0 0 0
382 0 ▶ undef $macdef if /\A\n\Z/;
Branch: 1 branch
BranchTrueFalseTotal
if /\A\n\Z/ 0 0 0
383  
384 0 ▶ if ($macdef) {
Branch: 1 branch
BranchTrueFalseTotal
if ($macdef) 0 0 0
385 0 push( @$macdef, $_ );
386 0 next;
387 }
388  
389 0 s/^\s*//;
390 0 chomp;
391  
392 0 ▶ while ( length && s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*// )
Branch: 1 branch
BranchTrueFalseTotal
if (length $_ and s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//) 0 0 0
Condition0%0/3
length $_ and s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//
!ll&&!rl&&r
000
MC/DC0%0/2
length $_ and s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//
length $_ s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//
Truth table0%0/3
A and B
A= length $_B= s/^("((?:[^"]+|\\.)*)"|((?:[^\\\s]+|\\.)*))\s*//
ABresult
0X0
100
111
393 {
394 0 ( my $tok = $+ ) =~ s/\\(.)/$1/g;
395 0 push( @tok, $tok );
396 }
397  
398 TOKEN:
399 0 ▶ while (@tok) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tok) 0 0 0
400 0 ▶ if ( $tok[0] eq "default" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok[0] eq "default") 0 0 0
401 0 shift(@tok);
402 0 $mach = bless {};
403 0 $netrc{default} = [$mach];
404  
405 0 next TOKEN;
406 }
407  
408 last TOKEN
409 0 ▶ unless @tok > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @tok > 1 0 0 0
410  
411 0 $tok = shift(@tok);
412  
413 0 ▶ if ( $tok eq "machine" ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($tok eq 'machine') { } 0 0 0
elsif ($tok =~ /^(login|password|account)$/) { } 0 0 0
elsif ($tok eq 'macdef') { } 0 0 0
414 0 my $host = shift @tok;
415 0 $mach = { machine => $host };
416  
417 $netrc{$host} = []
418 0 ▶ unless exists( $netrc{$host} );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $netrc{$host} 0 0 0
419 0 push( @{ $netrc{$host} }, $mach );
420 }
421 elsif ( $tok =~ /^(login|password|account)$/ ) {
422 0 ▶ next TOKEN unless $mach;
Branch: 1 branch
BranchTrueFalseTotal
unless $mach 0 0 0
423 0 my $value = shift @tok;
424  
425 # Following line added by rmerrell to remove '/' escape char in .netrc
426 0 $value =~ s/\/\\/\\/g;
427 0 $mach->{$1} = $value;
428 }
429 elsif ( $tok eq "macdef" ) {
430 0 ▶ next TOKEN unless $mach;
Branch: 1 branch
BranchTrueFalseTotal
unless $mach 0 0 0
431 0 my $value = shift @tok;
432 $mach->{macdef} = {}
433 0 ▶ unless exists $mach->{macdef};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $mach->{"macdef"} 0 0 0
434 0 $macdef = $mach->{machdef}{$value} = [];
435 }
436 }
437 }
438 0 $fh->close();
439 }
440
441 0 my $auth = $netrc{$host}[0];
442  
443 #if no machine is specified and there is only 1 machine in netrc, we use that one
444 0 ▶ if (!$auth && length((keys %netrc))==1){
Branch: 1 branch
BranchTrueFalseTotal
if (not $auth and length keys %netrc == 1) 0 0 0
Condition0%0/3
not $auth and length keys %netrc == 1
!ll&&!rl&&r
000
MC/DC0%0/2
not $auth and length keys %netrc == 1
not $auth length keys %netrc == 1
Truth table0%0/3
not(A) and B
A= not $authB= length keys %netrc == 1
ABresult
0X0
100
111
445 0 $auth = $netrc{(keys %netrc)[0]}[0];
446 }
447  
448 0 ▶ warn("Unable to find entry for host: $host") unless $auth;
Branch: 1 branch
BranchTrueFalseTotal
unless $auth 0 0 0
449 0 ▶ warn("Missing password for host: $host") unless $auth->{password};
Branch: 1 branch
BranchTrueFalseTotal
unless $auth->{"password"} 0 0 0
450 0 ▶ warn("Missing login for host: $host") unless $auth->{login};
Branch: 1 branch
BranchTrueFalseTotal
unless $auth->{"login"} 0 0 0
451  
452 0 return $auth;
453 }
454  
455  
456 0 ▶sub _normalizeSlash {
Subroutine _normalizeSlash: not called CC=1 SCAR=6.9
457 0 my ($containerPath) = @_;
458
459 0 $containerPath =~ s/^\///;
460 0 $containerPath =~ s/\/$//;
461 0 $containerPath .= '/';
462 0 return $containerPath;
463 }
464  
465  
466 0 ▶sub _postData {
Subroutine _postData: not called CC=5 SCAR=34.0
467 0 my ($ctx, $url, $data) = @_;
468  
469 0 ▶ print "POST " . $url . "\n" if $$ctx{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"debug"} 0 0 0
470 0 ▶ print Dumper($data) if $$ctx{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"debug"} 0 0 0
471  
472 0 my $json_obj = JSON->new->utf8->encode($data);
473  
474 0 my $req = POST $url;
475 0 $req->content_length(length($json_obj));
476 0 $req->content_type('application/json');
477 0 $req->content($json_obj);
478 0 $req->authorization_basic($$ctx{auth}{'login'}, $$ctx{auth}{'password'});
479  
480 0 my $response = $$ctx{userAgent}->request($req);
481  
482 # Simple error checking
483 0 ▶ if ( $response->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_error) 0 0 0
484 0 croak($response->status_line . '\n' . $response->decoded_content);
485 }
486  
487 0 ▶ my $response_json = JSON->new->utf8->decode( $response->content )
Condition0%0/2
'JSON'->new->utf8->decode($response->content) || croak("ERROR: Unable to decode JSON.\n$url\n")
l!l
00
MC/DC0%0/1
'JSON'->new->utf8->decode($response->content) || croak("ERROR: Unable to decode JSON.\n$url\n")
'JSON'->new->utf8->decode($response->content)
Truth table0%0/2
A
A= 'JSON'->new->utf8->decode($response->content)
Aresult
11
00
488 || croak("ERROR: Unable to decode JSON.\n$url\n");
489
490 0 return $response_json;
491 }
492  
493 0 ▶sub _createUserAgent {
Subroutine _createUserAgent: not called CC=2 SCAR=17.9
494 0 my %args = @_;
495  
496 0 my $ua = LWP::UserAgent->new;
497 0 $ua->agent("Perl API Client/1.0");
498 0 $ua->cookie_jar(HTTP::Cookies->new());
499  
500 0 ▶ if ($args{'-timeout'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"-timeout"}) 0 0 0
501 0 print "setting timeout to " . $args{'-timeout'} . "\n";
502 0 $ua->timeout($args{'-timeout'});
503 }
504 0 return $ua;
505 }
506  
507 0 ▶sub _buildURL {
Subroutine _buildURL: not called CC=1 SCAR=6.9
508 0 my ($ctx, $controller, $action) = @_;
509  
510 return URI->new(
511 _normalizeSlash($$ctx{baseUrl})
512 . _normalizeSlash($controller)
513 . _normalizeSlash($$ctx{containerPath})
514 0 . $action
515 . '?'
516 );
517 }
518  
519 0 ▶sub _checkRequiredParams {
Subroutine _checkRequiredParams: not called CC=3 SCAR=24.8
520 0 my %args = %{$_[0]};
521 0 my @required = @{$_[1]};
522  
523 0 foreach (@required) {
524 0 ▶ if (!$args{$_}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{$_}) 0 0 0
525 0 croak("ERROR: Missing required param: $_")
526 }
527 }
528 }
529  
530 0 ▶sub _fetchCSRF {
Subroutine _fetchCSRF: not called CC=5 SCAR=34.0
531 0 my ($ctx) = @_;
532  
533 0 my $url = _buildURL($ctx, 'login', 'whoAmI.api');
534  
535 0 ▶ print "CRSF " . $url . "\n" if $$ctx{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"debug"} 0 0 0
536  
537 0 my $req = GET $url;
538 0 $req->content_type('application/json');
539  
540 0 ▶ if (!$$ctx{isGuest}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ctx->{"isGuest"}) 0 0 0
541 0 $req->authorization_basic($$ctx{auth}{'login'}, $$ctx{auth}{'password'});
542 }
543  
544 0 my $response = $$ctx{userAgent}->request($req);
545  
546 0 ▶ if ($response->is_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($response->is_error) 0 0 0
547 0 croak($response->status_line . '\n' . $response->decoded_content);
548 }
549  
550 0 ▶ my $json_obj = JSON->new->utf8->decode($response->content)
Condition0%0/2
'JSON'->new->utf8->decode($response->content) || croak("ERROR: Unable to decode JSON.\n$url\n")
l!l
00
MC/DC0%0/1
'JSON'->new->utf8->decode($response->content) || croak("ERROR: Unable to decode JSON.\n$url\n")
'JSON'->new->utf8->decode($response->content)
Truth table0%0/2
A
A= 'JSON'->new->utf8->decode($response->content)
Aresult
11
00
551 || croak("ERROR: Unable to decode JSON.\n$url\n");
552  
553 0 return $$json_obj{'CSRF'};
554 }
555  
556 0 ▶sub _getServerContext {
Subroutine _getServerContext: not called CC=8 SCAR=42.8
557 0 my %args = @_;
558  
559 #allow baseUrl as environment variable
560 0 ▶ $args{'-baseUrl'} = $args{'-baseUrl'} || $ENV{LABKEY_URL};
Condition0%0/3
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-baseUrl'} || $ENV{'LABKEY_URL'}
$args{'-baseUrl'} $ENV{'LABKEY_URL'}
Truth table0%0/3
A || B
A= $args{'-baseUrl'}B= $ENV{'LABKEY_URL'}
ABresult
1X1
011
000
561  
562 0 my @required = ('-containerPath', '-baseUrl');
563 0 _checkRequiredParams(\%args, \@required);
564  
565 #if no machine supplied, extract domain from baseUrl
566 0 ▶ if (!$args{'-machine'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"-machine"}) 0 0 0
567 0 $args{'-machine'} = URI->new($args{'-baseUrl'})->host;
568 }
569  
570 0 my $is_guest;
571 my $lk_config;
572 0 ▶ my $netrc_file = $args{-netrcFile} || $ENV{LABKEY_NETRC};
Condition0%0/3
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-netrcFile'} || $ENV{'LABKEY_NETRC'}
$args{'-netrcFile'} $ENV{'LABKEY_NETRC'}
Truth table0%0/3
A || B
A= $args{'-netrcFile'}B= $ENV{'LABKEY_NETRC'}
ABresult
1X1
011
000
573  
574 0 ▶ if ($args{'-loginAsGuest'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'-loginAsGuest'}) { } 0 0 0
575 0 $is_guest = 1;
576 }
577 else {
578 0 $lk_config = _readrc($args{-machine}, $netrc_file);
579 0 $is_guest = 0;
580 }
581  
582 my $ctx = {
583 auth => $lk_config,
584 baseUrl => $args{'-baseUrl'},
585 containerPath => $args{'-containerPath'},
586 isGuest => $is_guest,
587 0 ▶ userAgent => $args{'-useragent'} || _createUserAgent(%args),
Condition0%0/3
$args{'-useragent'} || _createUserAgent(%args)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{'-useragent'} || _createUserAgent(%args)
$args{'-useragent'} _createUserAgent(%args)
Truth table0%0/3
A || B
A= $args{'-useragent'}B= _createUserAgent(%args)
ABresult
1X1
011
000
588 };
589  
590 0 ▶ if ($args{-debug}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"-debug"}) 0 0 0
591 0 $$ctx{debug} = 1;
592 }
593  
594 0 my $csrfHeader = "X-LABKEY-CSRF";
595  
596 0 ▶ if (!$$ctx{userAgent}->default_header($csrfHeader)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ctx->{"userAgent"}->default_header($csrfHeader)) 0 0 0
597 0 $$ctx{userAgent}->default_header($csrfHeader => _fetchCSRF($ctx));
598 }
599  
600 0 return $ctx;
601 }
602  
603 =pod
604  
605 =head1 ENVIORNMENT VARIABLES
606  
607 =over 4
608  
609 =item *
610 The 'LABKEY_URL' environment variable can be used instead of supplying a '-baseUrl' param.
611  
612 =item *
613 The 'LABKEY_NETRC' environment variable can be used to specify an alternate location of a netrc file, if not in the user's home directory.
614  
615 =back
616  
617 =head1 AUTHOR
618  
619 LabKey C<info@labkey.com>
620  
621 =head1 CONTRIBUTING
622  
623 Send comments, suggestions and bug reports to:
624  
625 L<https://www.labkey.org/home/developer/forum/project-start.view>
626  
627  
628 =head1 COPYRIGHT
629
630 Copyright (c) 2010 Ben Bimber
631 Copyright (c) 2011-2020 LabKey Corporation
632  
633 =head1 LICENSE
634  
635 Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
636  
637 =head1 SEE ALSO
638  
639 The LabKey client APIs are described in greater detail here:
640 https://www.labkey.org/Documentation/wiki-page.view?name=viewAPIs
641  
642 Support questions should be directed to the LabKey forum:
643 https://www.labkey.org/home/Server/Forum/announcements-list.view
644  
645 =cut
646  
647 6 1;
648  
↑ Summary