File: Operation.pm

package info (click to toggle)
libxml-compile-soap-perl 3.24%2Bds-1
  • links: PTS, VCS
  • area: non-free
  • in suites: buster
  • size: 620 kB
  • sloc: perl: 4,407; makefile: 2
file content (501 lines) | stat: -rw-r--r-- 16,260 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# Copyrights 2007-2018 by [Mark Overmeer <markov@cpan.org>].
#  For other contributors see ChangeLog.
# See the manual pages for details on the licensing terms.
# Pod stripped from pm file by OODoc 2.02.
# This code is part of distribution XML-Compile-SOAP.  Meta-POD processed
# with OODoc into POD and HTML manual-pages.  See README.md
# Copyright Mark Overmeer.  Licensed under the same terms as Perl itself.

package XML::Compile::SOAP11::Operation;
use vars '$VERSION';
$VERSION = '3.24';

use base 'XML::Compile::SOAP::Operation';

use warnings;
use strict;

use Log::Report 'xml-compile-soap';

use List::Util  'first';

use XML::Compile::Util       qw/pack_type unpack_type/;
use XML::Compile::SOAP::Util qw/:soap11/;
use XML::Compile::SOAP11::Client;
use XML::Compile::SOAP11::Server;
use XML::Compile::SOAP::Extension;

use vars '$VERSION';         # OODoc adds $VERSION to the script
$VERSION ||= '(devel)';

# client/server object per schema class, because initiation options
# can be different.  Class reference is key.
my (%soap11_client, %soap11_server);


sub init($)
{   my ($self, $args) = @_;

    $self->SUPER::init($args);

    $self->{$_}    = $args->{$_} || {}
        for qw/input_def output_def fault_def/;

    $self->{style} = $args->{style} || 'document';

    XML::Compile::SOAP::Extension->soap11OperationInit($self, $args);
    $self;
}

sub _fromWSDL11(@)
{   my ($class, %args) = @_;

    # Extract the SOAP11 specific information from a WSDL11 file.  There are
    # half a zillion parameters.
    my ($p_op, $b_op, $wsdl)
      = @args{ qw/port_op bind_op wsdl/ };

    $args{schemas}   = $wsdl;
    $args{endpoints} = $args{serv_port}{soap_address}{location};

    my $sop = $b_op->{soap_operation}     || {};
    $args{action}  ||= $sop->{soapAction};

    my $sb = $args{binding}{soap_binding} || {};
    $args{transport} = $sb->{transport}   || 'HTTP';
    $args{style}     = $sb->{style}       || 'document';

    $args{input_def} = $class->_msg_parts($wsdl, $args{name}, $args{style}
      , $p_op->{wsdl_input}, $b_op->{wsdl_input});

    $args{output_def} = $class->_msg_parts($wsdl, $args{name}.'Response'
      , $args{style}, $p_op->{wsdl_output}, $b_op->{wsdl_output});

    $args{fault_def}
      = $class->_fault_parts($wsdl, $p_op->{wsdl_fault}, $b_op->{wsdl_fault});

    $class->SUPER::new(%args);
}

sub _msg_parts($$$$$)
{   my ($class, $wsdl, $opname, $style, $port_op, $bind_op) = @_;
    my %parts;

    defined $port_op          # communication not in two directions
        or return ({}, {});

    if(my $body = $bind_op->{soap_body})
    {   my $msgname   = $port_op->{message};
        my @parts     = $class->_select_parts($wsdl, $msgname, $body->{parts});

        my ($ns, $local) = unpack_type $msgname;
        my $rpc_ns    = $body->{namespace} // '';
        $wsdl->addNicePrefix(call => $rpc_ns) if $rpc_ns;

        my $procedure
           = $style eq 'rpc' ? pack_type($rpc_ns, $opname)
           : @parts==1 && $parts[0]{type} ? $msgname
           : $local; 

        $parts{body}  = {procedure => $procedure, %$port_op, use => 'literal'
           , %$body, parts => \@parts};
    }
    elsif($port_op->{message})
    {   # missing <soap:body use="literal"> in <wsdl:input> or :output
        error __x"operation {opname} has a message in its portType but no encoding in the binding", opname => $opname;
    }

    my $bsh = $bind_op->{soap_header} || [];
    foreach my $header (ref $bsh eq 'ARRAY' ? @$bsh : $bsh)
    {   my $msgname  = $header->{message};
        my @parts    = $class->_select_parts($wsdl, $msgname, $header->{part});
         push @{$parts{header}}, { %$header, parts => \@parts };

        foreach my $fault ( @{$header->{headerfault} || []} )
        {   $msgname = $fault->{message};
            my @hf   = $class->_select_parts($wsdl, $msgname, $fault->{part});
            push @{$parts{headerfault}}, { %$fault,  parts => \@hf };
        }
    }
    \%parts;
}

