ApiClient.pm untested

filter: Statementstmt 0.0% 0 / 264 Branchbran 0.0% 0 / 108 Conditioncond 0.0% 0 / 42 MC/DCmcdc 0.0% 0 / 28 Subroutinesub 0.0% 0 / 39 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 499 CC 55 SCAR 40.3
CC
55
Cov
0%
call_api_once
156.0
deserialize
156.0
get_body_data
90.0
CRAP 56.5
1 =begin comment
2  
3 Copyright (c) 2019 Aspose Pty Ltd
4  
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11  
12 The above copyright notice and this permission notice shall be included in all
13 copies or substantial portions of the Software.
14  
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 SOFTWARE.
22  
23 =end comment
24  
25 =cut
26  
27 package AsposeSlidesCloud::ApiClient;
28  
29 use strict;
30 use warnings;
31 use utf8;
32  
33 use MIME::Base64;
34 use LWP::UserAgent;
35 use HTTP::Date;
36 use HTTP::Headers;
37 use HTTP::Response;
38 use HTTP::Request::Common qw(DELETE POST GET HEAD PUT);
39 use HTTP::Status;
40 use URI::Query;
41 use JSON;
42 use URI::Escape;
43 use Scalar::Util;
44 use Carp;
45 use Module::Runtime qw(use_module);
46 use Log::Any qw($log);
47 use Log::Any::Adapter ('Stderr');
48 use AsposeSlidesCloud::ApiInfo;
49 use AsposeSlidesCloud::ClassRegistry;
50 use AsposeSlidesCloud::Configuration;
51  
52 sub new {
53 my $class = shift;
54  
55 my $config;
56  
57 my %params = @_;
58  
59 if (defined $params{config}) {
60 $config = $params{config};
61 } else {
62 $config = AsposeSlidesCloud::Configuration->new(@_);
63 }
64  
65 my $ua = LWP::UserAgent->new;
66  
67 if ($config->{allow_insecure_requests}) {
68 $ua->ssl_opts(SSL_verify_mode => 0);
69 $ua->ssl_opts(verify_hostname => 0);
70 }
71  
72 if (defined $config->{http_request_timeout}) {
73 $ua->{timeout} = $config->{http_request_timeout};
74 }
75  
76 my (%args) = ('ua' => $ua, 'config' => $config);
77
78 return bless \%args, $class;
79 }
80  
81 # make the HTTP request
82 # @param string $resourcePath path to method endpoint
83 # @param string $method method to call
84 # @param array $queryParams parameters to be place in query URL
85 # @param array $postParams parameters to be placed in POST body
86 # @param array $headerParams parameters to be place in request header
87 # @param array $body_data data to be place in request body
88 # @param array $files files to be posted
89 # @return mixed
90 sub call_api {
91 my $self = shift;
92 my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $files) = @_;
93  
94 my $had_token = defined $self->{config}{access_token} && $self->{config}{access_token} ne "";
95 my $response = $self->call_api_once($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $files);
96 my $content = sprintf("%s", $response->content);
97 if ($had_token && ($response->code eq 401 || ($response->code eq 500 && !$content))) {
98 $self->{config}{access_token} = "";
99 $response = $self->call_api_once($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $files);
100 $content = sprintf("%s", $response->content);
101 }
102 unless ($response->is_success) {
103 croak(sprintf "API Exception(%s): %s\n%s", $response->code, $response->message, $content);
104 }
105 return $content;
106 }
107  
108 sub call_api_once {
109 my $self = shift;
110 my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $files) = @_;
111
112 $self->update_headers($header_params);
113
114 my $_url = $self->{config}{base_url}."/".$self->{config}{version}.$resource_path;
115  
116 # build query
117 if (%$query_params) {
118 $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify });
119 }
120  
121 my $_body_data = %$post_params ? $post_params : $self->get_body_data($header_params, $body_data, $files);
122  
123 # Make the HTTP request
124 my $_request;
125 if ($method eq 'POST') {
126 # multipart
127 $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ?
128 'form-data' : $header_params->{'Content-Type'};
129 $_request = POST($_url, %$header_params, Content => $_body_data);
130 }
131 elsif ($method eq 'PUT') {
132 # multipart
133 $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ?
134 'form-data' : $header_params->{'Content-Type'};
135
136 $_request = PUT($_url, %$header_params, Content => $_body_data);
137  
138 }
139 elsif ($method eq 'GET') {
140 my $headers = HTTP::Headers->new(%$header_params);
141 $_request = GET($_url, %$header_params);
142 }
143 elsif ($method eq 'HEAD') {
144 my $headers = HTTP::Headers->new(%$header_params);
145 $_request = HEAD($_url,%$header_params);
146 }
147 elsif ($method eq 'DELETE') { #TODO support form data
148 my $headers = HTTP::Headers->new(%$header_params);
149 $_request = DELETE($_url, %$headers);
150 }
151  
152 if ($self->{config}{debug}) {
153 $self->_log("REQUEST: " . $_request->as_string);
154 }
155  
156 my $_response = $self->{ua}->request($_request);
157  
158 if ($self->{config}{debug}) {
159 $self->_log("RESPONSE: " . $_response->as_string);
160 }
161
162 return $_response;
163 }
164  
165 # get request body
166 # @param array $headerParams parameters to be place in request header
167 # @param array $body_data data to be place in request body
168 # @param array $files files to be posted
169 # @return mixed
170 sub get_body_data {
171 my $self = shift;
172 my ($header_params, $body_data, $files) = @_;
173 my $part_count = 0;
174 if (defined $body_data) {
175 if (!(ref $body_data eq "HASH") && (rindex ref $body_data, "AsposeSlidesCloud::Object::", 0) == 0) {
176 $body_data = decode_json(JSON->new->convert_blessed->encode($body_data));
177 }
178 if (ref $body_data eq "HASH") {
179 $body_data = to_json($body_data); # model to json string
180 }
181 }
182 if (defined $files) {
183 $part_count += scalar @$files;
184 }
185 my $_body_data = "";
186 if ($part_count > 0) {
187 my $boundary = "7d70fb31-0eb9-4846-9ea8-933dfb69d8f1";
188 $header_params->{'Content-Type'} = "multipart/form-data; boundary=${boundary}";
189 if (defined $body_data) {
190 $_body_data = $_body_data . "\r\n--${boundary}\r\n";
191 $_body_data = $_body_data . "Content-Disposition: form-data; name=\"data\"\r\n";
192 $_body_data = $_body_data . "Content-Type: text/json\r\n";
193 $_body_data = $_body_data . "\r\n";
194 $_body_data = $_body_data . $body_data;
195 }
196 my $fileIndex = 1;
197 foreach (@$files) {
198 $_body_data = $_body_data . "\r\n--${boundary}\r\n";
199 $_body_data = $_body_data . "Content-Disposition: form-data; name=\"file${fileIndex}\";filename=\"file${fileIndex}\"\r\n";
200 $_body_data = $_body_data . "Content-Type: application/octet-stream\r\n";
201 $_body_data = $_body_data . "\r\n";
202 $_body_data = $_body_data . $_;
203 $fileIndex++;
204 }
205 $_body_data = $_body_data . "\r\n--${boundary}--\r\n";
206 } elsif (defined $body_data) {
207 $_body_data = $body_data;
208 } elsif (defined $files) {
209 $_body_data = @$files[0];
210 }
211 return $_body_data;
212 }
213  
214 # Take value and turn it into a string suitable for inclusion in
215 # the path, by url-encoding.
216 # @param string $value a string which will be part of the path
217 # @return string the serialized object
218 sub to_path_value {
219 my ($self, $value) = @_;
220 return $self->to_string($value);
221 }
222  
223 # Take value and turn it into a string suitable for inclusion in
224 # the query, by imploding comma-separated if it's an object.
225 # @param object $object an object to be serialized to a string
226 # @return string the serialized object
227 sub to_query_value {
228 my ($self, $object) = @_;
229 if (ref($object) eq 'ARRAY') {
230 return join(',', @$object);
231 } else {
232 return $self->to_string($object);
233 }
234 }
235  
236 # Take boolean value and turn it into a string suitable for inclusion in
237 # the query, by imploding comma-separated if it's an object.
238 # @param object $object an object to be serialized to a string
239 # @return string the serialized object
240 sub to_boolean_query_value {
241 my ($self, $value) = @_;
242 if ($value) {
243 return "true";
244 } else {
245 return "false";
246 }
247 }
248  
249 # Take value and turn it into a string suitable for inclusion in
250 # the header. If it's a string, pass through unchanged
251 # If it's a datetime object, format it in ISO8601
252 # @param string $value a string which will be part of the header
253 # @return string the header string
254 sub to_header_value {
255 my ($self, $value) = @_;
256 return $self->to_string($value);
257 }
258  
259 # Take value and turn it into a string suitable for inclusion in
260 # the http body (form parameter). If it's a string, pass through unchanged
261 # If it's a datetime object, format it in ISO8601
262 # @param string $value the value of the form parameter
263 # @return string the form string
264 sub to_form_value {
265 my ($self, $value) = @_;
266 return $self->to_string($value);
267 }
268  
269 # Take value and turn it into a string suitable for inclusion in
270 # the parameter. If it's a string, pass through unchanged
271 # If it's a datetime object, format it in ISO8601
272 # @param string $value the value of the parameter
273 # @return string the header string
274 sub to_string {
275 my ($self, $value) = @_;
276 if (ref($value) eq "DateTime") { # datetime in ISO8601 format
277 return $value->datetime();
278 }
279 else {
280 return sprintf("%s", $value);
281 }
282 }
283  
284  
285 # from Perl hashref
286 sub from_hash {
287 my ($self, $instance, $hash) = @_;
288  
289 # loop through attributes and use swagger_types to deserialize the data
290 my $current_types = {};
291 while ( my ($_key, $_type) = each %{$instance->swagger_types} ) {
292 $current_types->{$_key} = $_type;
293 }
294 while ( my ($_key, $_type) = each %{$current_types} ) {
295 my $_json_attribute = $instance->attribute_map->{$_key};
296 if ($_type =~ /^array\[/i) { # array
297 my $_subclass = substr($_type, 6, -1);
298 my @_array = ();
299 foreach my $_element (@{$hash->{$_json_attribute}}) {
300 if (defined $_element) {
301 push @_array, $self->_deserialize($_subclass, $_element);
302 } else {
303 push @_array, undef;
304 }
305 }
306 foreach my $_element (@{$hash->{lcfirst($_json_attribute)}}) {
307 if (defined $_element) {
308 push @_array, $self->_deserialize(lcfirst($_subclass), $_element);
309 } else {
310 push @_array, undef;
311 }
312 }
313 $instance->{$_key} = \@_array;
314 } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime
315 $instance->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute});
316 } elsif (exists $hash->{lcfirst($_json_attribute)}) { #hash(model), primitive, datetime
317 $instance->{$_key} = $self->_deserialize($_type, $hash->{lcfirst($_json_attribute)});
318 }
319 }
320
321 return $instance;
322 }
323  
324 # deserialize non-array data
325 sub _deserialize {
326 my ($self, $type, $data) = @_;
327
328 if ($type eq 'DateTime') {
329 return DateTime->from_epoch(epoch => str2time($data));
330 } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) {
331 return $data;
332 } else { # hash(model)
333 my $class = AsposeSlidesCloud::ClassRegistry->get_class_name(ucfirst($type), $data);
334 my $_instance = use_module("AsposeSlidesCloud::Object::$class")->new();
335 return $self->from_hash($_instance, $data);
336 }
337 }
338  
339 # Deserialize a JSON string into an object
340 #
341 # @param string $class class name is passed as a string
342 # @param string $data data of the body
343 # @return object an instance of $class
344 sub deserialize
345 {
346 my ($self, $class, $data) = @_;
347
348 if (not defined $data) {
349 return undef;
350 } elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash
351 if ($class =~ /^HASH\[(.*),(.*)\]$/) {
352 my ($key_type, $type) = ($1, $2);
353 my %hash;
354 my $decoded_data = decode_json $data;
355 foreach my $key (keys %$decoded_data) {
356 if (ref $decoded_data->{$key} eq 'HASH') {
357 $hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key});
358 } else {
359 $hash{$key} = $self->deserialize($type, $decoded_data->{$key});
360 }
361 }
362 return \%hash;
363 } else {
364 #TODO log error
365 }
366
367 } elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data
368 return $data if $data eq '[]'; # return if empty array
369
370 my $_sub_class = substr($class, 6, -1);
371 my $_json_data = decode_json $data;
372 my @_values = ();
373 foreach my $_value (@$_json_data) {
374 if (ref $_value eq 'ARRAY') {
375 push @_values, $self->deserialize($_sub_class, encode_json $_value);
376 } else {
377 push @_values, $self->deserialize($_sub_class, $_value);
378 }
379 }
380 return \@_values;
381 } elsif ($class eq 'DateTime') {
382 return DateTime->from_epoch(epoch => str2time($data));
383 } elsif (grep /^$class$/, ('string')) {
384 $data =~ s/^"(.*)"$/$1/;
385 return $data;
386 } elsif (grep /^$class$/, ('int', 'float', 'bool', 'object', 'File')) {
387 return $data;
388 } else { # model
389 $class = AsposeSlidesCloud::ClassRegistry->get_class_name($class, $data);
390 my $_instance = use_module("AsposeSlidesCloud::Object::$class")->new;
391 if (ref $data eq "HASH") {
392 return $self->from_hash($_instance, $data);
393 } else { # string, need to json decode first
394 return $self->from_hash($_instance, decode_json $data);
395 }
396 }
397 }
398  
399 # return 'Accept' based on an array of accept provided
400 # @param [Array] header_accept_array Array fo 'Accept'
401 # @return String Accept (e.g. application/json)
402 sub select_header_accept
403 {
404 my ($self, @header) = @_;
405
406 if (@header == 0 || (@header == 1 && $header[0] eq '')) {
407 return undef;
408 } elsif (grep(/^application\/json$/i, @header)) {
409 return 'application/json';
410 } else {
411 return join(',', @header);
412 }
413
414 }
415  
416 # return the content type based on an array of content-type provided
417 # @param [Array] content_type_array Array fo content-type
418 # @return String Content-Type (e.g. application/json)
419 sub select_header_content_type
420 {
421 my ($self, @header) = @_;
422
423 if (@header == 0 || (@header == 1 && $header[0] eq '')) {
424 return 'application/json'; # default to application/json
425 } elsif (grep(/^application\/json$/i, @header)) {
426 return 'application/json';
427 } elsif ($header[0] eq 'multipart/form-data') {
428 return 'application/octet-stream';
429 } else {
430 return $header[0]
431 }
432
433 }
434  
435 # add auth, user agent and other headers
436 #
437 # @param array $headerParams header parameters (by ref)
438 sub update_headers {
439 my ($self, $header_params) = @_;
440 my $custom_headers = $self->{config}{custom_headers};
441 foreach my $key (keys %$custom_headers) {
442 $header_params->{$key} = $self->{config}{custom_headers}{$key};
443 }
444 $self->update_params_for_auth($header_params);
445 }
446  
447 # update header and query param based on authentication setting
448 #
449 # @param array $headerParams header parameters (by ref)
450 sub update_params_for_auth {
451 my ($self, $header_params) = @_;
452 if ((defined $self->{config}{app_sid} && $self->{config}{app_sid} ne "") && (!defined $self->{config}{access_token} || $self->{config}{access_token} eq "")) {
453 my $_url = ($self->{config}{auth_base_url} // $self->{config}{base_url}) . "/connect/token";
454 my $_request = POST($_url, {}, Content => 'grant_type=client_credentials&client_id='.$self->{config}{app_sid}.'&client_secret='.$self->{config}{app_key});
455 my $_response = $self->{ua}->request($_request);
456 unless ($_response->is_success) {
457 my $content = sprintf("%s", $_response->content);
458 croak(sprintf "API Exception(%s): %s\n%s", 401, $_response->message, $content);
459 }
460 my $decoded_data = decode_json $_response->content;
461 $self->{config}{access_token} = $decoded_data->{access_token};
462 }
463 if (defined $self->{config}{access_token} && $self->{config}{access_token} ne "") {
464 $header_params->{'Authorization'} = 'Bearer ' . $self->{config}{access_token};
465 }
466 }
467  
468 sub _log {
469 my ($self, $message) = @_;
470 if (defined $self->{config}{logger}) {
471 $self->{config}{logger}->($message);
472 } else {
473 $log->debug($message);
474 }
475 }
476  
477 1;