sub _select_parts($$$)
{   my ($class, $wsdl, $msgname, $need_parts) = @_;
    my $msg = $wsdl->findDef(message => $msgname)
        or error __x"cannot find message {name}", name => $msgname;

    my @need
      = ref $need_parts     ? @$need_parts
      : defined $need_parts ? $need_parts
      : ();

    my $parts = $msg->{wsdl_part} || [];
    @need or return @$parts;

    my @sel;
    my %parts = map +($_->{name} => $_), @$parts;
    foreach my $name (@need)
    {   my $part = $parts{$name}
            or error __x"message {msg} does not have a part named {part}"
                  , msg => $msg->{name}, part => $name;

        push @sel, $part;
    }

    @sel;
}

sub _fault_parts($$$)
{   my ($class, $wsdl, $portop, $bind) = @_;

    my $port_faults  = $portop || [];
    my %faults;

    foreach my $fault (@$bind)
    {   $fault or next;
        my $name  = $fault->{name};

        my $port  = first {$_->{name} eq $name} @$port_faults;
        defined $port
            or error __x"cannot find port for fault {name}", name => $name;

        my $msgname = $port->{message}
            or error __x"no fault message name in portOperation";

        my $message = $wsdl->findDef(message => $msgname)
            or error __x"cannot find fault message {name}", name => $msgname;

        @{$message->{wsdl_part} || []}==1
            or error __x"fault message {name} must have one part exactly"
                  , name => $msgname;

        $faults{$name} =
          { part => $message->{wsdl_part}[0]
          , use  => ($fault->{use} || 'literal')
          };
    }

   +{ faults => \%faults };
}

#-------------------------------------------


sub style()     {shift->{style}}
sub version()   { 'SOAP11' }
sub serverClass { 'XML::Compile::SOAP11::Server' }
sub clientClass { 'XML::Compile::SOAP11::Client' }

#-------------------------------------------


sub addHeader($$$%)
{   my ($self, $dir, $label, $el, %opts) = @_;
    my $elem = $self->schemas->findName($el);
    my $defs
      = $dir eq 'INPUT'  ? 'input_def'
      : $dir eq 'OUTPUT' ? 'output_def'
      : $dir eq 'FAULT'  ? 'fault_def'
      : panic "addHeader $dir";
    my $headers = $self->{$defs}{header} ||= [];

    if(my $already = first {$_->{part} eq $label} @$headers)
    {   # the header is already defined, ignore second declaration
        my $other_type = $already->{parts}[0]{element};
        $other_type eq $elem
            or error __x"header {label} already defined with type {type}"
                 , label => $label, type => $other_type;
        return $already;
    }

    my %part =
      ( part  => $label, use => 'literal'
      , parts => [
         { name => $label, element => $elem
         , mustUnderstand => $opts{mustUnderstand}
         , destination    => $opts{destination}
         } ]);

    push @$headers, \%part;
    \%part;
}

#-------------------------------------------


sub compileHandler(@)
{   my ($self, %args) = @_;

    my $soap  = $soap11_server{$self->{schemas}}
      ||= XML::Compile::SOAP11::Server->new(schemas => $self->{schemas});
    my $style = $args{style} ||= $self->style;

    my @ro    = (%{$self->{input_def}},  %{$self->{fault_def}});
    my @so    = (%{$self->{output_def}}, %{$self->{fault_def}});

    $args{encode}   ||= $soap->_sender(@so, %args);
    $args{decode}   ||= $soap->_receiver(@ro, %args);
    $args{kind}     ||= $self->kind;
    $args{name}       = $self->name;
    $args{selector} ||= $soap->compileFilter(%{$self->{input_def}},
		style => $style);

    $args{callback} = XML::Compile::SOAP::Extension
      ->soap11HandlerWrapper($self, $args{callback}, \%args);

    $soap->compileHandler(%args);
}


sub compileClient(@)
{   my ($self, %args) = @_;

    my $client = $soap11_client{$self->{schemas}}
      ||= XML::Compile::SOAP11::Client->new(schemas => $self->{schemas});
    my $style  = $args{style} ||= $self->style;
    my $kind   = $args{kind}  ||= $self->kind;

    my @so     = (%{$self->{input_def}},  %{$self->{fault_def}});
    my @ro     = (%{$self->{output_def}}, %{$self->{fault_def}});

    my $call   = $client->compileClient
      ( name      => $self->name
      , kind      => $kind
      , encode    => $client->_sender(@so, %args)
      , decode    => $client->_receiver(@ro, %args)
      , transport => $self->compileTransporter(%args)
      , async     => $args{async}
      , soap      => $args{soap}
      );

    XML::Compile::SOAP::Extension->soap11ClientWrapper($self, $call, \%args);
}

#--------------------------


my $sep = '#--------------------------------------------------------------';

sub explain($$$@)
{   my ($self, $schema, $format, $dir, %args) = @_;

    # $schema has to be passed as argument, because we do not want operation
    # objects to be glued to a schema object after compile time.

    UNIVERSAL::isa($schema, 'XML::Compile::Schema')
        or error __x"explain() requires first element to be a schema";

    $format eq 'PERL'
        or error __x"only PERL template supported for the moment, not {got}"
            , got => $format;

    my $style       = $self->style;
    my $opname      = $self->name;
    my $skip_header = delete $args{skip_header} || 0;
    my $recurse     = delete $args{recurse}     || 0;

    my $def    = $dir eq 'INPUT' ? $self->{input_def} : $self->{output_def};
    my $faults = $self->{fault_def}{faults};

    my (@struct, @postproc, @attach);
    my @main = $recurse
       ? "# The details of the types and elements are attached below."
       : "# To explore the HASHes for each part, use recurse option.";

  HEAD_PART:
    foreach my $header (@{$def->{header} || []})
    {   foreach my $part ( @{$header->{parts} || []} )
        {   my $name = $part->{name};
            my ($kind, $value) = $part->{type} ? (type => $part->{type})
              : (element => $part->{element});
    
            my $type = $schema->prefixed($value) || $value;
            push @main, ''
              , "# Header part '$name' is $kind $type"
              , ($kind eq 'type' && $recurse ? "# See fake element '$name'" : ())
              , "my \$$name = {};";
            push @struct, "    $name => \$$name,";
    
            $recurse or next HEAD_PART;
    
            my $elem = $value;
            if($kind eq 'type')
            {   # generate element with part name, because template requires elem
                $schema->compileType(READER => $value, element => $name);
                $elem = $name;
            }
    
            push @attach, '', $sep, "\$$name ="
              , $schema->template(PERL => $elem, skip_header => 1, %args), ';';
        }
    }

  BODY_PART:
    foreach my $part ( @{$def->{body}{parts} || []} )
    {   my $name = $part->{name};
        my ($kind, $value) = $part->{type} ? (type => $part->{type})
          : (element => $part->{element});

        my $type = $schema->prefixed($value) || $value;
        push @main, ''
          , "# Body part '$name' is content for $kind $type"
          , ($kind eq 'type' && $recurse ? "# See fake element '$name'" : ())
          , "my \$$name = {};";
        push @struct, "    $name => \$$name,";

        $recurse or next BODY_PART;

        my $elem = $value;
        if($kind eq 'type')
        {   # generate element with part name, because template requires elem
            $schema->compileType(READER => $value, element => $name);
            $elem = $name;
        }

        push @attach, '', $sep, "\$$name ="
          , $schema->template(PERL => $elem, skip_header => 1, %args), ';';
    }

    foreach my $fault (sort keys %$faults)
    {   my $part = $faults->{$fault}{part};  # fault msgs have only one part
        my ($kind, $value) = $part->{type} ? (type => $part->{type})
          : (element => $part->{element});

        my $type = $schema->prefixFor($value)
          ? $schema->prefixed($value) : $value;

        if($dir eq 'OUTPUT')
        {   push @main, ''
              , "# ... or fault $fault is $kind"
              , "my \$$fault = {}; # $type"
              , ($kind eq 'type' && $recurse ? "# See fake element '$fault'" : ())
              , "my \$fault ="
              , "  { code   => pack_type(\$myns, 'Open.NoSuchFile')"
              , "  , reason => 'because I can'"
              , "  , detail => \$$fault"
              , '  };';
            push @struct, "    $fault => \$fault,";
        }
        else
        {   my $nice = $schema->prefixed($type) || $type;
            push @postproc
              , "    elsif(\$errname eq '$fault')"
              , "    {   # \$details is a $nice"
              , "    }";
        }

        $recurse or next;

        my $elem = $value;
        if($kind eq 'type')
        {   # generate element with part name, because template requires elem
            $schema->compileType(READER => $value, element => $fault);
            $elem = $fault;
        }

        push @attach, '', $sep, "# FAULT", "\$$fault ="
          , $schema->template(PERL => $elem, skip_header => 1, %args), ';';
    }

    if($dir eq 'INPUT')
    {   push @main, ''
         , '# Call with the combination of parts.'
         , 'my @params = (', @struct, ');'
         , 'my ($answer, $trace) = $call->(@params);', ''
         , '# @params will become %$data_in in the server handler.'
         , '# $answer is a HASH, an operation OUTPUT or Fault.'
         , '# $trace is an XML::Compile::SOAP::Trace object.';

        unshift @postproc, ''
          , '# You may get an error back from the server'
          , 'if(my $f = $answer->{Fault})'
          , '{   my $errname = $f->{_NAME};'
          , '    my $error   = $answer->{$errname};'
          , '    print "$error->{code}\n";', ''
          , '    my $details = $error->{detail};'
          , '    if(not $details)'
          , '    {   # system error, no $details'
          , '    }';
    
        push @postproc
          , '    exit 1;'
          , '}';
    }
    elsif($dir eq 'OUTPUT')
    {   s/^/   / for @main, @struct;
        unshift @main, ''
         , "sub handle_$opname(\$)"
         , '{  my ($server, $data_in) = @_;'
         , '   # process $data_in, structured as INPUT message.'
         , '   # Hint: use "print Dumper $data_in"';

        push @main, ''
         , '   # This will end-up as $answer at client-side'
         , '   return    # optional keyword'
         , "   +{", @struct, "    };", "}";
    }
    else
    {   error __x"template for direction INPUT or OUTPUT, not {got}"
          , got => $dir;
    }

    my @header;
    if(my $how = $def->{body})
    {   my $use  = $how->{use} || 'literal';
        push @header
          , "# Operation $how->{procedure}"
          , "#           $dir, $style $use";
    }
    else
    {   push @header,
          , "# Operation $opname has no $dir";
    }

    foreach my $fault (sort keys %$faults)
    {   my $usage = $faults->{$fault};
        push @header
      , "#           FAULT $fault, $style $usage->{use}" # $style?
    }

    push @header
      , "# Produced  by ".__PACKAGE__." version $VERSION"
      , "#           on ".localtime()
      , "#"
      , "# The output below is only an example: it cannot be used"
      , "# without interpretation, although very close to real code."
      , ""
        unless $args{skip_header};

    if($dir eq 'INPUT')
    {   push @header
          , '# Compile only once in your code, usually during initiation:'
          , "#   my \$call = \$wsdl->compileClient('$opname');"
          , '# then call it as often as you need.  Alternatively'
          , '#   $wsdl->compileCalls();   # once'
          , "#   \$response = \$wsdl->call('$opname', \$request);";
    }
    else #OUTPUT
    {   push @header
          , '# As part of the initiation phase of your server:'
          , 'my $daemon = XML::Compile::SOAP::HTTPDaemon->new;'
          , '$daemon->operationsFromWSDL'
          , '  ( $wsdl'
          , '  , callbacks =>'
          , "     { $opname => \\&handle_$opname}"
          , '  );'
    }

    join "\n", @header, @main, @postproc, @attach, '';
}

sub parsedWSDL()
{   my $self = shift;
      +{ input  => $self->{input_def}{body}
       , output => $self->{output_def}{body}
       , faults => $self->{fault_def}{faults}
       , style  => $self->style
       };
}

1;