Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4685 lines
153 KiB

  1. # ======================================================================
  2. #
  3. # Copyright (C) 2000-2001 Paul Kulchenko ([email protected])
  4. # SOAP::Lite is free software; you can redistribute it
  5. # and/or modify it under the same terms as Perl itself.
  6. #
  7. # $Id: SOAP::Lite.pm,v 0.51 2001/07/18 15:15:14 $
  8. #
  9. # ======================================================================
  10. package SOAP::Lite;
  11. use 5.004;
  12. use strict;
  13. use vars qw($VERSION);
  14. $VERSION = '0.51';
  15. # ======================================================================
  16. package SOAP::XMLSchemaSOAP1_1::Deserializer;
  17. sub anyTypeValue { 'ur-type' }
  18. sub as_boolean { shift; my $value = shift; $value eq '1' ? 1 : $value eq '0' ? 0 : die "Wrong boolean value '$value'\n" }
  19. sub as_base64 { shift; require MIME::Base64; MIME::Base64::decode_base64(shift) }
  20. sub as_string { defined $_[1] ? $_[1] : ''; }
  21. sub as_ur_type { $_[1] }
  22. BEGIN {
  23. no strict 'refs';
  24. for my $method (qw(
  25. float double decimal timeDuration recurringDuration uriReference
  26. integer nonPositiveInteger negativeInteger long int short byte
  27. nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  28. positiveInteger timeInstant time timePeriod date month year century
  29. recurringDate recurringDay language
  30. )) { my $name = 'as_' . $method; *$name = sub { $_[1] } }
  31. }
  32. # ----------------------------------------------------------------------
  33. package SOAP::XMLSchemaSOAP1_2::Deserializer;
  34. sub anyTypeValue { 'anyType' }
  35. sub as_boolean { shift; my $value = shift; $value eq '1' || $value eq 'true' ? 1 : $value eq '0' || $value eq 'false' ? 0 : die "Wrong boolean value '$value'\n" }
  36. sub as_base64 { shift; require MIME::Base64; MIME::Base64::decode_base64(shift) }
  37. sub as_string { defined $_[1] ? $_[1] : ''; }
  38. sub as_anyType { $_[1] }
  39. BEGIN {
  40. no strict 'refs';
  41. for my $method (qw(
  42. float double decimal dateTime timePeriod gMonth gYearMonth gYear century
  43. gMonthDay gDay duration recurringDuration anyURI
  44. language integer nonPositiveInteger negativeInteger long int short byte
  45. nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  46. positiveInteger date time dateTime
  47. )) { my $name = 'as_' . $method; *$name = sub { $_[1] } }
  48. }
  49. # ----------------------------------------------------------------------
  50. package SOAP::XMLSchemaApacheSOAP::Deserializer;
  51. sub as_map {
  52. my $self = shift;
  53. +{ map { my $hash = ($self->decode_object($_))[1]; ($hash->{key} => $hash->{value}) } @{$_[3] || []} };
  54. }
  55. sub as_Map; *as_Map = \&as_map;
  56. # ----------------------------------------------------------------------
  57. package SOAP::XMLSchema::Serializer;
  58. use vars qw(@ISA);
  59. sub xmlschemaclass {
  60. my $self = shift;
  61. return $ISA[0] unless @_;
  62. @ISA = (shift);
  63. return $self;
  64. }
  65. # ----------------------------------------------------------------------
  66. package SOAP::XMLSchema1999::Serializer;
  67. use vars qw(@EXPORT $AUTOLOAD);
  68. sub AUTOLOAD {
  69. local($1,$2);
  70. my($package, $method) = $AUTOLOAD =~ m/(?:(.+)::)([^:]+)$/;
  71. return if $method eq 'DESTROY';
  72. no strict 'refs';
  73. die "Method '$method' can't be found in a schema class '@{[__PACKAGE__]}'\n"
  74. unless $method =~ s/^as_// && grep {$_ eq $method} @EXPORT;
  75. $method =~ s/_/-/; # fix ur-type
  76. *$AUTOLOAD = sub {
  77. my $self = shift;
  78. my($value, $name, $type, $attr) = @_;
  79. return [$name, {'xsi:type' => "xsd:$method", %$attr}, $value];
  80. };
  81. goto &$AUTOLOAD;
  82. }
  83. BEGIN {
  84. @EXPORT = qw(ur_type
  85. float double decimal timeDuration recurringDuration uriReference
  86. integer nonPositiveInteger negativeInteger long int short byte
  87. nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  88. positiveInteger timeInstant time timePeriod date month year century
  89. recurringDate recurringDay language
  90. base64 hex string boolean
  91. );
  92. # predeclare subs, so ->can check will be positive
  93. foreach (@EXPORT) { eval "sub as_$_" }
  94. }
  95. sub nilValue { 'null' }
  96. sub anyTypeValue { 'ur-type' }
  97. sub as_base64 {
  98. my $self = shift;
  99. my($value, $name, $type, $attr) = @_;
  100. require MIME::Base64;
  101. return [$name, {'xsi:type' => SOAP::Utils::qualify($self->encprefix => 'base64'), %$attr}, MIME::Base64::encode_base64($value,'')];
  102. }
  103. sub as_hex {
  104. my $self = shift;
  105. my($value, $name, $type, $attr) = @_;
  106. return [$name, {'xsi:type' => 'xsd:hex', %$attr}, join '', map {sprintf "%x", ord} split '', $value];
  107. }
  108. sub as_string {
  109. my $self = shift;
  110. my($value, $name, $type, $attr) = @_;
  111. die "String value expected instead of @{[ref $value]} reference\n" if ref $value;
  112. return [$name, {'xsi:type' => 'xsd:string', %$attr}, SOAP::Utils::encode_data($value)];
  113. }
  114. sub as_undef { $_[1] ? '1' : '0' }
  115. sub as_boolean {
  116. my $self = shift;
  117. my($value, $name, $type, $attr) = @_;
  118. return [$name, {'xsi:type' => 'xsd:boolean', %$attr}, $value ? '1' : '0'];
  119. }
  120. # ----------------------------------------------------------------------
  121. package SOAP::XMLSchema1999::Deserializer;
  122. sub anyTypeValue { 'ur-type' }
  123. sub as_string; *as_string = \&SOAP::XMLSchemaSOAP1_1::Deserializer::as_string;
  124. sub as_boolean; *as_boolean = \&SOAP::XMLSchemaSOAP1_1::Deserializer::as_boolean;
  125. sub as_hex { shift; my $value = shift; $value =~ s/([a-zA-Z0-9]{2})/chr oct '0x'.$1/ge; $value }
  126. sub as_ur_type { $_[1] }
  127. sub as_undef { shift; my $value = shift; $value eq '1' || $value eq 'true' ? 1 : $value eq '0' || $value eq 'false' ? 0 : die "Wrong null/nil value '$value'\n" }
  128. BEGIN {
  129. no strict 'refs';
  130. for my $method (qw(
  131. float double decimal timeDuration recurringDuration uriReference
  132. integer nonPositiveInteger negativeInteger long int short byte
  133. nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  134. positiveInteger timeInstant time timePeriod date month year century
  135. recurringDate recurringDay language
  136. )) { my $name = 'as_' . $method; *$name = sub { $_[1] } }
  137. }
  138. # ----------------------------------------------------------------------
  139. package SOAP::XMLSchema2001::Serializer;
  140. use vars qw(@EXPORT);
  141. # no more warnings about "used only once"
  142. *AUTOLOAD if 0;
  143. *AUTOLOAD = \&SOAP::XMLSchema1999::Serializer::AUTOLOAD;
  144. BEGIN {
  145. @EXPORT = qw(anyType anySimpleType
  146. float double decimal dateTime timePeriod gMonth gYearMonth gYear century
  147. gMonthDay gDay duration recurringDuration anyURI
  148. language integer nonPositiveInteger negativeInteger long int short byte
  149. nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  150. positiveInteger date time
  151. string hex base64 boolean
  152. );
  153. # predeclare subs, so ->can check will be positive
  154. foreach (@EXPORT) { eval "sub as_$_" }
  155. }
  156. sub nilValue { 'nil' }
  157. sub anyTypeValue { 'anyType' }
  158. sub as_base64Binary {
  159. my $self = shift;
  160. my($value, $name, $type, $attr) = @_;
  161. require MIME::Base64;
  162. return [$name, {'xsi:type' => 'xsd:base64Binary', %$attr}, MIME::Base64::encode_base64($value,'')];
  163. }
  164. sub as_string; *as_string = \&SOAP::XMLSchema1999::Serializer::as_string;
  165. sub as_hex; *as_hex = \&SOAP::XMLSchema1999::Serializer::as_hex;
  166. sub as_base64; *as_base64 = \&as_base64Binary;
  167. sub as_undef { $_[1] ? 'true' : 'false' }
  168. sub as_boolean {
  169. my $self = shift;
  170. my($value, $name, $type, $attr) = @_;
  171. return [$name, {'xsi:type' => 'xsd:boolean', %$attr}, $value ? 'true' : 'false'];
  172. }
  173. # ----------------------------------------------------------------------
  174. package SOAP::XMLSchema2001::Deserializer;
  175. sub anyTypeValue { 'anyType' }
  176. sub as_string; *as_string = \&SOAP::XMLSchema1999::Deserializer::as_string;
  177. sub as_boolean; *as_boolean = \&SOAP::XMLSchemaSOAP1_2::Deserializer::as_boolean;
  178. sub as_base64Binary; *as_base64Binary = \&SOAP::XMLSchemaSOAP1_2::Deserializer::as_base64;
  179. sub as_hexBinary; *as_hexBinary = \&SOAP::XMLSchema1999::Deserializer::as_hex;
  180. sub as_undef; *as_undef = \&SOAP::XMLSchema1999::Deserializer::as_undef;
  181. BEGIN {
  182. no strict 'refs';
  183. for my $method (qw(
  184. anyType anySimpleType
  185. float double decimal dateTime timePeriod gMonth gYearMonth gYear century
  186. gMonthDay gDay duration recurringDuration anyURI
  187. language integer nonPositiveInteger negativeInteger long int short byte
  188. nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  189. positiveInteger date time dateTime
  190. )) { my $name = 'as_' . $method; *$name = sub { $_[1] } }
  191. }
  192. # ======================================================================
  193. package SOAP::Constants;
  194. BEGIN {
  195. use vars qw($NSMASK $ELMASK);
  196. $NSMASK = '[a-zA-Z_:][\w.\-:]*';
  197. $ELMASK = '^(?![xX][mM][lL])[a-zA-Z_][\w.\-]*$';
  198. use vars qw($NEXT_ACTOR $NS_ENV $NS_ENC $NS_APS
  199. $FAULT_CLIENT $FAULT_SERVER $FAULT_VERSION_MISMATCH
  200. $HTTP_ON_FAULT_CODE $HTTP_ON_SUCCESS_CODE $FAULT_MUST_UNDERSTAND
  201. $NS_XSI_ALL $NS_XSI_NILS %XML_SCHEMAS $DEFAULT_XML_SCHEMA
  202. $SOAP_VERSION %SOAP_VERSIONS
  203. $NS_SL $PREFIX_ENV $PREFIX_ENC
  204. $DO_NOT_USE_XML_PARSER $DO_NOT_CHECK_MUSTUNDERSTAND $DO_NOT_USE_CHARSET
  205. );
  206. $FAULT_CLIENT = 'Client';
  207. $FAULT_SERVER = 'Server';
  208. $FAULT_VERSION_MISMATCH = 'VersionMismatch';
  209. $FAULT_MUST_UNDERSTAND = 'MustUnderstand';
  210. $HTTP_ON_SUCCESS_CODE = 200; # OK
  211. $HTTP_ON_FAULT_CODE = 500; # INTERNAL_SERVER_ERROR
  212. %SOAP_VERSIONS = (
  213. ($SOAP_VERSION = 1.1) => {
  214. NEXT_ACTOR => 'http://schemas.xmlsoap.org/soap/actor/next',
  215. NS_ENV => 'http://schemas.xmlsoap.org/soap/envelope/',
  216. NS_ENC => 'http://schemas.xmlsoap.org/soap/encoding/',
  217. DEFAULT_XML_SCHEMA => 'http://www.w3.org/1999/XMLSchema',
  218. },
  219. 1.2 => {
  220. NEXT_ACTOR => 'http://www.w3.org/2001/06/soap-envelope/actor/next',
  221. NS_ENV => 'http://www.w3.org/2001/06/soap-envelope',
  222. NS_ENC => 'http://www.w3.org/2001/06/soap-encoding',
  223. DEFAULT_XML_SCHEMA => 'http://www.w3.org/2001/XMLSchema',
  224. },
  225. );
  226. # schema namespaces
  227. %XML_SCHEMAS = (
  228. 'http://www.w3.org/1999/XMLSchema' => 'SOAP::XMLSchema1999',
  229. 'http://www.w3.org/2001/XMLSchema' => 'SOAP::XMLSchema2001',
  230. 'http://schemas.xmlsoap.org/soap/encoding/' => 'SOAP::XMLSchemaSOAP1_1',
  231. 'http://www.w3.org/2001/06/soap-encoding' => 'SOAP::XMLSchemaSOAP1_2',
  232. );
  233. $NS_XSI_ALL = join join('|', map {"$_-instance"} grep {/XMLSchema/} keys %XML_SCHEMAS),
  234. '(?:', ')';
  235. $NS_XSI_NILS = join join('|', map { my $class = $XML_SCHEMAS{$_} . '::Serializer'; "\{($_)-instance\}" . $class->nilValue
  236. } grep {/XMLSchema/} keys %XML_SCHEMAS),
  237. '(?:', ')';
  238. # ApacheSOAP namespaces
  239. $NS_APS = 'http://xml.apache.org/xml-soap';
  240. # SOAP::Lite namespace
  241. $NS_SL = 'http://www.soaplite.com/';
  242. # default prefixes
  243. $PREFIX_ENV = 'SOAP-ENV';
  244. $PREFIX_ENC = 'SOAP-ENC';
  245. # others
  246. $DO_NOT_USE_XML_PARSER = 0;
  247. $DO_NOT_CHECK_MUSTUNDERSTAND = 0;
  248. $DO_NOT_USE_CHARSET = 0;
  249. }
  250. # ======================================================================
  251. package SOAP::Utils;
  252. sub qualify { $_[1] ? $_[1] =~ /:/ ? $_[1] : join(':', $_[0] || (), $_[1]) : defined $_[1] ? $_[0] : '' }
  253. sub overqualify (&$) { for ($_[1]) { &{$_[0]}; s/^:|:$//g } }
  254. sub disqualify {
  255. (my $qname = shift) =~ s/^($SOAP::Constants::NSMASK?)://;
  256. $qname;
  257. }
  258. sub longname { defined $_[0] ? sprintf('{%s}%s', $_[0], $_[1]) : $_[1] }
  259. sub splitlongname { local($1,$2); $_[0] =~ /^(?:\{(.*)\})?(.+)$/; return ($1,$2) }
  260. sub encode_data { (my $e = $_[0]) =~ s/([&<])/$1 eq '&'?'&amp;':'&lt;'/eg; $e }
  261. sub encode_attribute { (my $e = $_[0]) =~ s/([&<"])/$1 eq '&'?'&amp;':$1 eq '<'?'&lt;':'&quot;'/eg; $e }
  262. # ======================================================================
  263. package SOAP::Cloneable;
  264. sub clone {
  265. my $self = shift;
  266. return unless ref $self && UNIVERSAL::isa($self => __PACKAGE__);
  267. my $clone = bless {} => ref($self) || $self;
  268. foreach (keys %$self) {
  269. my $value = $self->{$_};
  270. $clone->{$_} = ref $value && UNIVERSAL::isa($value => __PACKAGE__) ? $value->clone : $value;
  271. }
  272. $clone;
  273. }
  274. # ======================================================================
  275. package SOAP::Transport;
  276. use vars qw($AUTOLOAD @ISA);
  277. @ISA = qw(SOAP::Cloneable);
  278. sub DESTROY { SOAP::Trace::objects('()') }
  279. sub new {
  280. my $self = shift;
  281. my $class = ref($self) || $self;
  282. return $self if ref $self;
  283. SOAP::Trace::objects('()');
  284. return bless {} => $class;
  285. }
  286. sub proxy {
  287. my $self = shift->new;
  288. my $class = ref $self;
  289. return $self->{_proxy} unless @_;
  290. $_[0] =~ /^(\w+):/ or die "proxy: transport protocol not specified\n";
  291. my $protocol = uc "$1"; # untainted now
  292. # https: should be done through Transport::HTTP.pm
  293. for ($protocol) { s/^HTTPS$/HTTP/ }
  294. (my $protocol_class = "${class}::$protocol") =~ s/-/_/g;
  295. no strict 'refs';
  296. unless (defined %{"$protocol_class\::Client::"} && UNIVERSAL::can("$protocol_class\::Client" => 'new')) {
  297. eval "require $protocol_class";
  298. die "Unsupported protocol '$protocol'\n" if $@ =~ m!^Can't locate SOAP/Transport/!;
  299. die if $@;
  300. }
  301. $protocol_class .= "::Client";
  302. return $self->{_proxy} = $protocol_class->new(endpoint => shift, @_);
  303. }
  304. sub AUTOLOAD {
  305. my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::') + 2);
  306. return if $method eq 'DESTROY';
  307. no strict 'refs';
  308. *$AUTOLOAD = sub { shift->proxy->$method(@_) };
  309. goto &$AUTOLOAD;
  310. }
  311. # ======================================================================
  312. package SOAP::Fault;
  313. use Carp ();
  314. sub DESTROY { SOAP::Trace::objects('()') }
  315. sub new {
  316. my $self = shift;
  317. unless (ref $self) {
  318. my $class = ref($self) || $self;
  319. $self = bless {} => $class;
  320. SOAP::Trace::objects('()');
  321. }
  322. Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1);
  323. while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  324. return $self;
  325. }
  326. sub BEGIN {
  327. no strict 'refs';
  328. for my $method (qw(faultcode faultstring faultactor faultdetail)) {
  329. my $field = '_' . $method;
  330. *$method = sub {
  331. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  332. if (@_) { $self->{$field} = shift; return $self }
  333. return $self->{$field};
  334. }
  335. }
  336. *detail = \&faultdetail;
  337. }
  338. # ======================================================================
  339. package SOAP::Data;
  340. use vars qw(@ISA @EXPORT_OK);
  341. use Exporter;
  342. use Carp ();
  343. @ISA = qw(Exporter);
  344. @EXPORT_OK = qw(name type attr value uri);
  345. sub DESTROY { SOAP::Trace::objects('()') }
  346. sub new {
  347. my $self = shift;
  348. unless (ref $self) {
  349. my $class = ref($self) || $self;
  350. $self = bless {_attr => {}, _value => [], _signature => []} => $class;
  351. SOAP::Trace::objects('()');
  352. }
  353. Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1);
  354. while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  355. return $self;
  356. }
  357. sub name {
  358. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  359. if (@_) {
  360. if ($_[0] && $_[0] =~ /^\{/) {
  361. my($uri, $name) = SOAP::Utils::splitlongname(shift);
  362. $self->uri($uri);
  363. $self->{_name} = $name;
  364. } else {
  365. $self->{_name} = shift;
  366. }
  367. $self->value(@_) if @_;
  368. return $self;
  369. }
  370. return $self->{_name};
  371. }
  372. sub attr {
  373. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  374. if (@_) { $self->{_attr} = shift; $self->value(@_) if @_; return $self }
  375. return $self->{_attr};
  376. }
  377. sub type {
  378. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  379. if (@_) {
  380. $self->{_type} = shift;
  381. $self->value(@_) if @_;
  382. return $self;
  383. }
  384. if (!defined $self->{_type} && (my @types = grep {/^\{$SOAP::Constants::NS_XSI_ALL}type$/o} keys %{$self->{_attr}})) {
  385. $self->{_type} = (SOAP::Utils::splitlongname(delete $self->{_attr}->{shift(@types)}))[1];
  386. }
  387. return $self->{_type};
  388. }
  389. BEGIN {
  390. no strict 'refs';
  391. for my $method (qw(root mustUnderstand)) {
  392. my $field = '_' . $method;
  393. *$method = sub {
  394. my $attr = $method eq 'root' ? "{$SOAP::Constants::NS_ENC}$method" : "{$SOAP::Constants::NS_ENV}$method";
  395. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  396. if (@_) {
  397. $self->{_attr}->{$attr} = $self->{$field} = shift() ? 1 : 0;
  398. $self->value(@_) if @_;
  399. return $self;
  400. }
  401. $self->{$field} = SOAP::XMLSchemaSOAP1_2::Deserializer->as_boolean($self->{_attr}->{$attr})
  402. if !defined $self->{$field} && defined $self->{_attr}->{$attr};
  403. return $self->{$field};
  404. }
  405. }
  406. for my $method (qw(actor encodingStyle)) {
  407. my $field = '_' . $method;
  408. *$method = sub {
  409. my $attr = "{$SOAP::Constants::NS_ENV}$method";
  410. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  411. if (@_) {
  412. $self->{_attr}->{$attr} = $self->{$field} = shift;
  413. $self->value(@_) if @_;
  414. return $self;
  415. }
  416. $self->{$field} = $self->{_attr}->{$attr}
  417. if !defined $self->{$field} && defined $self->{_attr}->{$attr};
  418. return $self->{$field};
  419. }
  420. }
  421. }
  422. sub uri {
  423. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  424. return $self->{_uri} unless @_;
  425. my $uri = $self->{_uri} = $self->{_attr}->{'xmlns:~'} = shift;
  426. warn "Usage of '::' in URI ($uri) is deprecated. Use '/' instead\n"
  427. if defined $uri && $^W && $uri =~ /::/;
  428. $self->value(@_) if @_;
  429. return $self;
  430. }
  431. sub set_value {
  432. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  433. $self->{_value} = [@_];
  434. return $self;
  435. }
  436. sub value {
  437. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  438. @_ ? ($self->set_value(@_), return $self)
  439. : wantarray ? return @{$self->{_value}} : return $self->{_value}->[0];
  440. }
  441. sub signature {
  442. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  443. @_ ? ($self->{_signature} = shift, return $self) : (return $self->{_signature});
  444. }
  445. # ======================================================================
  446. package SOAP::Header;
  447. use vars qw(@ISA);
  448. @ISA = qw(SOAP::Data);
  449. # ======================================================================
  450. package SOAP::Serializer;
  451. use Carp ();
  452. use vars qw(@ISA);
  453. @ISA = qw(SOAP::Cloneable SOAP::XMLSchema::Serializer);
  454. BEGIN {
  455. # namespaces and anonymous data structures
  456. my $ns = 0;
  457. my $name = 0;
  458. my $prefix = 'c-';
  459. sub gen_ns { 'namesp' . ++$ns }
  460. sub gen_name { join '', $prefix, 'gensym', ++$name }
  461. sub prefix { $prefix =~ s/^[^\-]+-/$_[1]-/; $_[0]; }
  462. }
  463. sub DESTROY { SOAP::Trace::objects('()') }
  464. sub new {
  465. my $self = shift;
  466. unless (ref $self) {
  467. my $class = ref($self) || $self;
  468. $self = bless {
  469. _level => 0,
  470. _autotype => 1,
  471. _readable => 0,
  472. _multirefinplace => 0,
  473. _seen => {},
  474. _typelookup => {
  475. base64 => [10, sub {$_[0] =~ /[^\x09\x0a\x0d\x20-\x7f]/}, 'as_base64'],
  476. int => [20, sub {$_[0] =~ /^[+-]?\d+$/}, 'as_int'],
  477. float => [30, sub {$_[0] =~ /^(-?(?:\d+(?:\.\d*)?|\.\d+|NaN|INF)|([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?)$/}, 'as_float'],
  478. string => [40, sub {1}, 'as_string'],
  479. },
  480. _encoding => 'UTF-8',
  481. _objectstack => {},
  482. _signature => [],
  483. _maptype => {SOAPStruct => $SOAP::Constants::NS_APS},
  484. _on_nonserialized => sub {Carp::carp "Cannot marshall @{[ref shift]} reference" if $^W; return},
  485. _attr => {
  486. "{$SOAP::Constants::NS_ENV}encodingStyle" => $SOAP::Constants::NS_ENC,
  487. },
  488. _namespaces => {
  489. $SOAP::Constants::NS_ENC => $SOAP::Constants::PREFIX_ENC,
  490. $SOAP::Constants::PREFIX_ENV ? ($SOAP::Constants::NS_ENV => $SOAP::Constants::PREFIX_ENV) : (),
  491. },
  492. _soapversion => SOAP::Lite->soapversion,
  493. } => $class;
  494. $self->xmlschema($SOAP::Constants::DEFAULT_XML_SCHEMA);
  495. SOAP::Trace::objects('()');
  496. }
  497. Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1);
  498. while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  499. return $self;
  500. }
  501. sub soapversion {
  502. my $self = shift;
  503. return $self->{_soapversion} unless @_;
  504. return $self if $self->{_soapversion} eq SOAP::Lite->soapversion;
  505. $self->{_soapversion} = shift;
  506. $self->attr({
  507. "{$SOAP::Constants::NS_ENV}encodingStyle" => $SOAP::Constants::NS_ENC,
  508. });
  509. $self->namespaces({
  510. $SOAP::Constants::NS_ENC => $SOAP::Constants::PREFIX_ENC,
  511. $SOAP::Constants::PREFIX_ENV ? ($SOAP::Constants::NS_ENV => $SOAP::Constants::PREFIX_ENV) : (),
  512. });
  513. $self->xmlschema($SOAP::Constants::DEFAULT_XML_SCHEMA);
  514. $self;
  515. }
  516. sub xmlschema {
  517. my $self = shift->new;
  518. return $self->{_xmlschema} unless @_;
  519. my @schema;
  520. if ($_[0]) {
  521. @schema = grep {/XMLSchema/ && /$_[0]/} keys %SOAP::Constants::XML_SCHEMAS;
  522. Carp::croak "More than one schema match parameter '$_[0]': @{[join ', ', @schema]}" if @schema > 1;
  523. Carp::croak "No schema match parameter '$_[0]'" if @schema != 1;
  524. }
  525. # do nothing if current schema is the same as new
  526. return $self if $self->{_xmlschema} && $self->{_xmlschema} eq $schema[0];
  527. my $ns = $self->namespaces;
  528. # delete current schema from namespaces
  529. if (my $schema = $self->{_xmlschema}) {
  530. delete $ns->{$schema};
  531. delete $ns->{"$schema-instance"};
  532. }
  533. # add new schema into namespaces
  534. if (my $schema = $self->{_xmlschema} = shift @schema) {
  535. $ns->{$schema} = 'xsd';
  536. $ns->{"$schema-instance"} = 'xsi';
  537. }
  538. # and here is the class serializer should work with
  539. my $class = exists $SOAP::Constants::XML_SCHEMAS{$self->{_xmlschema}} ?
  540. $SOAP::Constants::XML_SCHEMAS{$self->{_xmlschema}} . '::Serializer' : $self;
  541. $self->xmlschemaclass($class);
  542. return $self;
  543. }
  544. sub namespace {
  545. Carp::carp "'SOAP::Serializer->namespace' method is deprecated. Instead use '->envprefix'" if $^W;
  546. shift->envprefix(@_);
  547. }
  548. sub encodingspace {
  549. Carp::carp "'SOAP::Serializer->encodingspace' method is deprecated. Instead use '->encprefix'" if $^W;
  550. shift->encprefix(@_);
  551. }
  552. sub envprefix {
  553. my $self = shift->new;
  554. return $self->namespaces->{$SOAP::Constants::NS_ENV} unless @_;
  555. $self->namespaces->{$SOAP::Constants::NS_ENV} = shift;
  556. return $self;
  557. }
  558. sub encprefix {
  559. my $self = shift->new;
  560. return $self->namespaces->{$SOAP::Constants::NS_ENC} unless @_;
  561. $self->namespaces->{$SOAP::Constants::NS_ENC} = shift;
  562. return $self;
  563. }
  564. sub BEGIN {
  565. no strict 'refs';
  566. for my $method (qw(readable level seen autotype typelookup uri attr maptype
  567. namespaces multirefinplace encoding signature
  568. on_nonserialized)) {
  569. my $field = '_' . $method;
  570. *$method = sub {
  571. my $self = shift->new;
  572. @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  573. }
  574. }
  575. for my $method (qw(method fault freeform)) { # aliases for envelope
  576. *$method = sub { shift->envelope($method => @_) }
  577. }
  578. for my $method (qw(qualify overqualify disqualify)) { # import from SOAP::Utils
  579. *$method = \&{'SOAP::Utils::'.$method};
  580. }
  581. }
  582. sub gen_id { sprintf "%U", $_[1] }
  583. sub multiref_object {
  584. my $self = shift;
  585. my $object = shift;
  586. my $id = $self->gen_id($object);
  587. my $seen = $self->seen;
  588. $seen->{$id}->{count}++;
  589. $seen->{$id}->{multiref} ||= $seen->{$id}->{count} > 1;
  590. $seen->{$id}->{value} = $object;
  591. $seen->{$id}->{recursive} ||= 0;
  592. return $id;
  593. }
  594. sub recursive_object {
  595. my $self = shift;
  596. $self->seen->{$self->gen_id(shift)}->{recursive} = 1;
  597. }
  598. sub is_href {
  599. my $self = shift;
  600. my $seen = $self->seen->{shift || return} or return;
  601. return 1 if $seen->{id};
  602. return $seen->{multiref} &&
  603. !($seen->{id} = (shift ||
  604. $seen->{recursive} ||
  605. $seen->{multiref} && $self->multirefinplace));
  606. }
  607. sub multiref_anchor {
  608. my $seen = shift->seen->{my $id = shift || return undef};
  609. return $seen->{multiref} ? "ref-$id" : undef;
  610. }
  611. sub encode_multirefs {
  612. my $self = shift;
  613. return if $self->multirefinplace;
  614. my $seen = $self->seen;
  615. map { $_->[1]->{_id} = 1; $_
  616. } map { $self->encode_object($seen->{$_}->{value})
  617. } grep { $seen->{$_}->{multiref} && !$seen->{$_}->{recursive}
  618. } keys %$seen;
  619. }
  620. # ----------------------------------------------------------------------
  621. sub maptypetouri {
  622. my ($self, $type) = @_;
  623. if (defined $type && $type !~ /:/) {
  624. (my $fixed = $type) =~ s/__/::/g;
  625. $self->maptype->{$fixed} = $self->uri || return $type
  626. unless exists $self->maptype->{$fixed};
  627. $type = $self->maptype->{$fixed}
  628. ? qualify($self->namespaces->{$self->maptype->{$fixed}} ||= gen_ns, $type)
  629. : undef;
  630. }
  631. return $type;
  632. }
  633. sub encode_object {
  634. my($self, $object, $name, $type, $attr) = @_;
  635. $attr ||= {};
  636. return $self->encode_scalar($object, $name, $type, $attr) unless ref $object;
  637. my $id = $self->multiref_object($object);
  638. use vars '%objectstack'; # we'll play with symbol table
  639. local %objectstack = %objectstack; # want to see objects ONLY in the current tree
  640. # did we see this object in current tree? Seems to be recursive refs
  641. $self->recursive_object($object) if ++$objectstack{$id} > 1;
  642. # return if we already saw it twice. It should be already properly serialized
  643. return if $objectstack{$id} > 2;
  644. if (UNIVERSAL::isa($object => 'SOAP::Data')) {
  645. # using $object->SOAP::Data:: to enable overriding name() and others in inherited classes
  646. $object->SOAP::Data::name($name) unless defined $object->SOAP::Data::name;
  647. my @realvalues = $object->SOAP::Data::value;
  648. my $attr = $self->attrstoqname($object->SOAP::Data::attr);
  649. return [$object->SOAP::Data::name || gen_name, $attr] unless @realvalues;
  650. my $method = "as_" . ($object->SOAP::Data::type || '-'); # dummy type if not defined
  651. # try to call method specified for this type
  652. my @values = map {
  653. $self->can($method) && $self->$method($_, $object->SOAP::Data::name || gen_name, $object->SOAP::Data::type, {(defined() ? () : (qualify(xsi => $self->xmlschemaclass->nilValue) => $self->xmlschemaclass->as_undef(1))), %$attr})
  654. || $self->typecast($_, $object->SOAP::Data::name || gen_name, $object->SOAP::Data::type, $attr)
  655. || $self->encode_object($_, $object->SOAP::Data::name, $object->SOAP::Data::type, $attr)
  656. } @realvalues;
  657. $object->SOAP::Data::signature([map {join $;, $_->[0], disqualify($_->[1]->{'xsi:type'} || '')} @values]) if @values;
  658. return wantarray ? @values : $values[0];
  659. }
  660. my $class = ref $object;
  661. if ($class !~ /^(?:SCALAR|ARRAY|HASH|REF)$/o) {
  662. # we could also check for CODE|GLOB|LVALUE, but we cannot serialize
  663. # them anyway, so they'll be cought by check below
  664. $class =~ s/::/__/g;
  665. $name = $class if !defined $name;
  666. $type = $class if !defined $type && $self->autotype;
  667. my $method = 'as_' . $class;
  668. if ($self->can($method)) {
  669. my $encoded = $self->$method($object, $name, $type, $attr);
  670. return $encoded if ref $encoded;
  671. # return only if handled, otherwise handle with default handlers
  672. }
  673. }
  674. return
  675. UNIVERSAL::isa($object => 'REF') ||
  676. UNIVERSAL::isa($object => 'SCALAR') ? $self->encode_scalar($object, $name, $type, $attr) :
  677. UNIVERSAL::isa($object => 'ARRAY') ? $self->encode_array($object, $name, $type, $attr) :
  678. UNIVERSAL::isa($object => 'HASH') ? $self->encode_hash($object, $name, $type, $attr) :
  679. $self->on_nonserialized->($object);
  680. }
  681. sub encode_scalar {
  682. my($self, $value, $name, $type, $attr) = @_;
  683. $name ||= gen_name;
  684. my $schemaclass = $self->xmlschemaclass;
  685. # null reference
  686. return [$name, {%$attr, qualify(xsi => $schemaclass->nilValue) => $schemaclass->as_undef(1)}] unless defined $value;
  687. # object reference
  688. return [$name, $attr, [$self->encode_object($$value)], $self->gen_id($value)] if ref $value;
  689. # defined type
  690. return [$name, {%$attr, 'xsi:type' => qualify('xsd' => $self->maptypetouri($type))}, $value] if defined $type;
  691. # autodefined type
  692. if ($self->autotype) {
  693. my $lookup = $self->typelookup;
  694. for (sort {$lookup->{$a}->[0] <=> $lookup->{$b}->[0]} keys %$lookup) {
  695. my $method = $lookup->{$_}->[2];
  696. return $self->can($method) && $self->$method($value, $name, $type, $attr)
  697. || $method->($value, $name, $type, $attr)
  698. if $lookup->{$_}->[1]->($value);
  699. }
  700. }
  701. # invariant
  702. return [$name, $attr, $value];
  703. }
  704. sub encode_array {
  705. my($self, $array, $name, $type, $attr) = @_;
  706. my $items = 'item';
  707. # TD: add support for multidimensional, partially transmitted and sparse arrays
  708. my @items = map {$self->encode_object($_, $items)} @$array;
  709. my $num = @items;
  710. my($arraytype, %types) = '-';
  711. for (@items) { $arraytype = $_->[1]->{'xsi:type'} || '-'; $types{$arraytype}++ }
  712. $arraytype = sprintf "%s\[$num]", keys %types > 1 || $arraytype eq '-' ? qualify(xsd => $self->xmlschemaclass->anyTypeValue) : $arraytype;
  713. $type = 'Array' if $self->autotype && !defined $type; # make ApacheSOAP users happy
  714. return [$name || qualify($self->encprefix => 'Array'),
  715. {qualify($self->encprefix => 'arrayType') => $arraytype, 'xsi:type' => qualify($self->encprefix => $type), %$attr},
  716. [@items], $self->gen_id($array)
  717. ];
  718. }
  719. sub encode_hash {
  720. my($self, $hash, $name, $type, $attr) = @_;
  721. if ($self->autotype && grep {!/$SOAP::Constants::ELMASK/o} keys %$hash) {
  722. warn qq!Cannot encode @{[$name ? "'$name'" : 'unnamed']} element as 'hash'. Will be encoded as 'map' instead\n! if $^W;
  723. return $self->as_map($hash, $name || gen_name, $type, $attr);
  724. }
  725. $type = 'SOAPStruct' if $self->autotype && !defined $type && exists $self->maptype->{SOAPStruct}; # make ApacheSOAP users happy
  726. return [$name || gen_name,
  727. {'xsi:type' => qualify($self->encprefix => $self->maptypetouri($type)), %$attr},
  728. [map {$self->encode_object($hash->{$_}, $_)} keys %$hash],
  729. $self->gen_id($hash)
  730. ];
  731. }
  732. # ----------------------------------------------------------------------
  733. sub as_ordered_hash {
  734. my $self = shift;
  735. my($value, $name, $type, $attr) = @_;
  736. die "Not an ARRAY reference for 'ordered_hash' type" unless UNIVERSAL::isa($value => 'ARRAY');
  737. return [$name, $attr,
  738. [map{$self->encode_object(@{$value}[2*$_+1,2*$_])} 0..$#$value/2],
  739. $self->gen_id($value)
  740. ];
  741. }
  742. sub as_map {
  743. my $self = shift;
  744. my($value, $name, $type, $attr) = @_;
  745. die "Not a HASH reference for 'map' type" unless UNIVERSAL::isa($value => 'HASH');
  746. my $prefix = ($self->namespaces->{$SOAP::Constants::NS_APS} ||= 'xmlsoap');
  747. my @items = map {$self->encode_object(SOAP::Data->type(ordered_hash => [key => $_, value => $value->{$_}]), 'item', '')} keys %$value;
  748. return [$name, {'xsi:type' => "$prefix:Map", %$attr}, [@items], $self->gen_id($value)];
  749. }
  750. sub as_xml {
  751. my $self = shift;
  752. my($value, $name, $type, $attr) = @_;
  753. return [$name, {'_xml' => 1}, $value];
  754. }
  755. sub typecast {
  756. my $self = shift;
  757. my($value, $name, $type, $attr) = @_;
  758. return if ref $value; # skip complex object, caller knows how to deal with it
  759. return if $self->autotype && !defined $type; # we don't know, autotype knows
  760. return [$name,
  761. {(defined $type && $type gt '' ? ('xsi:type' => qualify('xsd' => $self->maptypetouri($type))) : ()), %$attr},
  762. $value
  763. ];
  764. }
  765. # ----------------------------------------------------------------------
  766. sub toqname {
  767. my $self = shift;
  768. my $long = shift;
  769. return $long unless $long =~ /^\{(.*)\}(.+)$/;
  770. return qualify $self->namespaces->{$1} ||= gen_ns, $2;
  771. }
  772. sub attrstoqname {
  773. my $self = shift;
  774. my $attrs = shift;
  775. return {
  776. map { /^\{(.*)\}(.+)$/
  777. ? ($self->toqname($_) => $2 eq 'type' || $2 eq 'arrayType' ? $self->toqname($attrs->{$_}) : $attrs->{$_})
  778. : ($_ => $attrs->{$_})
  779. } keys %$attrs
  780. };
  781. }
  782. sub tag {
  783. my $self = shift;
  784. my($tag, $attrs, @values) = @_;
  785. my $value = join '', @values;
  786. my $level = $self->level;
  787. my $indent = $self->readable ? "\n" . ' ' x (($level-1)*2) : '';
  788. # check for special attribute
  789. return "$indent$value" if exists $attrs->{_xml} && delete $attrs->{_xml};
  790. die "Element '$tag' can't be allowed in valid XML message. Died\n"
  791. if $tag !~ /^(?![xX][mM][lL])$SOAP::Constants::NSMASK$/o;
  792. my $prolog = '';
  793. if ($level == 1) {
  794. my $namespaces = $self->namespaces;
  795. foreach (keys %$namespaces) { $attrs->{qualify(xmlns => $namespaces->{$_})} = $_ }
  796. $prolog = qq!<?xml version="1.0" encoding="@{[$self->encoding]}"?>!;
  797. }
  798. my $tagattrs = join(' ', '', map { sprintf '%s="%s"', $_, SOAP::Utils::encode_attribute($attrs->{$_}) }
  799. grep { $_ && defined $attrs->{$_} && ($_ ne 'xsi:type' || $attrs->{$_} ne '')
  800. } keys %$attrs);
  801. $value gt ''
  802. ? sprintf("$prolog$indent<%s%s$indent>%s</%s>", $tag, $tagattrs, $value, $tag)
  803. : sprintf("$prolog$indent<%s%s/>", $tag, $tagattrs);
  804. }
  805. sub xmlize {
  806. my $self = shift;
  807. my($name, $attrs, $values, $id) = @{+shift}; $attrs ||= {};
  808. if (exists $attrs->{'xmlns:~'} && defined(my $xmlns = delete $attrs->{'xmlns:~'})) {
  809. my $ns = ($name =~ s/^($SOAP::Constants::NSMASK?):// ? $1 : gen_ns);
  810. # xmlns:a='' is incorrect, will be xmlns=''
  811. if ($xmlns ne '') {
  812. $attrs->{"xmlns:$ns"} = $xmlns;
  813. $name = "$ns:$name";
  814. } else {
  815. $attrs->{'xmlns'} = $xmlns;
  816. }
  817. }
  818. local $self->{_level} = $self->{_level} + 1;
  819. return $self->tag($name, $attrs) unless defined $values;
  820. return $self->tag($name, $attrs, $values) unless UNIVERSAL::isa($values => 'ARRAY');
  821. return $self->tag($name, {%$attrs, href => '#' . $self->multiref_anchor($id)}) if $self->is_href($id, delete($attrs->{_id}));
  822. return $self->tag($name, {%$attrs, id => $self->multiref_anchor($id)}, map {$self->xmlize($_)} @$values);
  823. }
  824. sub uriformethod {
  825. my $self = shift;
  826. my $method_is_data = ref $_[0] && UNIVERSAL::isa($_[0] => 'SOAP::Data');
  827. # drop prefrix from method that could be string or SOAP::Data object
  828. my $prefix = (my $method = $method_is_data ? $_[0]->name : $_[0]) =~ s/^($SOAP::Constants::NSMASK?)://
  829. ? $1 : '';
  830. my $attr = {reverse %{$self->namespaces}};
  831. # try to define namespace that could be stored as
  832. # a) method is SOAP::Data
  833. # ? attribute in method's element as xmlns= or xmlns:${prefix}=
  834. # : uri
  835. # b) attribute in Envelope element as xmlns= or xmlns:${prefix}=
  836. # c) no prefix or prefix equal serializer->envprefix
  837. # ? '', but see coment below
  838. # : die with error message
  839. my $uri = $method_is_data
  840. ? ref $_[0]->attr && ($_[0]->attr->{$prefix ? "xmlns:$prefix" : 'xmlns'} || $_[0]->attr->{'xmlns:~'})
  841. : $self->uri;
  842. defined $uri or $uri = $attr->{$prefix || ''};
  843. defined $uri or $uri = !$prefix || $prefix eq $self->envprefix
  844. # still in doubts what should namespace be in this case
  845. # but will keep it like this for now and be compatible with our server
  846. ? ( $method_is_data && $^W && warn("URI is not provided as an attribute for method ($method)\n"),
  847. ''
  848. )
  849. : die "Can't find namespace for method ($prefix:$method)\n";
  850. return ($uri, $method);
  851. }
  852. sub serialize { SOAP::Trace::trace('()');
  853. my $self = shift->new;
  854. @_ == 1 or Carp::croak "serialize() method accepts one parameter";
  855. $self->seen({}); # reinitialize multiref table
  856. my($encoded) = $self->encode_object($_[0]);
  857. # now encode multirefs if any
  858. # v -------------- subelements of Envelope
  859. push(@{$encoded->[2]}, $self->encode_multirefs) if ref $encoded->[2];
  860. return $self->xmlize($encoded);
  861. }
  862. sub envelope { SOAP::Trace::trace('()');
  863. my $self = shift->new;
  864. my $type = shift;
  865. my(@parameters, @header);
  866. for (@_) {
  867. defined $_ && ref $_ && UNIVERSAL::isa($_ => 'SOAP::Header')
  868. ? push(@header, $_) : push(@parameters, $_);
  869. }
  870. my $header = @header ? SOAP::Data->set_value(@header) : undef;
  871. my($body,$parameters);
  872. if ($type eq 'method' || $type eq 'response') {
  873. SOAP::Trace::method(@parameters);
  874. my $method = shift(@parameters) or die "Unspecified method for SOAP call\n";
  875. $parameters = @parameters ? SOAP::Data->set_value(@parameters) : undef;
  876. $body = UNIVERSAL::isa($method => 'SOAP::Data')
  877. ? $method : SOAP::Data->name($method)->uri($self->uri);
  878. $body->set_value($parameters ? \$parameters : ());
  879. } elsif ($type eq 'fault') {
  880. SOAP::Trace::fault(@parameters);
  881. $body = SOAP::Data
  882. -> name(qualify($self->envprefix => 'Fault'))
  883. # commented on 2001/03/28 because of failing in ApacheSOAP
  884. # need to find out more about it
  885. # -> attr({'xmlns' => ''})
  886. -> value(\SOAP::Data->set_value(
  887. SOAP::Data->name(faultcode => qualify($self->envprefix => $parameters[0])),
  888. SOAP::Data->name(faultstring => $parameters[1]),
  889. defined($parameters[2]) ? SOAP::Data->name(detail => do{my $detail = $parameters[2]; ref $detail ? \$detail : $detail}) : (),
  890. defined($parameters[3]) ? SOAP::Data->name(faultactor => $parameters[3]) : (),
  891. ));
  892. } elsif ($type eq 'freeform') {
  893. SOAP::Trace::freeform(@parameters);
  894. $body = SOAP::Data->set_value(@parameters);
  895. } else {
  896. die "Wrong type of envelope ($type) for SOAP call\n";
  897. }
  898. $self->seen({}); # reinitialize multiref table
  899. my($encoded) = $self->encode_object(
  900. SOAP::Data->name(qualify($self->envprefix => 'Envelope') => \SOAP::Data->value(
  901. ($header ? SOAP::Data->name(qualify($self->envprefix => 'Header') => \$header) : ()),
  902. SOAP::Data->name(qualify($self->envprefix => 'Body') => \$body)
  903. ))->attr($self->attr)
  904. );
  905. $self->signature($parameters->signature) if ref $parameters;
  906. # IMHO multirefs should be encoded after Body, but only some
  907. # toolkits understand this encoding, so we'll keep them for now (04/15/2001)
  908. # as the last element inside the Body
  909. # v -------------- subelements of Envelope
  910. # vv -------- last of them (Body)
  911. # v --- subelements
  912. push(@{$encoded->[2]->[-1]->[2]}, $self->encode_multirefs) if ref $encoded->[2]->[-1]->[2];
  913. return $self->xmlize($encoded);
  914. }
  915. # ======================================================================
  916. package SOAP::Parser;
  917. sub DESTROY { SOAP::Trace::objects('()') }
  918. sub xmlparser {
  919. my $self = shift;
  920. return eval { $SOAP::Constants::DO_NOT_USE_XML_PARSER ? undef : do {require XML::Parser; XML::Parser->new} } ||
  921. eval { require XML::Parser::Lite; XML::Parser::Lite->new } ||
  922. die "XML::Parser is not @{[$SOAP::Constants::DO_NOT_USE_XML_PARSER ? 'used' : 'available']} and ", $@;
  923. }
  924. sub parser {
  925. my $self = shift->new;
  926. @_ ? ($self->{'_parser'} = shift, return $self) : return ($self->{'_parser'} ||= $self->xmlparser);
  927. }
  928. sub new {
  929. my $self = shift;
  930. my $class = ref($self) || $self;
  931. return $self if ref $self;
  932. SOAP::Trace::objects('()');
  933. return bless {_parser => shift} => $class;
  934. }
  935. sub decode { SOAP::Trace::trace('()');
  936. my $self = shift;
  937. # mis(?)communication between SOAP::Parser, XML::Parser and
  938. # XML::Parser::Expat used to produce memory leak
  939. # Thanks to Ryan Adams <[email protected]>
  940. # checked by number of tests in t/02-payload.t
  941. $self->parser->setHandlers(
  942. Init => sub { shift; $self->init(@_) },
  943. Final => sub { shift; $self->final(@_) },
  944. Start => sub { shift; $self->start(@_) },
  945. End => sub { shift; $self->end(@_) },
  946. Char => sub { shift; $self->char(@_) }
  947. );
  948. $self->parser->parse($_[0]);
  949. }
  950. sub init { undef shift->{_values} }
  951. sub final { shift->{_done} }
  952. sub start { push @{shift->{_values}}, [shift, {@_}] }
  953. sub char { shift->{_values}->[-1]->[3] .= shift }
  954. sub end {
  955. my $self = shift;
  956. my $done = pop @{$self->{_values}};
  957. undef $done->[3] if ref $done->[2];
  958. @{$self->{_values}} ? (push @{$self->{_values}->[-1]->[2]}, $done)
  959. : ($self->{_done} = $done);
  960. }
  961. # ======================================================================
  962. package SOAP::MIMEParser;
  963. use vars qw(@ISA);
  964. @ISA = qw(MIME::Parser);
  965. sub DESTROY { SOAP::Trace::objects('()') }
  966. sub new { local $^W; require MIME::Parser; Exporter::require_version('MIME::Parser' => 5.220);
  967. my $self = shift;
  968. unless (ref $self) {
  969. my $class = ref($self) || $self;
  970. $self = $class->SUPER::new();
  971. unshift(@_, output_to_core => 'ALL', tmp_to_core => 1, ignore_errors => 1);
  972. SOAP::Trace::objects('()');
  973. }
  974. while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  975. return $self;
  976. }
  977. sub get_multipart_id { (shift || '') =~ /^<(.+)>$/; $1 || '' }
  978. sub decode {
  979. my $self = shift;
  980. my $entity = eval { $self->parse_data(shift) } or die "Something wrong with MIME message: @{[$@ || $self->last_error]}\n";
  981. my @result =
  982. $entity->head->mime_type eq 'multipart/form-data' ? $self->decode_form_data($entity) :
  983. $entity->head->mime_type eq 'multipart/related' ? $self->decode_related($entity) :
  984. $entity->head->mime_type eq 'text/xml' ? () :
  985. die "Can't handle MIME messsage with specified type (@{[$entity->head->mime_type]})\n";
  986. @result ? @result
  987. : $entity->bodyhandle->as_string ? [undef, '', undef, $entity->bodyhandle->as_string]
  988. : die "No content in MIME message\n";
  989. }
  990. sub decode_form_data {
  991. my($self, $entity) = @_;
  992. my @result;
  993. foreach my $part ($entity->parts) {
  994. my $name = $part->head->mime_attr('content-disposition.name');
  995. my $type = $part->head->mime_type || '';
  996. $name eq 'payload'
  997. ? unshift(@result, [$name, '', $type, $part->bodyhandle->as_string])
  998. : push(@result, [$name, '', $type, $part->bodyhandle->as_string]);
  999. }
  1000. @result;
  1001. }
  1002. sub decode_related {
  1003. my($self, $entity) = @_;
  1004. my $start = get_multipart_id($entity->head->mime_attr('content-type.start'));
  1005. my $location = $entity->head->mime_attr('content-location') || 'thismessage:/';
  1006. my @result;
  1007. foreach my $part ($entity->parts) {
  1008. my $pid = get_multipart_id($part->head->get('content-id',0));
  1009. my $plocation = $part->head->get('content-location',0) || '';
  1010. my $type = $part->head->mime_type || '';
  1011. $start && $pid eq $start
  1012. ? unshift(@result, [$start, $location, $type, $part->bodyhandle->as_string])
  1013. : push(@result, [$pid, $plocation, $type, $part->bodyhandle->as_string]);
  1014. }
  1015. die "Can't find 'start' parameter in multipart MIME message\n"
  1016. if @result > 1 && !$start;
  1017. @result;
  1018. }
  1019. # ======================================================================
  1020. package SOAP::SOM;
  1021. use Carp ();
  1022. sub BEGIN {
  1023. no strict 'refs';
  1024. my %path = (
  1025. root => '/',
  1026. envelope => '/Envelope',
  1027. body => '/Envelope/Body',
  1028. header => '/Envelope/Header',
  1029. headers => '/Envelope/Header/[>0]',
  1030. fault => '/Envelope/Body/Fault',
  1031. faultcode => '/Envelope/Body/Fault/faultcode',
  1032. faultstring => '/Envelope/Body/Fault/faultstring',
  1033. faultactor => '/Envelope/Body/Fault/faultactor',
  1034. faultdetail => '/Envelope/Body/Fault/detail',
  1035. );
  1036. for my $method (keys %path) {
  1037. *$method = sub {
  1038. my $self = shift;
  1039. ref $self or return $path{$method};
  1040. Carp::croak "Method '$method' is readonly and doesn't accept any parameters" if @_;
  1041. return $self->valueof($path{$method});
  1042. };
  1043. }
  1044. my %results = (
  1045. method => '/Envelope/Body/[1]',
  1046. result => '/Envelope/Body/[1]/[1]',
  1047. freeform => '/Envelope/Body/[>0]',
  1048. paramsin => '/Envelope/Body/[1]/[>0]',
  1049. paramsall => '/Envelope/Body/[1]/[>0]',
  1050. paramsout => '/Envelope/Body/[1]/[>1]',
  1051. );
  1052. for my $method (keys %results) {
  1053. *$method = sub {
  1054. my $self = shift;
  1055. ref $self or return $results{$method};
  1056. Carp::croak "Method '$method' is readonly and doesn't accept any parameters" if @_;
  1057. defined $self->fault ? return : return $self->valueof($results{$method});
  1058. };
  1059. }
  1060. }
  1061. # use object in boolean context return true/false on last match
  1062. # Ex.: $som->match('//Fault') ? 'SOAP call failed' : 'success';
  1063. use overload fallback => 1, 'bool' => sub { @{shift->{_current}} > 0 };
  1064. sub DESTROY { SOAP::Trace::objects('()') }
  1065. sub new {
  1066. my $self = shift;
  1067. my $class = ref($self) || $self;
  1068. my $content = shift;
  1069. SOAP::Trace::objects('()');
  1070. return bless { _content => $content, _current => [$content] } => $class;
  1071. }
  1072. sub valueof {
  1073. my $self = shift;
  1074. local $self->{_current} = $self->{_current};
  1075. $self->match(shift) if @_;
  1076. return wantarray ? map {$_->[4]} @{$self->{_current}}
  1077. : @{$self->{_current}} ? $self->{_current}->[0]->[4] : undef;
  1078. }
  1079. sub headerof { # SOAP::Header is the same as SOAP::Data, so just rebless it
  1080. wantarray
  1081. ? map { bless $_ => 'SOAP::Header' } shift->dataof(@_)
  1082. : bless shift->dataof(@_) => 'SOAP::Header';
  1083. }
  1084. sub dataof {
  1085. my $self = shift;
  1086. local $self->{_current} = $self->{_current};
  1087. $self->match(shift) if @_;
  1088. return wantarray ? map {$self->_as_data($_)} @{$self->{_current}}
  1089. : @{$self->{_current}} ? $self->_as_data($self->{_current}->[0]) : undef;
  1090. }
  1091. sub namespaceuriof {
  1092. my $self = shift;
  1093. local $self->{_current} = $self->{_current};
  1094. $self->match(shift) if @_;
  1095. return wantarray ? map {(SOAP::Utils::splitlongname($_->[0]))[0]} @{$self->{_current}}
  1096. : @{$self->{_current}} ? (SOAP::Utils::splitlongname($self->{_current}->[0]->[0]))[0] : undef;
  1097. }
  1098. sub _as_data {
  1099. my $self = shift;
  1100. my $pointer = shift;
  1101. SOAP::Data
  1102. -> new(name => $pointer->[0], attr => $pointer->[1])
  1103. -> set_value($pointer->[4]);
  1104. }
  1105. sub match {
  1106. my $self = shift;
  1107. my $path = shift;
  1108. $self->{_current} = [
  1109. $path =~ s!^/!! || !@{$self->{_current}}
  1110. ? $self->_traverse($self->{_content}, 1 => split '/' => $path)
  1111. : map {$self->_traverse_tree($_->[2], split '/' => $path)} @{$self->{_current}}
  1112. ];
  1113. return $self;
  1114. }
  1115. sub _traverse {
  1116. my $self = shift;
  1117. my($pointer, $itself, $path, @path) = @_;
  1118. if ($path && substr($path, 0, 1) eq '{') {
  1119. $path = join '/', $path, shift @path while @path && $path !~ /}/;
  1120. }
  1121. my($op, $num) = $path =~ /^\[(<=|<|>=|>|=|!=?)?(\d+)\]$/ if defined $path;
  1122. return $pointer unless defined $path;
  1123. $op = '==' unless $op; $op .= '=' if $op eq '=' || $op eq '!';
  1124. my $numok = defined $num && eval "$itself $op $num";
  1125. my $nameok = ($pointer->[0] || '') =~ /(?:^|\})$path$/ if defined $path; # name can be with namespace
  1126. my $anynode = $path eq '';
  1127. unless ($anynode) {
  1128. if (@path) {
  1129. return if defined $num && !$numok || !defined $num && !$nameok;
  1130. } else {
  1131. return $pointer if defined $num && $numok || !defined $num && $nameok;
  1132. return;
  1133. }
  1134. }
  1135. my @walk;
  1136. push @walk, $self->_traverse_tree([$pointer], @path) if $anynode;
  1137. push @walk, $self->_traverse_tree($pointer->[2], $anynode ? ($path, @path) : @path);
  1138. return @walk;
  1139. }
  1140. sub _traverse_tree {
  1141. my $self = shift;
  1142. my($pointer, @path) = @_;
  1143. my $itself = 1;
  1144. grep {defined}
  1145. map {$self->_traverse($_, $itself++, @path)}
  1146. grep {!exists $_->[1]->{"{$SOAP::Constants::NS_ENC}root"} ||
  1147. $_->[1]->{"{$SOAP::Constants::NS_ENC}root"} ne '0'}
  1148. @$pointer;
  1149. }
  1150. # ======================================================================
  1151. package SOAP::Deserializer;
  1152. use vars qw(@ISA);
  1153. @ISA = qw(SOAP::Cloneable);
  1154. sub DESTROY { SOAP::Trace::objects('()') }
  1155. sub BEGIN {
  1156. no strict 'refs';
  1157. for my $method (qw(ids hrefs parser base xmlschemas xmlschema)) {
  1158. my $field = '_' . $method;
  1159. *$method = sub {
  1160. my $self = shift->new;
  1161. @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  1162. }
  1163. }
  1164. }
  1165. sub new {
  1166. my $self = shift;
  1167. my $class = ref($self) || $self;
  1168. return $self if ref $self;
  1169. SOAP::Trace::objects('()');
  1170. return bless {
  1171. _ids => {},
  1172. _hrefs => {},
  1173. _parser => SOAP::Parser->new,
  1174. _xmlschemas => {
  1175. $SOAP::Constants::NS_APS => 'SOAP::XMLSchemaApacheSOAP::Deserializer',
  1176. map { $_ => $SOAP::Constants::XML_SCHEMAS{$_} . '::Deserializer'
  1177. } keys %SOAP::Constants::XML_SCHEMAS
  1178. },
  1179. } => $class;
  1180. }
  1181. sub mimeparser {
  1182. my $field = '_mimeparser';
  1183. my $self = shift->new;
  1184. @_ ? ($self->{$field} = shift, return $self)
  1185. : return $self->{$field} ||= new SOAP::MIMEParser;
  1186. }
  1187. sub is_xml {
  1188. $_[1] =~ /^\s*</ || $_[1] !~ /^[\w-]+:/;
  1189. }
  1190. sub baselocation {
  1191. my $self = shift;
  1192. my $location = shift;
  1193. if ($location) {
  1194. my $uri = URI->new($location);
  1195. # make absolute location if relative
  1196. $location = $uri->abs($self->base)->as_string unless $uri->scheme;
  1197. }
  1198. $location;
  1199. }
  1200. sub mimedecode {
  1201. my $self = shift->new;
  1202. my $body;
  1203. foreach ($self->mimeparser->decode($_[0])) {
  1204. my($id, $location, $type, $value) = @$_;
  1205. unless ($body) { # we are here for the first time, so it's a MAIN part
  1206. $body = $self->parser->decode($value);
  1207. $self->base($location); # store the base location
  1208. } else {
  1209. $location = $self->baselocation($location);
  1210. my $part = $type eq 'text/xml' ? $self->parser->decode($value) : ['', undef, undef, $value];
  1211. $self->ids->{$id} = $part if $id;
  1212. $self->ids->{$location} = $part if $location;
  1213. }
  1214. }
  1215. return $body;
  1216. }
  1217. sub decode {
  1218. my $self = shift->new;
  1219. return $self->is_xml($_[0])
  1220. ? $self->parser->decode($_[0])
  1221. : $self->mimedecode($_[0]);
  1222. }
  1223. sub deserialize { SOAP::Trace::trace('()');
  1224. my $self = shift->new;
  1225. # initialize
  1226. $self->hrefs({});
  1227. $self->ids({});
  1228. # TBD: find better way to signal parsing errors
  1229. my $parsed = $self->decode($_[0]); # TBD: die on possible errors in Parser?
  1230. # if there are some IDs (from mime processing), then process others
  1231. # otherwise delay till we first meet IDs
  1232. if (keys %{$self->ids()}) {$self->traverse_ids($parsed)} else {$self->ids($parsed)}
  1233. $self->decode_object($parsed);
  1234. return SOAP::SOM->new($parsed);
  1235. }
  1236. sub traverse_ids {
  1237. my $self = shift;
  1238. my $ref = shift;
  1239. my($undef, $attrs, $childs) = @$ref;
  1240. # ^^^^^^ to fix nasty error on Mac platform (Carl K. Cunningham)
  1241. $self->ids->{$attrs->{id}} = $ref if exists $attrs->{id};
  1242. return unless ref $childs;
  1243. for (@$childs) {$self->traverse_ids($_)};
  1244. }
  1245. sub decode_object {
  1246. my $self = shift;
  1247. my $ref = shift;
  1248. my($name, $attrs, $childs, $value) = @$ref;
  1249. use vars qw($ns %uris); # drop namespace from name
  1250. local %uris = (%uris, map {$_ => $attrs->{$_}} grep {/^xmlns(:|$)/} keys %$attrs);
  1251. # first check the attributes
  1252. foreach (keys %$attrs) {
  1253. do { $2 ne 'encodingStyle' ||
  1254. $uris{"xmlns:$1"} ne $SOAP::Constants::NS_ENV ||
  1255. length($attrs->{$_}) == 0 || # encodingStyle=""
  1256. $attrs->{$_} =~ /\b$SOAP::Constants::NS_ENC/ ||
  1257. die "Unrecognized/unsupported value of encodingStyle attribute\n" },
  1258. do { $1 =~ /^[xX][mX][lL]/ ||
  1259. $uris{"xmlns:$1"} &&
  1260. do {
  1261. $attrs->{SOAP::Utils::longname($uris{"xmlns:$1"}, $2)} = do {
  1262. my $value = delete $attrs->{$_};
  1263. $2 ne 'type' && $2 ne 'arrayType'
  1264. ? $value
  1265. : SOAP::Utils::longname($value =~ m/^($SOAP::Constants::NSMASK?):(${SOAP::Constants::NSMASK}(?:\[[\d,]*\])*)/
  1266. ? ($uris{"xmlns:$1"} || die("Unresolved prefix '$1' for attribute value '$value'\n"), $2)
  1267. : ($uris{'xmlns'} || die("Unspecified namespace for type '$value'\n"), $value)
  1268. );
  1269. };
  1270. 1;
  1271. } ||
  1272. die "Unresolved prefix '$1' for attribute '$_'\n" }
  1273. if m/^($SOAP::Constants::NSMASK?):($SOAP::Constants::NSMASK)$/;
  1274. }
  1275. # and now check the element
  1276. local $ns = ($name =~ s/^($SOAP::Constants::NSMASK?):// ? $1 : '');
  1277. $ref->[0] = SOAP::Utils::longname(
  1278. $ns ? ($uris{"xmlns:$ns"} || die "Unresolved prefix '$ns' for element '$name'\n")
  1279. : ($uris{"xmlns"} || undef), # that's ok
  1280. $name
  1281. );
  1282. return $name => ($ref->[4] = $self->decode_value($ref));
  1283. }
  1284. sub decode_value {
  1285. my $self = shift;
  1286. my $ref = shift;
  1287. my($name, $attrs, $childs, $value) = @$ref;
  1288. my $arraytype = delete $attrs->{'~:type'};
  1289. # either specified with xsi:type, or <enc:name/> or array element
  1290. my($type) = grep {defined}
  1291. map($attrs->{$_}, grep {/^\{$SOAP::Constants::NS_XSI_ALL\}type$/o} keys %$attrs),
  1292. $name =~ /^\{$SOAP::Constants::NS_ENC\}/ ? $name : $arraytype;
  1293. # $name is not used here since type should be encoded as type, not as name
  1294. my($schema, $class) = SOAP::Utils::splitlongname($type) if $type;
  1295. my $schemaclass = $schema && $self->xmlschemas->{$schema}
  1296. || $self;
  1297. # store schema that is used in parsed message
  1298. $self->xmlschema($schema) if $schema && $schema =~ /XMLSchema/;
  1299. # don't use class/type if anyType/ur-type is specified on wire
  1300. undef $class if $schemaclass->can('anyTypeValue') && $schemaclass->anyTypeValue eq $class;
  1301. my $method = 'as_' . ($class || '-'); # dummy type if not defined
  1302. $class =~ s/__/::/g if $class;
  1303. my $id = $attrs->{id};
  1304. if (defined $id && exists $self->hrefs->{$id}) {
  1305. return $self->hrefs->{$id};
  1306. } elsif (exists $attrs->{href}) {
  1307. (my $id = delete $attrs->{href}) =~ s/^(#|cid:)?//;
  1308. # convert to absolute if not internal '#' or 'cid:'
  1309. $id = $self->baselocation($id) unless $1;
  1310. return $self->hrefs->{$id} if exists $self->hrefs->{$id};
  1311. my $ids = $self->ids;
  1312. # first time optimization. we don't traverse IDs unless asked for it
  1313. if (ref $ids ne 'HASH') { $self->ids({}); $self->traverse_ids($ids); $ids = $self->ids }
  1314. if (exists $ids->{$id}) {
  1315. my $obj = ($self->decode_object(delete $ids->{$id}))[1];
  1316. return $self->hrefs->{$id} = $obj;
  1317. } else {
  1318. die "Unresolved (wrong?) href ($id) in element '$name'\n";
  1319. }
  1320. }
  1321. return undef if grep {
  1322. /^$SOAP::Constants::NS_XSI_NILS$/ &&
  1323. $self->xmlschemas->{$1 || $2}->as_undef($attrs->{$_})
  1324. } keys %$attrs;
  1325. # try to handle with typecasting
  1326. my $res = $self->typecast($value, $name, $attrs, $childs, $type);
  1327. return $res if defined $res;
  1328. # ok, continue with others
  1329. if (exists $attrs->{"{$SOAP::Constants::NS_ENC}arrayType"}) {
  1330. my $res = [];
  1331. $self->hrefs->{$id} = $res if defined $id;
  1332. my($type, $multisize) = $attrs->{"{$SOAP::Constants::NS_ENC}arrayType"} =~ /^(.+)\[(\d*(?:,\d+)*)\]$/;
  1333. my $size = 1; foreach (split /,/, $multisize) { $size *= $_ || 0 }
  1334. # multidimensional
  1335. if ($multisize =~ /,/) {
  1336. @$res = splitarray([map {$_?$_:undef} split /,/, $multisize],
  1337. [map { $_->[1]->{'~:type'} = $type; scalar(($self->decode_object($_))[1])
  1338. } @{$childs || []}
  1339. ]);
  1340. # normal
  1341. } else {
  1342. @$res = map { $_->[1]->{'~:type'} = $type; scalar(($self->decode_object($_))[1])
  1343. } @{$childs || []};
  1344. }
  1345. # sparse (position)
  1346. if (ref $childs && exists $childs->[0]->[1]->{"{$SOAP::Constants::NS_ENC}position"}) {
  1347. my @new;
  1348. for (my $pos = 0; $pos < @$childs; $pos++) {
  1349. my($position) = $childs->[$pos]->[1]->{"{$SOAP::Constants::NS_ENC}position"} =~ /^\[(\d+)\]$/
  1350. or die "Position must be specified for all elements of sparse array\n";
  1351. $new[$position-1] = $res->[$pos];
  1352. }
  1353. @$res = @new;
  1354. }
  1355. # partially transmitted (offset)
  1356. my($offset) = $attrs->{"{$SOAP::Constants::NS_ENC}offset"} =~ /^\[(\d+)\]$/
  1357. if exists $attrs->{"{$SOAP::Constants::NS_ENC}offset"};
  1358. unshift(@$res, (undef) x $offset) if $offset;
  1359. die "Too many elements in array. @{[scalar@$res]} instead of claimed $multisize ($size)\n"
  1360. if $multisize && $size < @$res;
  1361. return defined $class && $class ne 'Array' ? bless($res => $class) : $res;
  1362. } elsif ($name =~ /^\{$SOAP::Constants::NS_ENC\}Struct$/ || !$schemaclass->can($method) && (ref $childs || defined $class && !defined $value)) {
  1363. my $res = {};
  1364. $self->hrefs->{$id} = $res if defined $id;
  1365. %$res = map {$self->decode_object($_)} @{$childs || []};
  1366. return defined $class && $class ne 'SOAPStruct' ? bless($res => $class) : $res;
  1367. } else {
  1368. my $res;
  1369. if ($schemaclass->can($method)) {
  1370. $method = "$schemaclass\::$method" unless ref $schemaclass;
  1371. $res = $self->$method($value, $name, $attrs, $childs, $type);
  1372. } else {
  1373. $res = $self->typecast($value, $name, $attrs, $childs, $type);
  1374. $res = $class ? die "Unrecognized type '$type'\n" : $value
  1375. unless defined $res;
  1376. }
  1377. $self->hrefs->{$id} = $res if defined $id;
  1378. return $res;
  1379. }
  1380. }
  1381. sub splitarray {
  1382. my @sizes = @{+shift};
  1383. my $size = shift @sizes;
  1384. my $array = shift;
  1385. return splice(@$array, 0, $size) unless @sizes;
  1386. my @array = ();
  1387. push @array, [splitarray([@sizes], $array)] while @$array && (!defined $size || $size--);
  1388. return @array;
  1389. }
  1390. sub typecast { } # typecast is called for both objects AND scalar types
  1391. # check ref of the second parameter (first is the object)
  1392. # return undef if you don't want to handle it
  1393. # ======================================================================
  1394. package SOAP::Client;
  1395. sub BEGIN {
  1396. no strict 'refs';
  1397. for my $method (qw(endpoint code message is_success status options)) {
  1398. my $field = '_' . $method;
  1399. *$method = sub {
  1400. my $self = shift->new;
  1401. @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  1402. }
  1403. }
  1404. }
  1405. # ======================================================================
  1406. package SOAP::Server::Object;
  1407. sub gen_id; *gen_id = \&SOAP::Serializer::gen_id;
  1408. my %alive;
  1409. my %objects;
  1410. sub objects_by_reference {
  1411. shift;
  1412. while (@_) { @alive{shift()} = ref $_[0] ? shift : sub { $_[1]-$_[$_[5] ? 5 : 4] > 600 } }
  1413. keys %alive;
  1414. }
  1415. sub reference {
  1416. my $self = shift;
  1417. my $stamp = time;
  1418. my $object = shift;
  1419. my $id = $stamp . $self->gen_id($object);
  1420. # this is code for garbage collection
  1421. my $time = time;
  1422. my $type = ref $object;
  1423. my @objects = grep { $objects{$_}->[1] eq $type } keys %objects;
  1424. for (grep { $alive{$type}->(scalar @objects, $time, @{$objects{$_}}) } @objects) {
  1425. delete $objects{$_};
  1426. }
  1427. $objects{$id} = [$object, $type, $stamp];
  1428. bless { id => $id } => ref $object;
  1429. }
  1430. sub references {
  1431. my $self = shift;
  1432. return @_ unless %alive; # small optimization
  1433. map { ref($_) && exists $alive{ref $_} ? $self->reference($_) : $_ } @_;
  1434. }
  1435. sub object {
  1436. my $self = shift;
  1437. my $class = ref($self) || $self;
  1438. my $object = shift;
  1439. return $object unless ref($object) && $alive{ref $object} && exists $object->{id};
  1440. my $reference = $objects{$object->{id}};
  1441. die "Object with specified id couldn't be found\n" unless ref $reference->[0];
  1442. $reference->[3] = time; # last access time
  1443. return $reference->[0]; # reference to actual object
  1444. }
  1445. sub objects {
  1446. my $self = shift;
  1447. return @_ unless %alive; # small optimization
  1448. map { ref($_) && exists $alive{ref $_} && exists $_->{id} ? $self->object($_) : $_ } @_;
  1449. }
  1450. # ======================================================================
  1451. package SOAP::Server::Parameters;
  1452. # ======================================================================
  1453. package SOAP::Server;
  1454. use Carp ();
  1455. sub DESTROY { SOAP::Trace::objects('()') }
  1456. sub new {
  1457. my $self = shift;
  1458. unless (ref $self) {
  1459. my $class = ref($self) || $self;
  1460. my(@params, @methods);
  1461. while (@_) { my($method, $params) = splice(@_,0,2);
  1462. $class->can($_[0]) ? push(@methods, $method, $params)
  1463. : $^W && Carp::carp "Unrecognized parameter '$method' in new()";
  1464. }
  1465. $self = bless {
  1466. _dispatch_to => [],
  1467. _dispatch_with => {},
  1468. _dispatched => [],
  1469. _action => '',
  1470. _options => {},
  1471. } => $class;
  1472. unshift(@methods, $self->initialize);
  1473. while (@methods) { my($method, $params) = splice(@methods,0,2);
  1474. $self->$method(ref $params eq 'ARRAY' ? @$params : $params)
  1475. }
  1476. SOAP::Trace::objects('()');
  1477. }
  1478. Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1);
  1479. while (@_) { my($method, $params) = splice(@_,0,2);
  1480. $self->can($method)
  1481. ? $self->$method(ref $params eq 'ARRAY' ? @$params : $params)
  1482. : $^W && Carp::carp "Unrecognized parameter '$method' in new()"
  1483. }
  1484. return $self;
  1485. }
  1486. sub initialize {
  1487. return (
  1488. serializer => SOAP::Serializer->new,
  1489. deserializer => SOAP::Deserializer->new,
  1490. on_action => sub {},
  1491. on_dispatch => sub {return},
  1492. );
  1493. }
  1494. sub BEGIN {
  1495. no strict 'refs';
  1496. for my $method (qw(action myuri serializer deserializer options dispatch_with)) {
  1497. my $field = '_' . $method;
  1498. *$method = sub {
  1499. my $self = shift->new;
  1500. @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  1501. }
  1502. }
  1503. for my $method (qw(on_action on_dispatch)) {
  1504. my $field = '_' . $method;
  1505. *$method = sub {
  1506. my $self = shift->new;
  1507. return $self->{$field} unless @_;
  1508. local $@;
  1509. $self->{$field} = ref $_[0] eq 'CODE' ? shift : eval shift;
  1510. Carp::croak $@ if $@;
  1511. Carp::croak "$method() expects subroutine (CODE) or string that evaluates into subroutine (CODE)"
  1512. unless ref $self->{$field} eq 'CODE';
  1513. return $self;
  1514. }
  1515. }
  1516. for my $method (qw(dispatch_to)) {
  1517. my $field = '_' . $method;
  1518. *$method = sub {
  1519. my $self = shift->new;
  1520. @_ ? ($self->{$field} = [@_], return $self)
  1521. : return @{$self->{$field}};
  1522. }
  1523. }
  1524. }
  1525. sub objects_by_reference {
  1526. my $self = shift->new;
  1527. @_ ? (SOAP::Server::Object->objects_by_reference(@_), return $self)
  1528. : SOAP::Server::Object->objects_by_reference;
  1529. }
  1530. sub dispatched {
  1531. my $self = shift->new;
  1532. @_ ? (push(@{$self->{_dispatched}}, @_), return $self)
  1533. : return @{$self->{_dispatched}};
  1534. }
  1535. sub find_target {
  1536. my $self = shift;
  1537. my $request = shift;
  1538. # try to find URI/method from on_dispatch call first
  1539. my($method_uri, $method_name) = $self->on_dispatch->($request);
  1540. # if nothing there, then get it from envelope itself
  1541. ($method_uri, $method_name) = ($request->namespaceuriof || '', $request->dataof->name)
  1542. unless $method_name;
  1543. $self->on_action->($self->action, $method_uri, $method_name);
  1544. my($class, $static);
  1545. # try to bind directly
  1546. if (defined($class = $self->dispatch_with->{$method_uri}
  1547. || $self->dispatch_with->{$self->action})) {
  1548. # return object, nothing else to do here
  1549. return ($class, $method_uri, $method_name) if ref $class;
  1550. $static = 1;
  1551. } else {
  1552. die "URI path shall map to class" unless defined ($class = URI->new($method_uri)->path);
  1553. for ($class) { s!^/|/$!!g; s!/!::!g; s/^$/main/; }
  1554. die "Failed to access class ($class)" unless $class =~ /^(\w[\w:]*)$/;
  1555. my $fullname = "$class\::$method_name";
  1556. foreach ($self->dispatch_to) {
  1557. return ($_, $method_uri, $method_name) if ref eq $class; # $OBJECT
  1558. next if ref; # skip other objects
  1559. # will ignore errors, because it may complain on
  1560. # d:\foo\bar, which is PATH and not regexp
  1561. eval {
  1562. $static ||=
  1563. $class =~ /^$_$/ || # MODULE
  1564. $fullname =~ /^$_$/ || # MODULE::method
  1565. $method_name =~ /^$_$/ && ($class eq 'main') # method ('main' assumed)
  1566. ;
  1567. };
  1568. }
  1569. }
  1570. no strict 'refs';
  1571. unless (defined %{"${class}::"}) {
  1572. # allow all for static and only specified path for dynamic bindings
  1573. local @INC = (($static ? @INC : ()), grep {!ref && m![/\\.]!} $self->dispatch_to);
  1574. eval 'local $^W; ' . "require $class";
  1575. die "Failed to access class ($class): $@" if $@;
  1576. $self->dispatched($class) unless $static;
  1577. }
  1578. die "Denied access to method ($method_name) in class ($class)"
  1579. unless $static || grep {/^$class$/} $self->dispatched;
  1580. return ($class, $method_uri, $method_name);
  1581. }
  1582. sub handle { SOAP::Trace::trace('()');
  1583. my $self = shift;
  1584. my $result = eval { local $SIG{__DIE__};
  1585. $self->serializer->soapversion(1.1);
  1586. my $request = eval { $self->deserializer->deserialize($_[0]) };
  1587. die "Application failed during request deserialization: $@" if $@;
  1588. my $som = ref $request;
  1589. die "Can't find root element in the message" unless $request->match($som->envelope);
  1590. # check for proper namespace, but allow unqualified root element
  1591. die SOAP::Fault->faultcode($SOAP::Constants::FAULT_VERSION_MISMATCH)
  1592. ->faultstring($@)
  1593. if $request->namespaceuriof &&
  1594. !eval { SOAP::Lite->soapversion($request->namespaceuriof); 1 };
  1595. $self->serializer->soapversion(SOAP::Lite->soapversion);
  1596. $self->serializer->xmlschema($self->deserializer->xmlschema) if $self->deserializer->xmlschema;
  1597. die SOAP::Fault->faultcode($SOAP::Constants::FAULT_MUST_UNDERSTAND)
  1598. ->faultstring("Header has mustUnderstand attribute set to 'true'")
  1599. if !$SOAP::Constants::DO_NOT_CHECK_MUSTUNDERSTAND &&
  1600. grep { $_->mustUnderstand && (!$_->actor || $_->actor eq $SOAP::Constants::NEXT_ACTOR)
  1601. } $request->dataof($som->headers);
  1602. die "Can't find method element in the message" unless $request->match($som->method);
  1603. my($class, $method_uri, $method_name) = $self->find_target($request);
  1604. my @results = eval { local $^W;
  1605. my @parameters = $request->paramsin;
  1606. # SOAP::Trace::dispatch($fullname);
  1607. SOAP::Trace::parameters(@parameters);
  1608. push @parameters, $request if UNIVERSAL::isa($class => 'SOAP::Server::Parameters');
  1609. SOAP::Server::Object->references(
  1610. defined $parameters[0] && ref $parameters[0] && UNIVERSAL::isa($parameters[0] => $class)
  1611. ? do {
  1612. my $object = shift @parameters;
  1613. SOAP::Server::Object->object(ref $class ? $class : $object)->$method_name(
  1614. SOAP::Server::Object->objects(@parameters)),
  1615. map { $_->name(SOAP::Utils::longname($SOAP::Constants::NS_SL => $_->name))
  1616. } $request->headerof($som->method.'/[1]')->value($object)
  1617. }
  1618. : $class->$method_name(SOAP::Server::Object->objects(@parameters))
  1619. );
  1620. };
  1621. SOAP::Trace::result(@results);
  1622. # let application errors pass through with 'Server' code
  1623. die ref $@ ?
  1624. $@ : $@ =~ /^Can't locate object method "$method_name"/ ?
  1625. "Failed to locate method ($method_name) in class ($class)" :
  1626. SOAP::Fault->faultcode($SOAP::Constants::FAULT_SERVER)->faultstring($@)
  1627. if $@;
  1628. return $self->serializer
  1629. -> prefix('s') # distinguish generated element names between client and server
  1630. -> uri($method_uri)
  1631. -> envelope(response => $method_name . 'Response', @results);
  1632. };
  1633. # void context
  1634. return unless defined wantarray;
  1635. # normal result
  1636. return $result unless $@;
  1637. # check fails, something wrong with message
  1638. return $self->make_fault($SOAP::Constants::FAULT_CLIENT, $@) unless ref $@;
  1639. # died with SOAP::Fault
  1640. return $self->make_fault($@->faultcode || $SOAP::Constants::FAULT_SERVER,
  1641. $@->faultstring || 'Application error',
  1642. $@->faultdetail, $@->faultactor)
  1643. if UNIVERSAL::isa($@ => 'SOAP::Fault');
  1644. # died with complex detail
  1645. return $self->make_fault($SOAP::Constants::FAULT_SERVER, 'Application error' => $@);
  1646. }
  1647. sub make_fault {
  1648. my $self = shift;
  1649. my($code, $string, $detail, $actor) = @_;
  1650. $self->serializer->fault($code, $string, $detail, $actor || $self->myuri);
  1651. }
  1652. # ======================================================================
  1653. package SOAP::Trace;
  1654. use Carp ();
  1655. my @list = qw(transport dispatch result parameters headers objects method fault freeform trace debug);
  1656. { no strict 'refs'; for (@list) { *$_ = sub {} } }
  1657. sub defaultlog {
  1658. my $caller = (caller(1))[3];
  1659. $caller = (caller(2))[3] if $caller =~ /eval/;
  1660. chomp(my $msg = join ' ', @_);
  1661. printf STDERR "%s: %s\n", $caller, $msg;
  1662. }
  1663. sub import { no strict 'refs'; local $^W;
  1664. my $pack = shift;
  1665. my(@notrace, @symbols);
  1666. for (@_) {
  1667. if (ref eq 'CODE') {
  1668. my $call = $_;
  1669. foreach (@symbols) { *$_ = sub { $call->(@_) } }
  1670. @symbols = ();
  1671. } else {
  1672. local $_ = $_;
  1673. my $minus = s/^-//;
  1674. my $all = $_ eq 'all';
  1675. Carp::carp "Illegal symbol for tracing ($_)" unless $all || $pack->can($_);
  1676. $minus ? push(@notrace, $all ? @list : $_) : push(@symbols, $all ? @list : $_);
  1677. }
  1678. }
  1679. foreach (@symbols) { *$_ = \&defaultlog }
  1680. foreach (@notrace) { *$_ = sub {} }
  1681. }
  1682. # ======================================================================
  1683. package SOAP::Custom::XML::Data;
  1684. use vars qw(@ISA $AUTOLOAD);
  1685. @ISA = qw(SOAP::Data);
  1686. use overload fallback => 1, '""' => sub { shift->value };
  1687. sub _compileit {
  1688. no strict 'refs';
  1689. my $method = shift;
  1690. *$method = sub {
  1691. return __PACKAGE__->SUPER::name($method => $_[0]->attr->{$method})
  1692. if exists $_[0]->attr->{$method};
  1693. my @elems = grep {
  1694. ref $_ && UNIVERSAL::isa($_ => __PACKAGE__) && $_->SUPER::name =~ /(^|:)$method$/
  1695. } $_[0]->value;
  1696. return wantarray? @elems : $elems[0];
  1697. }
  1698. }
  1699. sub BEGIN { foreach (qw(name type import)) { _compileit($_) } }
  1700. sub AUTOLOAD {
  1701. my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::') + 2);
  1702. return if $method eq 'DESTROY';
  1703. _compileit($method);
  1704. goto &$AUTOLOAD;
  1705. }
  1706. # ======================================================================
  1707. package SOAP::Custom::XML::Deserializer;
  1708. use vars qw(@ISA);
  1709. @ISA = qw(SOAP::Deserializer);
  1710. sub decode_value {
  1711. my $self = shift;
  1712. my $ref = shift;
  1713. my($name, $attrs, $childs, $value) = @$ref;
  1714. # base class knows what to do with it
  1715. return $self->SUPER::decode_value($ref) if exists $attrs->{href};
  1716. SOAP::Custom::XML::Data
  1717. -> SOAP::Data::name($name)
  1718. -> attr($attrs)
  1719. -> set_value(ref $childs && @$childs ? map(scalar(($self->decode_object($_))[1]), @$childs) : $value);
  1720. }
  1721. # ======================================================================
  1722. package SOAP::Schema::Deserializer;
  1723. use vars qw(@ISA);
  1724. @ISA = qw(SOAP::Custom::XML::Deserializer);
  1725. # ======================================================================
  1726. package SOAP::Schema::WSDL;
  1727. use vars qw(%imported);
  1728. sub import {
  1729. my $self = shift;
  1730. my $s = shift;
  1731. my $schema;
  1732. my @a = $s->import;
  1733. local %imported = %imported;
  1734. foreach (@a) {
  1735. next unless $_->location;
  1736. my $location = $_->location->value;
  1737. if ($imported{$location}++) {
  1738. warn "Recursion loop detected in service description from '$location'. Ignored\n" if $^W;
  1739. return $s;
  1740. }
  1741. $schema ||= SOAP::Schema->new;
  1742. my $root = $self->import($schema->deserializer->deserialize($schema->access($location))->root);
  1743. $root->SOAP::Data::name eq 'definitions' ? $s->set_value($s->value, $root->value) :
  1744. $root->SOAP::Data::name eq 'schema' ? do { # add <types> element if there is no one
  1745. $s->set_value($s->value, SOAP::Schema::Deserializer->deserialize('<types></types>')->root) unless $s->types;
  1746. $s->types->set_value($s->types->value, $root) } :
  1747. die "Don't know what to do with '@{[$root->SOAP::Data::name]}' in schema imported from '$location'\n";
  1748. }
  1749. $s;
  1750. }
  1751. sub parse {
  1752. my $self = shift;
  1753. my($s, $service, $port) = @_;
  1754. my @result;
  1755. # handle imports
  1756. $self->import($s);
  1757. # handle descriptions without <service>, aka tModel-type descriptions
  1758. my @services = $s->service;
  1759. # if there is no <service> element we'll provide it
  1760. @services = SOAP::Schema::Deserializer->deserialize(<<"FAKE")->root->service unless @services;
  1761. <definitions>
  1762. <service name="@{[$service || 'FakeService']}">
  1763. <port name="@{[$port || 'FakePort']}" binding="@{[$s->binding->name]}"/>
  1764. </service>
  1765. </definitions>
  1766. FAKE
  1767. foreach (@services) {
  1768. my $name = $_->name;
  1769. next if $service && $service ne $name;
  1770. my %services;
  1771. foreach ($_->port) {
  1772. next if $port && $port ne $_->name;
  1773. my $binding = SOAP::Utils::disqualify($_->binding);
  1774. my $endpoint = ref $_->address ? $_->address->location : undef;
  1775. foreach ($s->binding) {
  1776. # is this a SOAP binding?
  1777. next unless $_->binding->uri eq 'http://schemas.xmlsoap.org/wsdl/soap/';
  1778. next unless $_->name eq $binding;
  1779. my $porttype = SOAP::Utils::disqualify($_->type);
  1780. foreach ($_->operation) {
  1781. my $opername = $_->name;
  1782. my $soapaction = $_->operation->soapAction;
  1783. my $namespace = $_->input->body->namespace;
  1784. my @parts;
  1785. foreach ($s->portType) {
  1786. next unless $_->name eq $porttype;
  1787. foreach ($_->operation) {
  1788. next unless $_->name eq $opername;
  1789. my $inputmessage = SOAP::Utils::disqualify($_->input->message);
  1790. foreach ($s->message) {
  1791. next unless $_->name eq $inputmessage;
  1792. @parts = $_->part;
  1793. }
  1794. }
  1795. }
  1796. $services{$opername} = {}; # should be initialized in 5.7 and after
  1797. for ($services{$opername}) {
  1798. $_->{endpoint} = $endpoint;
  1799. $_->{soapaction} = $soapaction;
  1800. $_->{uri} = $namespace;
  1801. $_->{parameters} = [@parts];
  1802. }
  1803. }
  1804. }
  1805. }
  1806. # fix nonallowed characters in package name, and add 's' if started with digit
  1807. for ($name) { s/\W+/_/g; s/^(\d)/s$1/ }
  1808. push @result, $name => \%services;
  1809. }
  1810. return @result;
  1811. }
  1812. # ======================================================================
  1813. package SOAP::Schema;
  1814. use Carp ();
  1815. sub DESTROY { SOAP::Trace::objects('()') }
  1816. sub new {
  1817. my $self = shift;
  1818. unless (ref $self) {
  1819. my $class = ref($self) || $self;
  1820. $self = bless {
  1821. _deserializer => SOAP::Schema::Deserializer->new,
  1822. } => $class;
  1823. SOAP::Trace::objects('()');
  1824. }
  1825. Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1);
  1826. while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  1827. return $self;
  1828. }
  1829. sub BEGIN {
  1830. no strict 'refs';
  1831. for my $method (qw(deserializer schema services)) {
  1832. my $field = '_' . $method;
  1833. *$method = sub {
  1834. my $self = shift->new;
  1835. @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  1836. }
  1837. }
  1838. }
  1839. sub parse {
  1840. my $self = shift->new;
  1841. my $s = $self->deserializer->deserialize($self->access)->root;
  1842. # here should be something that defines what schema description we want to use
  1843. $self->services({SOAP::Schema::WSDL->parse($s, @_)});
  1844. }
  1845. sub load {
  1846. my $self = shift->new;
  1847. local $^W; # supress warnings about redefining
  1848. foreach (keys %{$self->services || Carp::croak 'Nothing to load. Schema is not specified'}) {
  1849. eval $self->stub($_) or Carp::croak "Bad stub: $@";
  1850. }
  1851. $self;
  1852. }
  1853. sub access { require LWP::UserAgent;
  1854. my $self = shift->new;
  1855. my $url = shift || $self->schema || Carp::croak 'Nothing to access. URL is not specified';
  1856. my $ua = LWP::UserAgent->new;
  1857. my $resp = $ua->request(HTTP::Request->new(GET => $url));
  1858. $resp->is_success ? $resp->content : Carp::croak $resp->status_line;
  1859. }
  1860. sub stub {
  1861. my $self = shift->new;
  1862. my $package = shift;
  1863. my $services = $self->services->{$package};
  1864. my $schema = $self->schema;
  1865. join("\n",
  1866. "package $package;\n",
  1867. "# -- generated by SOAP::Lite (v$SOAP::Lite::VERSION) for Perl -- soaplite.com -- Copyright (C) 2000-2001 Paul Kulchenko --",
  1868. ($schema ? "# -- generated from $schema [@{[scalar localtime]}]\n" : "\n"),
  1869. 'my %methods = (',
  1870. (map { my $service = $_;
  1871. join("\n",
  1872. " $_ => {",
  1873. map(" $_ => '$services->{$service}{$_}',", qw/endpoint soapaction uri/),
  1874. " parameters => [",
  1875. map(" SOAP::Data->new(name => '" . $_->name .
  1876. "', type => '" . $_->type .
  1877. "', attr => {" . do{ my %attr = %{$_->attr}; join ', ', map {"'$_' => '$attr{$_}'"} grep {/^xmlns:(?!-)/} keys %attr} .
  1878. "}),", @{$services->{$service}{parameters}}),
  1879. " ],\n },",
  1880. ),
  1881. } keys %$services),
  1882. ");", <<'EOP');
  1883. use SOAP::Lite;
  1884. use Exporter;
  1885. use Carp ();
  1886. use vars qw(@ISA $AUTOLOAD @EXPORT_OK %EXPORT_TAGS);
  1887. @ISA = qw(Exporter SOAP::Lite);
  1888. @EXPORT_OK = (keys %methods);
  1889. %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
  1890. no strict 'refs';
  1891. for my $method (@EXPORT_OK) {
  1892. my %method = %{$methods{$method}};
  1893. *$method = sub {
  1894. my $self = UNIVERSAL::isa($_[0] => __PACKAGE__)
  1895. ? ref $_[0] ? shift # OBJECT
  1896. # CLASS, either get self or create new and assign to self
  1897. : (shift->self || __PACKAGE__->self(__PACKAGE__->new))
  1898. # function call, either get self or create new and assign to self
  1899. : (__PACKAGE__->self || __PACKAGE__->self(__PACKAGE__->new));
  1900. $self->proxy($method{endpoint} || Carp::croak "No server address (proxy) specified") unless $self->proxy;
  1901. my @templates = @{$method{parameters}};
  1902. my $som = $self
  1903. -> endpoint($method{endpoint})
  1904. -> uri($method{uri})
  1905. -> on_action(sub{qq!"$method{soapaction}"!})
  1906. -> call($method => map {shift(@templates)->value($_)} @_);
  1907. UNIVERSAL::isa($som => 'SOAP::SOM') ? wantarray ? $som->paramsall : $som->result
  1908. : $som;
  1909. }
  1910. }
  1911. 1;
  1912. EOP
  1913. }
  1914. # ======================================================================
  1915. package SOAP;
  1916. use vars qw($AUTOLOAD);
  1917. my $soap; # shared between SOAP and SOAP::Lite packages
  1918. { no strict 'refs';
  1919. *AUTOLOAD = sub {
  1920. local($1,$2);
  1921. my($package, $method) = $AUTOLOAD =~ m/(?:(.+)::)([^:]+)$/;
  1922. return if $method eq 'DESTROY';
  1923. my $soap = ref $_[0] && UNIVERSAL::isa($_[0] => 'SOAP::Lite') ? $_[0] : $soap;
  1924. my $uri = URI->new($soap->uri);
  1925. my $currenturi = $uri->path;
  1926. $package =
  1927. ref $_[0] && UNIVERSAL::isa($_[0] => 'SOAP::Lite') ? $currenturi :
  1928. $package eq 'SOAP' ? ref $_[0] || ($_[0] eq 'SOAP'
  1929. ? $currenturi || Carp::croak "URI is not specified for method call" : $_[0]) :
  1930. $package eq 'main' ? $currenturi || $package
  1931. : $package;
  1932. # drop first parameter if it's a class name
  1933. {
  1934. my $pack = $package;
  1935. for ($pack) { s!^/!!; s!/!::!g; }
  1936. shift @_ if !ref $_[0] && ($_[0] eq $pack || $_[0] eq 'SOAP') ||
  1937. ref $_[0] && UNIVERSAL::isa($_[0] => 'SOAP::Lite');
  1938. }
  1939. for ($package) { s!::!/!g; s!^/?!/!; }
  1940. $uri->path($package);
  1941. my $som = $soap->uri($uri->as_string)->call($method => @_);
  1942. UNIVERSAL::isa($som => 'SOAP::SOM') ? wantarray ? $som->paramsall : $som->result
  1943. : $som;
  1944. };
  1945. }
  1946. # ======================================================================
  1947. package SOAP::Lite;
  1948. use vars qw($AUTOLOAD @ISA);
  1949. use Carp ();
  1950. use URI;
  1951. @ISA = qw(SOAP::Cloneable);
  1952. # provide access to global/autodispatched object
  1953. sub self { @_ > 1 ? $soap = $_[1] : $soap }
  1954. # no more warnings about "used only once"
  1955. *UNIVERSAL::AUTOLOAD if 0;
  1956. sub autodispatched { \&{*UNIVERSAL::AUTOLOAD} eq \&{*SOAP::AUTOLOAD} };
  1957. sub soapversion {
  1958. my $self = shift;
  1959. my $version = shift or return $SOAP::Constants::SOAP_VERSION;
  1960. ($version) = grep { $SOAP::Constants::SOAP_VERSIONS{$_}->{NS_ENV} eq $version
  1961. } keys %SOAP::Constants::SOAP_VERSIONS
  1962. unless exists $SOAP::Constants::SOAP_VERSIONS{$version};
  1963. die qq!Wrong SOAP version specified. Supported versions:\n@{[
  1964. join "\n", map {" $_ ($SOAP::Constants::SOAP_VERSIONS{$_}->{NS_ENV})"} keys %SOAP::Constants::SOAP_VERSIONS
  1965. ]}\n!
  1966. unless defined(my $def = $SOAP::Constants::SOAP_VERSIONS{$version});
  1967. foreach (keys %$def) {
  1968. eval "\$SOAP::Constants::$_ = '$SOAP::Constants::SOAP_VERSIONS{$version}->{$_}'";
  1969. }
  1970. $SOAP::Constants::SOAP_VERSION = $version;
  1971. $self;
  1972. }
  1973. BEGIN { SOAP::Lite->soapversion(1.1) }
  1974. sub import {
  1975. my $pkg = shift;
  1976. my $caller = caller;
  1977. no strict 'refs';
  1978. # emulate 'use SOAP::Lite 0.99' behavior
  1979. $pkg->require_version(shift) if defined $_[0] && $_[0] =~ /^\d/;
  1980. while (@_) {
  1981. my $command = shift;
  1982. my @parameters = UNIVERSAL::isa($_[0] => 'ARRAY') ? @{shift()} : shift
  1983. if @_ && $command ne 'autodispatch';
  1984. if ($command eq 'autodispatch' || $command eq 'dispatch_from') {
  1985. $soap = ($soap||$pkg)->new;
  1986. no strict 'refs';
  1987. foreach ($command eq 'autodispatch' ? 'UNIVERSAL' : @parameters) {
  1988. my $sub = "${_}::AUTOLOAD";
  1989. defined &{*$sub}
  1990. ? (\&{*$sub} eq \&{*SOAP::AUTOLOAD} ? () : Carp::croak "$sub already assigned and won't work with DISPATCH. Died")
  1991. : (*$sub = *SOAP::AUTOLOAD);
  1992. }
  1993. } elsif ($command eq 'service' || $command eq 'schema') {
  1994. warn "'schema =>' interface is changed. Use 'service =>' instead\n"
  1995. if $command eq 'schema' && $^W;
  1996. foreach (keys %{SOAP::Schema->schema(shift(@parameters))->parse(@parameters)->load->services}) {
  1997. $_->export_to_level(1, undef, ':all');
  1998. }
  1999. } elsif ($command eq 'debug' || $command eq 'trace') {
  2000. SOAP::Trace->import(@parameters ? @parameters : 'all');
  2001. } elsif ($command eq 'import') {
  2002. local $^W; # supress warnings about redefining
  2003. my $package = shift(@parameters);
  2004. $package->export_to_level(1, undef, @parameters ? @parameters : ':all') if $package;
  2005. } else {
  2006. Carp::carp "Odd (wrong?) number of parameters in import(), still continue" if $^W && !(@parameters & 1);
  2007. $soap = ($soap||$pkg)->$command(@parameters);
  2008. }
  2009. }
  2010. }
  2011. sub DESTROY { SOAP::Trace::objects('()') }
  2012. sub new {
  2013. my $self = shift;
  2014. unless (ref $self) {
  2015. my $class = ref($self) || $self;
  2016. # check whether we can clone. Only the SAME class allowed, no inheritance
  2017. $self = ref($soap) eq $class ? $soap->clone : {
  2018. _transport => SOAP::Transport->new,
  2019. _serializer => SOAP::Serializer->new,
  2020. _deserializer => SOAP::Deserializer->new,
  2021. _autoresult => 0,
  2022. _on_action => sub { sprintf '"%s#%s"', shift || '', shift },
  2023. _on_fault => sub {ref $_[1] ? return $_[1] : Carp::croak $_[0]->transport->is_success ? $_[1] : $_[0]->transport->status},
  2024. };
  2025. bless $self => $class;
  2026. $self->on_nonserialized($self->on_nonserialized || $self->serializer->on_nonserialized);
  2027. SOAP::Trace::objects('()');
  2028. }
  2029. Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1);
  2030. while (@_) { my($method, $params) = splice(@_,0,2);
  2031. $self->can($method)
  2032. ? $self->$method(ref $params eq 'ARRAY' ? @$params : $params)
  2033. : $^W && Carp::carp "Unrecognized parameter '$method' in new()"
  2034. }
  2035. return $self;
  2036. }
  2037. sub BEGIN {
  2038. no strict 'refs';
  2039. for my $method (qw(endpoint transport serializer deserializer outputxml autoresult)) {
  2040. my $field = '_' . $method;
  2041. *$method = sub {
  2042. my $self = shift->new;
  2043. @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  2044. }
  2045. }
  2046. for my $method (qw(on_action on_fault on_nonserialized)) {
  2047. my $field = '_' . $method;
  2048. *$method = sub {
  2049. my $self = shift->new;
  2050. return $self->{$field} unless @_;
  2051. local $@;
  2052. $self->{$field} = ref $_[0] eq 'CODE' ? shift : eval shift;
  2053. Carp::croak $@ if $@;
  2054. Carp::croak "$method() expects subroutine (CODE) or string that evaluates into subroutine (CODE)"
  2055. unless ref $self->{$field} eq 'CODE';
  2056. return $self;
  2057. }
  2058. }
  2059. for my $method (qw(proxy)) {
  2060. *$method = sub {
  2061. my $self = shift->new;
  2062. @_ ? ($self->transport->$method(@_), return $self) : return $self->transport->$method();
  2063. }
  2064. }
  2065. for my $method (qw(autotype readable namespace encodingspace envprefix encprefix
  2066. multirefinplace encoding typelookup uri header maptype xmlschema)) {
  2067. *$method = sub {
  2068. my $self = shift->new;
  2069. @_ ? ($self->serializer->$method(@_), return $self) : return $self->serializer->$method();
  2070. }
  2071. }
  2072. }
  2073. sub service {
  2074. my $field = '_service';
  2075. my $self = shift->new;
  2076. return $self->{$field} unless @_;
  2077. my %services = %{SOAP::Schema->schema($self->{$field} = shift)->parse(@_)->load->services};
  2078. Carp::croak "Cannot activate service description with multiple services through this interface\n"
  2079. if keys %services > 1;
  2080. return (keys %services)[0]->new;
  2081. }
  2082. sub schema {
  2083. warn "SOAP::Lite->schema(...) interface is changed. Use ->service() instead\n" if $^W;
  2084. shift->service(@_);
  2085. }
  2086. sub on_debug {
  2087. my $self = shift;
  2088. # comment this warning for now, till we redesign SOAP::Trace (2001/02/20)
  2089. # Carp::carp "'SOAP::Lite->on_debug' method is deprecated. Instead use 'SOAP::Lite +debug ...'" if $^W;
  2090. SOAP::Trace->import(debug => shift);
  2091. $self;
  2092. }
  2093. sub AUTOLOAD {
  2094. my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::') + 2);
  2095. return if $method eq 'DESTROY';
  2096. ref $_[0] or Carp::croak qq!Can't locate class method "$method" via package "! . __PACKAGE__ .'"';
  2097. no strict 'refs';
  2098. *$AUTOLOAD = sub {
  2099. my $self = shift;
  2100. my $som = $self->call($method => @_);
  2101. return $self->autoresult && UNIVERSAL::isa($som => 'SOAP::SOM')
  2102. ? wantarray ? $som->paramsall : $som->result
  2103. : $som;
  2104. };
  2105. goto &$AUTOLOAD;
  2106. }
  2107. sub call { SOAP::Trace::trace('()');
  2108. my $self = shift;
  2109. return $self->{_call} unless @_;
  2110. my $serializer = $self->serializer;
  2111. $serializer->on_nonserialized($self->on_nonserialized);
  2112. my $response = $self->transport->send_receive(
  2113. endpoint => $self->endpoint,
  2114. action => scalar($self->on_action->($serializer->uriformethod($_[0]))),
  2115. envelope => $serializer->envelope(method => shift, @_), # leave only parameters
  2116. encoding => $serializer->encoding,
  2117. );
  2118. return $response if $self->outputxml;
  2119. # deserialize and store result
  2120. my $result = $self->{_call} = eval { $self->deserializer->deserialize($response) } if $response;
  2121. if (!$self->transport->is_success || # transport fault
  2122. $@ || # not deserializible
  2123. # fault message even if transport OK
  2124. # or no transport error (for example, fo TCP, POP3, IO implementations)
  2125. UNIVERSAL::isa($result => 'SOAP::SOM') && $result->fault) {
  2126. return $self->{_call} = ($self->on_fault->($self, $@ ? $@ . ($response || '') : $result) || $result);
  2127. }
  2128. return unless $response; # nothing to do for one-ways
  2129. # little bit tricky part that binds in/out parameters
  2130. if (UNIVERSAL::isa($result => 'SOAP::SOM') &&
  2131. ($result->paramsout || $result->headers) &&
  2132. $serializer->signature) {
  2133. my $num = 0;
  2134. my %signatures = map {$_ => $num++} @{$serializer->signature};
  2135. for ($result->dataof(SOAP::SOM::paramsout), $result->dataof(SOAP::SOM::headers)) {
  2136. my $signature = join $;, $_->name, $_->type || '';
  2137. if (exists $signatures{$signature}) {
  2138. my $param = $signatures{$signature};
  2139. my($value) = $_->value; # take first value
  2140. UNIVERSAL::isa($_[$param] => 'SOAP::Data') ? $_[$param]->SOAP::Data::value($value) :
  2141. UNIVERSAL::isa($_[$param] => 'ARRAY') ? (@{$_[$param]} = @$value) :
  2142. UNIVERSAL::isa($_[$param] => 'HASH') ? (%{$_[$param]} = %$value) :
  2143. UNIVERSAL::isa($_[$param] => 'SCALAR') ? (${$_[$param]} = $$value) :
  2144. ($_[$param] = $value)
  2145. }
  2146. }
  2147. }
  2148. return $result;
  2149. }
  2150. # ======================================================================
  2151. package SOAP::Lite::COM;
  2152. require SOAP::Lite;
  2153. sub required {
  2154. foreach (qw(
  2155. URI::_foreign URI::http URI::https
  2156. LWP::Protocol::http LWP::Protocol::https LWP::Authen::Basic LWP::Authen::Digest
  2157. HTTP::Daemon Compress::Zlib SOAP::Transport::HTTP)) {
  2158. eval join ';', 'local $SIG{__DIE__}', "require $_";
  2159. }
  2160. }
  2161. sub new { required; SOAP::Lite->new(@_) }
  2162. sub create; *create = \&new; # make alias. Somewhere 'new' is registered keyword
  2163. sub server { required; shift->new(@_) }
  2164. sub instanceof { my $class = shift; eval "require $class"; $class->new(@_) }
  2165. sub data { SOAP::Data->new(@_) }
  2166. sub header { SOAP::Header->new(@_) }
  2167. sub hash { +{@_} }
  2168. # ======================================================================
  2169. 1;
  2170. __END__
  2171. =head1 NAME
  2172. SOAP::Lite - Client and server side SOAP implementation
  2173. =head1 SYNOPSIS
  2174. use SOAP::Lite;
  2175. print SOAP::Lite
  2176. -> uri('http://www.soaplite.com/Temperatures')
  2177. -> proxy('http://services.soaplite.com/temper.cgi')
  2178. -> f2c(32)
  2179. -> result;
  2180. The same code with autodispatch:
  2181. use SOAP::Lite +autodispatch =>
  2182. uri => 'http://www.soaplite.com/Temperatures',
  2183. proxy => 'http://services.soaplite.com/temper.cgi';
  2184. print f2c(32);
  2185. Code in OO-style:
  2186. use SOAP::Lite +autodispatch =>
  2187. uri => 'http://www.soaplite.com/Temperatures',
  2188. proxy => 'http://services.soaplite.com/temper.cgi';
  2189. my $temperatures = Temperatures->new(32); # get object
  2190. print $temperatures->as_celsius; # invoke method
  2191. Code with service description:
  2192. use SOAP::Lite;
  2193. print SOAP::Lite
  2194. -> service('http://www.xmethods.net/sd/StockQuoteService.wsdl')
  2195. -> getQuote('MSFT');
  2196. Code for SOAP server (CGI):
  2197. use SOAP::Transport::HTTP;
  2198. SOAP::Transport::HTTP::CGI
  2199. -> dispatch_to('/Your/Path/To/Deployed/Modules', 'Module::Name', 'Module::method')
  2200. -> handle;
  2201. Visual Basic client (through COM interface):
  2202. MsgBox CreateObject("SOAP.Lite").new( _
  2203. "proxy", "http://services.xmethods.net/soap", _
  2204. "uri", "urn:xmethods-delayed-quotes" _
  2205. ).getQuote("MSFT").result
  2206. mod_soap enabled SOAP server:
  2207. .htaccess
  2208. SetHandler perl-script
  2209. PerlHandler Apache::SOAP
  2210. PerlSetVar dispatch_to "/Your/Path/To/Deployed/Modules, Module::Name"
  2211. ASP/VB SOAP server:
  2212. <%
  2213. Response.ContentType = "text/xml"
  2214. Response.Write(Server.CreateObject("SOAP.Lite") _
  2215. .server("SOAP::Server") _
  2216. .dispatch_to("/Your/Path/To/Deployed/Modules") _
  2217. .handle(Request.BinaryRead(Request.TotalBytes)) _
  2218. )
  2219. %>
  2220. =head1 DESCRIPTION
  2221. SOAP::Lite is a collection of Perl modules which provides a
  2222. simple and lightweight interface to the Simple Object Access Protocol
  2223. (SOAP) both on client and server side.
  2224. This version of SOAP::Lite supports the SOAP 1.1 specification ( http://www.w3.org/TR/SOAP ).
  2225. The main features of the library are:
  2226. =over 3
  2227. =item *
  2228. Supports SOAP 1.1 spec.
  2229. =item *
  2230. Interoperability tests with different implementations: Apache SOAP, Frontier,
  2231. Microsoft SOAP, Microsoft .NET, DevelopMentor, XMethods, 4s4c, Phalanx,
  2232. Kafka, SQLData, Lucin (in Java, Perl, C++, Python, VB, COM, XSLT).
  2233. =item *
  2234. Provides COM interface. Single dll (standalone [2.5MB] or minimal [32kB]).
  2235. Works on Windows 9x/Me/NT/2K. Doesn't require ROPE or MSXML.
  2236. Examples in VB, Excel/VBA, C#, ASP, JavaScript, PerlScript and Perl.
  2237. =item *
  2238. Provides transparent compression support for HTTP transport.
  2239. =item *
  2240. Provides mod_soap module. Make SOAP server with a few lines in .htaccess
  2241. or .conf file.
  2242. =item *
  2243. Includes XML::Parser::Lite (regexp-based XML parser) which runs instead
  2244. of XML::Parser where Perl 5.6 runs (even on WinCE) with some limitations.
  2245. =item *
  2246. Includes XMLRPC::Lite, implementation of XML-RPC protocol on client and
  2247. server side. All transports and features of SOAP::Lite are available.
  2248. =item *
  2249. Supports multipart/form-data MIME attachments.
  2250. =item *
  2251. Supports circular linked lists and multiple references.
  2252. =item *
  2253. Supports Map datatype (encoding of maps/hashes with arbitrary keys).
  2254. =item *
  2255. Supports HTTPS protocol.
  2256. =item *
  2257. Provides proxy support.
  2258. =item *
  2259. Provides CGI/daemon/mod_perl/Apache::Registry server implementations.
  2260. =item *
  2261. Provides TCP server implementation.
  2262. =item *
  2263. Provides IO (STDIN/STDOUT/File) server implementation.
  2264. =item *
  2265. Provides FTP client implementation.
  2266. =item *
  2267. Supports single/multipart MIME attachment (parsing side only).
  2268. =item *
  2269. Supports SMTP protocol.
  2270. =item *
  2271. Provides POP3 server implementation.
  2272. =item *
  2273. Supports M-POST and redirects in HTTP transport.
  2274. =item *
  2275. Supports Basic/Digest server authentication.
  2276. =item *
  2277. Works with CGI accelerators, like VelociGen and PerlEx.
  2278. =item *
  2279. Supports UDDI interface on client side. See UDDI::Lite for details.
  2280. =item *
  2281. Supports UDDI publishing API. Examples and documentation provided.
  2282. =item *
  2283. Supports WSDL schema with stub and run-time access.
  2284. =item *
  2285. Supports blessed object references.
  2286. =item *
  2287. Supports arrays (both serialization and deserialization with autotyping).
  2288. =item *
  2289. Supports custom serialization.
  2290. =item *
  2291. Provides exception transport with custom exceptions
  2292. =item *
  2293. Supports Base64 encoding.
  2294. =item *
  2295. Supports XML entity encoding.
  2296. =item *
  2297. Supports header attributes.
  2298. =item *
  2299. Supports dynamic and static class/method binding.
  2300. =item *
  2301. Supports objects-by-reference with simple garbage collection and activation.
  2302. =item *
  2303. Provides shell for interactive SOAP sessions.
  2304. =item *
  2305. Supports out parameters binding.
  2306. =item *
  2307. Supports transparent SOAP calls with autodispatch feature.
  2308. =item *
  2309. Provides easy services deployment. Put module in specified directory and
  2310. it'll be accessible.
  2311. =item *
  2312. Has tests, examples and documentation to let you be up and running in no time.
  2313. =back
  2314. =head2 WHERE TO FIND EXAMPLES
  2315. See F<t/*.t>, F<examples/*.pl> and the module documentation for a client-side
  2316. examples that demonstrate the serialization of a SOAP request, sending it
  2317. via HTTP to the server and receiving the response, and the deserialization
  2318. of the response. See F<examples/server/*> for server-side implementations.
  2319. =head1 OVERVIEW OF CLASSES AND PACKAGES
  2320. This table should give you a quick overview of the classes provided by the
  2321. library.
  2322. SOAP::Lite.pm
  2323. -- SOAP::Lite -- Main class provides all logic
  2324. -- SOAP::Transport -- Supports transport architecture
  2325. -- SOAP::Data -- Provides extensions for serialization architecture
  2326. -- SOAP::Header -- Provides extensions for header serialization
  2327. -- SOAP::Parser -- Parses XML file into object tree
  2328. -- SOAP::Serializer -- Serializes data structures to SOAP package
  2329. -- SOAP::Deserializer -- Deserializes results of SOAP::Parser into objects
  2330. -- SOAP::SOM -- Provides access to deserialized object tree
  2331. -- SOAP::Constants -- Provides access to common constants
  2332. -- SOAP::Trace -- Provides tracing facilities
  2333. -- SOAP::Schema -- Provides access and stub(s) for schema(s)
  2334. -- SOAP::Schema::WSDL -- WSDL implementation for SOAP::Schema
  2335. -- SOAP::Server -- Handles requests on server side
  2336. -- SOAP::Server::Object -- Handles objects-by-reference
  2337. -- SOAP::Fault -- Provides support for Faults on server side
  2338. SOAP::Transport::HTTP.pm
  2339. -- SOAP::Transport::HTTP::Client -- Client interface to HTTP transport
  2340. -- SOAP::Transport::HTTP::Server -- Server interface to HTTP transport
  2341. -- SOAP::Transport::HTTP::CGI -- CGI implementation of server interface
  2342. -- SOAP::Transport::HTTP::Daemon -- Daemon implementation of server interface
  2343. -- SOAP::Transport::HTTP::Apache -- mod_perl implementation of server interface
  2344. SOAP::Transport::POP3.pm
  2345. -- SOAP::Transport::POP3::Server -- Server interface to POP3 protocol
  2346. SOAP::Transport::MAILTO.pm
  2347. -- SOAP::Transport::MAILTO::Client -- Client interface to SMTP/sendmail
  2348. SOAP::Transport::LOCAL.pm
  2349. -- SOAP::Transport::LOCAL::Client -- Client interface to local transport
  2350. SOAP::Transport::TCP.pm
  2351. -- SOAP::Transport::TCP::Server -- Server interface to TCP protocol
  2352. -- SOAP::Transport::TCP::Client -- Client interface to TCP protocol
  2353. SOAP::Transport::IO.pm
  2354. -- SOAP::Transport::IO::Server -- Server interface to IO transport
  2355. =head2 SOAP::Lite
  2356. All methods that C<SOAP::Lite> provides can be used for both
  2357. setting and retrieving values. If you provide no parameters, you will
  2358. get current value, and if parameters are provided, a new value
  2359. will be assigned to the object and the method in question will return
  2360. the current object (if not stated otherwise). This is suitable for stacking
  2361. these calls like:
  2362. $lite = SOAP::Lite
  2363. -> uri('http://simon.fell.com/calc')
  2364. -> proxy('http://soap.4s4c.com/ssss4c/soap.asp')
  2365. ;
  2366. The order is insignificant and you may call the new() method first. If you
  2367. don't do it, SOAP::Lite will do it for you. However, the new() method
  2368. gives you additional syntax:
  2369. $lite = new SOAP::Lite
  2370. uri => 'http://simon.fell.com/calc',
  2371. proxy => 'http://soap.4s4c.com/ssss4c/soap.asp'
  2372. ;
  2373. =over 4
  2374. =item new()
  2375. new() accepts a hash with method names as keys. It will call the
  2376. appropriate methods together with the passed values. Since new() is
  2377. optional it won't be mentioned anymore.
  2378. =item transport()
  2379. Provides access to the L</"SOAP::Transport"> object. The object will be created
  2380. for you. You can reassign it (but generally you should not).
  2381. =item serializer()
  2382. Provides access to the L</"SOAP::Serialization"> object. The object will be
  2383. created for you. You can reassign it (but generally you should not).
  2384. =item proxy()
  2385. Shortcut for C<< transport->proxy() >>. This lets you specify an endpoint
  2386. (service address) and also loads the required module at the same time. It is
  2387. required for dispatching SOAP calls. The name of the module will be defined
  2388. depending on the protocol specific for the endpoint. The prefix
  2389. C<SOAP::Transport> will be prepended, the module will be loaded and object of
  2390. class (with appended C<::Client>) will be created.
  2391. For example, for F<http://localhost/>, the class for creating objects will
  2392. look for C<SOAP::Transport:HTTP::Client>;
  2393. In addition to endpoint parameter, proxy() can accept any transport specific
  2394. parameters that could be passed as name => value pairs. For example, to
  2395. specify proxy settings for HTTP protocol you may do:
  2396. $soap->proxy('http://endpoint.server/',
  2397. proxy => ['http' => 'http://my.proxy.server/']);
  2398. Notice that since proxy (second one) expects to get more than one
  2399. parameter you should wrap them in array.
  2400. Another useful example can be the client that is sensitive to cookie-based
  2401. authentication. You can provide this with:
  2402. $soap->proxy('http://localhost/',
  2403. cookie_jar => HTTP::Cookies->new(ignore_discard => 1));
  2404. You may specify timeout for HTTP transport with following code:
  2405. $soap->proxy('http://localhost/', timeout => 5);
  2406. =item endpoint()
  2407. Lets you specify an endpoint B<without> changing/loading the protocol module.
  2408. This is useful for switching endpoints without switching protocols. You should
  2409. call C<proxy()> first. No checks for protocol equivalence will be made.
  2410. =item outputxml()
  2411. Lets you specify the kind of output from all method calls. If C<true>, all
  2412. methods will return unprocessed, raw XML code. You can parse it with
  2413. XML::Parser, SOAP::Deserializer or any other appropriate module.
  2414. =item autotype()
  2415. Shortcut for C<< serializer->autotype() >>. This lets you specify whether
  2416. the serializer will try to make autotyping for you or not. Default setting
  2417. is C<true>.
  2418. =item readable()
  2419. Shortcut for C<< serializer->readable() >>. This lets you specify the format
  2420. for the generated XML code. Carriage returns <CR> and indentation will be
  2421. added for readability. Useful in the case you want to see the generated code
  2422. in a debugger. By default, there are no additional characters in generated
  2423. XML code.
  2424. =item namespace()
  2425. Shortcut for C<< serializer->namespace() >>. This lets you specify the default
  2426. namespace for generated envelopes (C<'SOAP-ENV'> by default).
  2427. =item encodingspace()
  2428. Shortcut for C<< serializer->encodingspace() >>. This lets you specify the
  2429. default encoding namespace for generated envelopes (C<'SOAP-ENC'> by default).
  2430. =item encoding()
  2431. Shortcut for C<< serializer->encoding() >>. This lets you specify the encoding
  2432. for generated envelopes. For now it will not actually change envelope
  2433. encoding, it will just modify the XML header (C<'UTF-8'> by default).
  2434. =item typelookup()
  2435. Shortcut for C<< serializer->typelookup() >>. This gives you access to
  2436. the C<typelookup> table that is used for autotyping. For more information
  2437. see L</"SOAP::Serializer">.
  2438. =item uri()
  2439. Shortcut for C<< serializer->uri() >>. This lets you specify the uri for SOAP
  2440. methods. Nothing is specified by default and your call will definitely fail
  2441. if you don't specify the required uri.
  2442. B<WARNING>: URIs are just identifiers. They may B<look like URLs>, but they are
  2443. not guaranteed to point to anywhere and shouldn't be used as such pointers.
  2444. URIs assume to be unique within the space of all XML documents, so consider
  2445. them as unique identifiers and nothing else.
  2446. =item multirefinplace()
  2447. Shortcut for C<< serializer->multirefinplace() >>. If true, the serializer will
  2448. put values for multireferences in the first occurrence of the reference.
  2449. Otherwise it will be encoded as top independent element, right after C<method>
  2450. element inside C<Body>. Default value is C<false>.
  2451. =item header()
  2452. B<DEPRECATED>: Use SOAP::Header instead.
  2453. Shortcut for C<< serializer->header() >>. This lets you specify the header for
  2454. generated envelopes. You can specify C<root>, C<mustUnderstand> or any
  2455. other header using L</"SOAP::Data"> class:
  2456. $serializer = SOAP::Serializer->envelope('method' => 'mymethod', 1,
  2457. SOAP::Header->name(t1 => 5)->mustUnderstand(1),
  2458. SOAP::Header->name(t2 => 7)->mustUnderstand(2),
  2459. );
  2460. will be serialized into:
  2461. <SOAP-ENV:Envelope ...attributes skipped>
  2462. <SOAP-ENV:Header>
  2463. <t1 xsi:type="xsd:int" SOAP-ENV:mustUnderstand="1">5</t1>
  2464. <t2 xsi:type="xsd:int" SOAP-ENV:mustUnderstand="1">7</t2>
  2465. </SOAP-ENV:Header>
  2466. <SOAP-ENV:Body>
  2467. <namesp1:mymethod xmlns:namesp1="urn:SOAP__Serializer">
  2468. <c-gensym6 xsi:type="xsd:int">1</c-gensym6>
  2469. </namesp1:mymethod>
  2470. </SOAP-ENV:Body>
  2471. </SOAP-ENV:Envelope>
  2472. You can mix C<SOAP::Header> parameters with other parameters and you can also
  2473. return C<SOAP::Header> parameters as a result of a remote call. They will be
  2474. placed into the header. See C<My::Parameters::addheader> as an example.
  2475. =item on_action()
  2476. This lets you specify a handler for C<on_action event>. It is triggered when
  2477. creating SOAPAction. The default handler will set SOAPAction to
  2478. C<"uri#method">. You can change this behavior globally
  2479. (see L</"DEFAULT SETTINGS">) or locally, for a particular object.
  2480. =item on_fault()
  2481. This lets you specify a handler for C<on_fault> event. The default behavior is
  2482. to B<die> on an transport error and to B<do nothing> on other error conditions. You
  2483. may change this behavior globally (see L</"DEFAULT SETTINGS">) or locally, for a
  2484. particular object.
  2485. =item on_debug()
  2486. This lets you specify a handler for C<on_debug event>. Default behavior is to
  2487. do nothing. Use C<+trace/+debug> option for SOAP::Lite instead. If you use if
  2488. be warned that since this method is just interface to C<+trace/+debug> it has
  2489. B<global> effect, so if you install it for one object it'll be in effect for
  2490. all subsequent calls (even for other objects).
  2491. =item on_nonserialized()
  2492. This lets you specify a handler for C<on_nonserialized event>. The default
  2493. behavior is to produce a warning if warnings are on for everything that cannot
  2494. be properly serialized (like CODE references or GLOBs).
  2495. =item call()
  2496. Provides alternative interface for remote method calls. You can always
  2497. run C<< SOAP::Lite->new(...)->method(@parameters) >>, but call() gives
  2498. you several additional options:
  2499. =over 4
  2500. =item prefixed method
  2501. If you want to specify prefix for generated method's element one of the
  2502. available options is do it with call() interface:
  2503. print SOAP::Lite
  2504. -> new(....)
  2505. -> call('myprefix:method' => @parameters)
  2506. -> result;
  2507. This example will work on client side only. If you want to change prefix
  2508. on server side you should override default serializer. See
  2509. F<examples/server/soap.*> for examples.
  2510. =item access to any method
  2511. If for some reason you want to get access to remote procedures that have
  2512. the same name as methods of SOAP::Lite object these calls (obviously) won't
  2513. be dispatched. In that case you can originate your call trough call():
  2514. print SOAP::Lite
  2515. -> new(....)
  2516. -> call(new => @parameters)
  2517. -> result;
  2518. =item implementation of OO interface
  2519. With L<autodispatch|/"AUTODISPATCHING AND SOAP:: PREFIX"> you can make CLASS/OBJECT calls like:
  2520. my $obj = CLASS->new(@parameters);
  2521. print $obj->method;
  2522. However, because of side effects L<autodispatch|/"AUTODISPATCHING AND SOAP:: PREFIX">
  2523. has, it's not always possible to use this syntax. call() provides you with
  2524. alternative:
  2525. # you should specify uri()
  2526. my $soap = SOAP::Lite
  2527. -> uri('http://my.own.site/CLASS') # <<< CLASS goes here
  2528. # ..... other parameters
  2529. ;
  2530. my $obj = $soap->call(new => @parameters)->result;
  2531. print $soap->call(method => $obj)->result;
  2532. # $obj object will be updated here if necessary,
  2533. # as if you call $obj->method() and method() updates $obj
  2534. # Update of modified object MAY not work if server on another side
  2535. # is not SOAP::Lite
  2536. =item ability to set method's attributes
  2537. Additionally this syntax lets you specify attributes for method element:
  2538. print SOAP::Lite
  2539. -> new(....)
  2540. -> call(SOAP::Data->name('method')->attr({xmlns => 'mynamespace'})
  2541. => @parameters)
  2542. -> result;
  2543. You can specify B<any> attibutes and C<name> of C<SOAP::Data> element becomes
  2544. name of method. Everything else except attributes is ignored and parameters
  2545. should be provided as usual.
  2546. Be warned, that though you have more control using this method, you B<should>
  2547. specify namespace attribute for method explicitely, even if you made uri()
  2548. call earlier. So, if you have to have namespace on method element, instead of:
  2549. print SOAP::Lite
  2550. -> new(....)
  2551. -> uri('mynamespace') # will be ignored
  2552. -> call(SOAP::Data->name('method') => @parameters)
  2553. -> result;
  2554. do
  2555. print SOAP::Lite
  2556. -> new(....)
  2557. -> call(SOAP::Data->name('method')->attr({xmlns => 'mynamespace'})
  2558. => @parameters)
  2559. -> result;
  2560. because in the former call uri() will be ignored and namespace won't be
  2561. specified. If you run script with C<-w> option (as recommended) SOAP::Lite
  2562. gives you a warning:
  2563. URI is not provided as attribute for method (method)
  2564. Moreover, it'll become fatal error if you try to call it with prefixed name:
  2565. print SOAP::Lite
  2566. -> new(....)
  2567. -> uri('mynamespace') # will be ignored
  2568. -> call(SOAP::Data->name('a:method') => @parameters)
  2569. -> result;
  2570. gives you:
  2571. Can't find namespace for method (a:method)
  2572. because nothing is associated with prefix C<'a'>.
  2573. =back
  2574. One more comment. One case when SOAP::Lite will change something that
  2575. you specified is when you specified prefixed name and empty namespace name:
  2576. print SOAP::Lite
  2577. -> new(....)
  2578. -> uri('')
  2579. -> call('a:method' => @parameters)
  2580. -> result;
  2581. This code will generate:
  2582. <method xmlns="">....</method>
  2583. instead of
  2584. <a:method xmlns:a="">....</method>
  2585. because later is not allowed according to XML Namespace specification.
  2586. In all other aspects C<< ->call(mymethod => @parameters) >> is just a
  2587. synonim for C<< ->mymethod(@parameters) >>.
  2588. =item self()
  2589. Returns object reference to B<global> defaul object specified with
  2590. C<use SOAP::Lite ...> interface. Both class method and object method return
  2591. reference to B<global> object, so:
  2592. use SOAP::Lite
  2593. proxy => 'http://my.global.server'
  2594. ;
  2595. my $soap = SOAP::Lite->proxy('http://my.local.server');
  2596. print $soap->self->proxy;
  2597. prints C<'http://my.global.server'> (the same as C<< SOAP::Lite->self->proxy >>).
  2598. See L</"DEFAULT SETTINGS"> for more information.
  2599. =item dispatch_from()
  2600. Does exactly the same as L<autodispatch|/"AUTODISPATCHING AND SOAP:: PREFIX">
  2601. does, but doesn't install UNIVERSAL::AUTOLOAD handler and only install
  2602. AUTOLOAD handlers in specified classes. Can be used only with C<use SOAP::Lite ...>
  2603. clause and should be specified first:
  2604. use SOAP::Lite
  2605. dispatch_from => ['A', 'B'], # use "dispatch_from => 'A'" for one class
  2606. uri => ....,
  2607. proxy => ....,
  2608. ;
  2609. A->a;
  2610. B->b;
  2611. =back
  2612. =head2 SOAP::Data
  2613. You can use this class if you want to specify a value, a name, atype, a uri or
  2614. attributes for SOAP elements (use C<value()>, C<name()>, C<type()>,
  2615. C<uri()> and C<attr()> methods correspondingly).
  2616. For example, C<< SOAP::Data->name('abc')->value(123) >> will be serialized
  2617. into C<< <abc>123</abc> >>, as well as will C<< SOAP::Data->name(abc => 123) >>.
  2618. Each of them (except the value() method) can accept a value as the second
  2619. parameter. All methods return the current value if you call them without
  2620. parameters. The return the object otherwise, so you can stack them. See tests
  2621. for more examples. You can import these methods with:
  2622. SOAP::Data->import('name');
  2623. or
  2624. import SOAP::Data 'name';
  2625. and then use C<< name(abc => 123) >> for brevity.
  2626. An interface for specific attributes is also provided. You can use the C<actor()>,
  2627. C<mustUnderstand()>, C<encodingStyle()> and C<root()> methods to set/get
  2628. values of the correspondent attributes.
  2629. SOAP::Data
  2630. ->name(c => 3)
  2631. ->encodingStyle('http://xml.apache.org/xml-soap/literalxml')
  2632. will be serialized into:
  2633. <c SOAP-ENV:encodingStyle="http://xml.apache.org/xml-soap/literalxml"
  2634. xsi:type="xsd:int">3</c>
  2635. =head2 SOAP::Serializer
  2636. Usually you don't need to interact directly with this module. The only
  2637. case when you need it, it when using autotyping. This feature lets you specify
  2638. types for your data according to your needs as well as to introduce new
  2639. data types (like ordered hash for example).
  2640. You can specify a type with C<< SOAP::Data->type(float => 123) >>. During
  2641. the serialization stage the module will try to serialize your data with the
  2642. C<as_float> method. It then calls the C<typecast> method (you can override it
  2643. or inherit your own class from L</"SOAP::Data">) and only then it will try to
  2644. serialize it according to data type (C<SCALAR>, C<ARRAY> or C<HASH>). For example:
  2645. SOAP::Data->type('ordered_hash' => [a => 1, b => 2])
  2646. will be serialized as an ordered hash, using the C<as_ordered_hash> method.
  2647. If you do not specify a type directly, the serialization module will try
  2648. to autodefine the type for you according to the C<typelookup> hash. It contains
  2649. the type name as key and the following 3-element array as value:
  2650. priority,
  2651. check_function (CODE reference),
  2652. typecast function (METHOD name or CODE reference)
  2653. For example, if you want to add C<uriReference> to autodefined types,
  2654. you should add something like this:
  2655. $s->typelookup->{uriReference} =
  2656. [11, sub { $_[0] =~ m!^http://! }, 'as_uriReference'];
  2657. and add the C<as_uriReference> method to the L</"SOAP::Serializer"> class:
  2658. sub SOAP::Serializer::as_uriReference {
  2659. my $self = shift;
  2660. my($value, $name, $type, $attr) = @_;
  2661. return [$name, {'xsi:type' => 'xsd:uriReference', %$attr}, $value];
  2662. }
  2663. The specified methods will work for both autotyping and direct typing, so you
  2664. can use either
  2665. SOAP::Data->type(uriReference => 'http://yahoo.com')>
  2666. or just
  2667. 'http://yahoo.com'
  2668. and it will be serialized into the same type. For more examples see C<as_*>
  2669. methods in L</"SOAP::Serializer">.
  2670. The SOAP::Serializer provides you with C<autotype()>, C<readable()>, C<namespace()>,
  2671. C<encodingspace()>, C<encoding()>, C<typelookup()>, C<uri()>, C<multirefinplace()> and
  2672. C<envelope()> methods. All methods (except C<envelope()>) are described in the
  2673. L</"SOAP::Lite"> section.
  2674. =over 4
  2675. =item envelope()
  2676. This method allows you to build three kind of envelopes depending on the first
  2677. parameter:
  2678. =over 4
  2679. =item method
  2680. envelope(method => 'methodname', @parameters);
  2681. or
  2682. method('methodname', @parameters);
  2683. Lets you build a request/response envelope.
  2684. =item fault
  2685. envelope(fault => 'faultcode', 'faultstring', $details);
  2686. or
  2687. fault('faultcode', 'faultstring', $details);
  2688. Lets you build a fault envelope. Faultcode will be properly qualified and
  2689. details could be string or object.
  2690. =item freeform
  2691. envelope(freeform => 'something that I want to serialize');
  2692. or
  2693. freeform('something that I want to serialize');
  2694. Reserved for nonRPC calls. Lets you build your own payload inside a SOAP
  2695. envelope. All SOAP 1.1 specification rules are enforced, except method
  2696. specific ones. See UDDI::Lite as example.
  2697. =back
  2698. =back
  2699. For more examples see tests and SOAP::Transport::HTTP.pm
  2700. =head2 SOAP::SOM
  2701. All calls you are making through object oriented interface will
  2702. return SOAP::SOM object, and you can access actual values with it.
  2703. Next example gives you brief overview of the class:
  2704. my $soap = SOAP::Lite .....;
  2705. my $som = $soap->method(@parameters);
  2706. if ($som->fault) { # will be defined if Fault element is in the message
  2707. print $som->faultdetail; # returns value of 'detail' element as
  2708. # string or object
  2709. $som->faultcode; #
  2710. $som->faultstring; # also available
  2711. $som->faultactor; #
  2712. } else {
  2713. $som->result; # gives you access to result of call
  2714. # it could be any data structure, for example reference
  2715. # to array if server didi something like: return [1,2];
  2716. $som->paramsout; # gives you access to out parameters if any
  2717. # for example, you'll get array (1,2) if
  2718. # server returns ([1,2], 1, 2);
  2719. # [1,2] will be returned as $som->result
  2720. # and $som->paramsall will return ([1,2], 1, 2)
  2721. # see section IN/OUT, OUT PARAMETERS AND AUTOBINDING
  2722. # for more information
  2723. $som->paramsall; # gives access to result AND out parameters (if any)
  2724. # and returns them as one array
  2725. $som->valueof('//myelement'); # returns value(s) (as perl data) of
  2726. # 'myelement' if any. All elements in array
  2727. # context and only first one in scalar
  2728. $h = $som->headerof('//myheader'); # returns element as SOAP::Header, so
  2729. # you can access attributes and values
  2730. # with $h->mustUnderstand, $h->actor
  2731. # or $h->attr (for all attributes)
  2732. }
  2733. SOAP::SOM object gives you access to the deserialized envelope via several
  2734. methods. All methods accept a node path (similar to XPath notations).
  2735. SOM interprets '/' as the root node, '//' as relative location path
  2736. ('//Body' will find all bodies in document, as well as
  2737. '/Envelope//nums' will find all 'nums' nodes under Envelope node),
  2738. '[num]' as node number and '[op num]' with C<op> being a comparison
  2739. operator ('<', '>', '<=', '>=', '!', '=').
  2740. All nodes in nodeset will be returned in document order.
  2741. =over 4
  2742. =item match()
  2743. Accepts a path to a node and returns true/false in a boolean context and
  2744. a SOM object otherwise. C<valueof()> and C<dataof()> can be used to get
  2745. value(s) of matched node(s).
  2746. =item valueof()
  2747. Returns the value of a (previously) matched node. It accepts a node path.
  2748. In this case, it returns the value of matched node, but does not change the current
  2749. node. Suitable when you want to match a node and then navigate through
  2750. node children:
  2751. $som->match('/Envelope/Body/[1]'); # match method
  2752. $som->valueof('[1]'); # result
  2753. $som->valueof('[2]'); # first out parameter (if present)
  2754. The returned value depends on the context. In a scalar context it will return
  2755. the first element from matched nodeset. In an array context it will return
  2756. all matched elements.
  2757. =item dataof()
  2758. Same as C<valueof()>, but it returns a L</"SOAP::Data"> object, so you can get
  2759. access to the name, the type and attributes of an element.
  2760. =item headerof()
  2761. Same as C<dataof()>, but it returns L</"SOAP::Header"> object, so you can get
  2762. access to the name, the type and attributes of an element. Can be used for
  2763. modifying headers (if you want to see updated header inside Header element,
  2764. it's better to use this method instead of C<dataof()> method).
  2765. =item namespaceuriof()
  2766. Returns the uri associated with the matched element. This uri can also be
  2767. inherited, for example, if you have
  2768. <a xmlns='http://my.namespace'>
  2769. <b>
  2770. value
  2771. </b>
  2772. </a>
  2773. this method will return same value for 'b' element as for 'a'.
  2774. =back
  2775. SOAP::SOM also provides methods for direct access to the envelope, the body,
  2776. methods and parameters (both in and out). All these methods return real
  2777. values (in most cases it will be a hash reference), if called as object
  2778. method. Returned values also depend on context: in an array context it will
  2779. return an array of values and in scalar context it will return the first
  2780. element. So, if you want to access the first output parameter, you can call
  2781. C<< $param = $som->paramsout >>;
  2782. and you will get it regardless of the actual number of output parameters.
  2783. If you call it as class function (for example, SOAP::SOM::method)
  2784. it returns an XPath string that matches the current element
  2785. ('/Envelope/Body/[1]' in case of 'method'). The method will return C<undef>
  2786. if not present OR if you try to access an undefined element. To distinguish
  2787. between these two cases you can first access the C<match()> method that
  2788. will return true/false in a boolean context and then get the real value:
  2789. if ($som->match('//myparameter')) {
  2790. $value = $som->valueof; # can be undef too
  2791. } else {
  2792. # doesn't exist
  2793. }
  2794. =over 4
  2795. =item root()
  2796. Returns the value (as hash) of the root element. Do exactly the same as
  2797. C<< $som->valueof('/') >> does.
  2798. =item envelope()
  2799. Returns the value (as hash) of the C<Envelope> element. Keys in this hash will be
  2800. 'Header' (if present), 'Body' and any other (optional) elements. Values will
  2801. be the deserialized header, body, and elements, respectively.
  2802. If called as function (C<SOAP::SOM::envelope>) it will return a Xpath string
  2803. that matches the envelope content. Useful when you want just match it and
  2804. then iterate over the content by yourself. Example:
  2805. if ($som->match(SOAP::SOM::envelope)) {
  2806. $som->valueof('Header'); # should give access to header if present
  2807. $som->valueof('Body'); # should give access to body
  2808. } else {
  2809. # hm, are we doing SOAP or what?
  2810. }
  2811. =item header()
  2812. Returns the value (as hash) of the C<Header> element. If you want to access all
  2813. attributes in the header use:
  2814. # get element as SOAP::Data object
  2815. $transaction = $som->match(join '/', SOAP::SOM::header, 'transaction')->dataof;
  2816. # then you can access all attributes of 'transaction' element
  2817. $transaction->attr;
  2818. =item headers()
  2819. Returns a node set of values with deserialized headers. The difference between
  2820. the C<header()> and C<headers()> methods is that the first gives you access
  2821. to the whole header and second to the headers inside the 'Header' tag:
  2822. $som->headerof(join '/', SOAP::SOM::header, '[1]');
  2823. # gives you first header as SOAP::Header object
  2824. ($som->headers)[0];
  2825. # gives you value of the first header, same as
  2826. $som->valueof(join '/', SOAP::SOM::header, '[1]');
  2827. $som->header->{name_of_your_header_here}
  2828. # gives you value of name_of_your_header_here
  2829. =item body()
  2830. Returns the value (as hash) of the C<Body> element.
  2831. =item fault()
  2832. Returns the value (as hash) of C<Fault> element: C<faultcode>, C<faultstring> and
  2833. C<detail>. If C<Fault> element is present, C<result()>, C<paramsin()>,
  2834. C<paramsout()> and C<method()> will return an undef.
  2835. =item faultcode()
  2836. Returns the value of the C<faultcode> element if present and undef otherwise.
  2837. =item faultstring()
  2838. Returns the value of the C<faultstring> element if present and undef otherwise.
  2839. =item faultactor()
  2840. Returns the value of the C<faultactor> element if present and undef otherwise.
  2841. =item faultdetail()
  2842. Returns the value of the C<detail> element if present and undef otherwise.
  2843. =item method()
  2844. Returns the value of the method element (all input parameters if you call it on
  2845. a deserialized request envelope, and result/output parameters if you call it
  2846. on a deserialized response envelope). Returns undef if the 'Fault' element is
  2847. present.
  2848. =item result()
  2849. Returns the value of the C<result> of the method call. In fact, it will return
  2850. the first child element (in document order) of the method element.
  2851. =item paramsin()
  2852. Returns the value(s) of all passed parameters.
  2853. =item paramsout()
  2854. Returns value(s) of the output parameters.
  2855. =item paramsall()
  2856. Returns value(s) of the result AND output parameters as one array.
  2857. =back
  2858. =head2 SOAP::Schema
  2859. SOAP::Schema gives you ability to load schemas and create stubs according
  2860. to these schemas. Different syntaxes are provided:
  2861. =over 4
  2862. =item *
  2863. use SOAP::Lite
  2864. service => 'http://www.xmethods.net/sd/StockQuoteService.wsdl',
  2865. # service => 'file:/your/local/path/StockQuoteService.wsdl',
  2866. # service => 'file:./StockQuoteService.wsdl',
  2867. ;
  2868. print getQuote('MSFT'), "\n";
  2869. =item *
  2870. use SOAP::Lite;
  2871. print SOAP::Lite
  2872. -> service('http://www.xmethods.net/sd/StockQuoteService.wsdl')
  2873. -> getQuote('MSFT'), "\n";
  2874. =item *
  2875. use SOAP::Lite;
  2876. my $service = SOAP::Lite
  2877. -> service('http://www.xmethods.net/sd/StockQuoteService.wsdl');
  2878. print $service->getQuote('MSFT'), "\n";
  2879. =back
  2880. You can create stub with B<stubmaker> script:
  2881. perl stubmaker.pl http://www.xmethods.net/sd/StockQuoteService.wsdl
  2882. and you'll be able to access SOAP services in one line:
  2883. perl "-MStockQuoteService qw(:all)" -le "print getQuote('MSFT')"
  2884. or dynamically:
  2885. perl "-MSOAP::Lite service=>'file:./quote.wsdl'" -le "print getQuote('MSFT')"
  2886. Other supported syntaxes with stub(s) are:
  2887. =over 4
  2888. =item *
  2889. use StockQuoteService ':all';
  2890. print getQuote('MSFT'), "\n";
  2891. =item *
  2892. use StockQuoteService;
  2893. print StockQuoteService->getQuote('MSFT'), "\n";
  2894. =item *
  2895. use StockQuoteService;
  2896. my $service = StockQuoteService->new;
  2897. print $service->getQuote('MSFT'), "\n";
  2898. =back
  2899. Support for schemas is limited for now. Though module was tested with dozen
  2900. different schemas it won't understand complex objects and will work only
  2901. with WSDL.
  2902. =head2 SOAP::Trace
  2903. SOAP::Trace provides you with a trace/debug facility for the SOAP::Lite
  2904. library. To activate it you need to specify a list of traceable
  2905. events/parts of SOAP::Lite:
  2906. use SOAP::Lite +trace =>
  2907. qw(list of available traces here);
  2908. Available events are:
  2909. transport -- (client) access to request/response for transport layer
  2910. dispatch -- (server) shows full name of dispatched call
  2911. result -- (server) result of method call
  2912. parameters -- (server) parameters for method call
  2913. headers -- (server) headers of received message
  2914. objects -- (both) new/DESTROY calls
  2915. method -- (both) parameters for '->envelope(method =>' call
  2916. fault -- (both) parameters for '->envelope(fault =>' call
  2917. freeform -- (both) parameters for '->envelope(freeform =>' call
  2918. trace -- (both) trace enters into some important functions
  2919. debug -- (both) details about transport
  2920. For example:
  2921. use SOAP::Lite +trace =>
  2922. qw(method fault);
  2923. lets you output the parameter values for all your fault/normal envelopes onto STDERR.
  2924. If you want to log it you can either redirect STDERR to some file
  2925. BEGIN { open(STDERR, '>>....'); }
  2926. or (preferably) define your own function for a particular event:
  2927. use SOAP::Lite +trace =>
  2928. method => sub {'log messages here'}, fault => \&log_faults;
  2929. You can share the same function for several events:
  2930. use SOAP::Lite +trace =>
  2931. method, fault => \&log_methods_and_faults;
  2932. Also you can use 'all' to get all available tracing and use '-' in front of an event to
  2933. disable particular event:
  2934. use SOAP::Lite +trace =>
  2935. all, -transport; # to get all logging without transport messages
  2936. Finally,
  2937. use SOAP::Lite +trace;
  2938. will switch all debugging on.
  2939. You can use 'debug' instead of 'trace'. I prefer 'trace', others 'debug'.
  2940. Also C<on_debug> is available for backward compatibility, as in
  2941. use SOAP::Lite;
  2942. my $s = SOAP::Lite
  2943. -> uri('http://tempuri.org/')
  2944. -> proxy('http://beta.search.microsoft.com/search/MSComSearchService.asmx')
  2945. -> on_debug(sub{print@_}) # show you request/response with headers
  2946. ;
  2947. print $s->GetVocabulary(SOAP::Data->name('{http://tempuri.org/}Query' => 'something'))
  2948. ->valueof('//FOUND');
  2949. or switch it on individually, with
  2950. use SOAP::Lite +trace => debug;
  2951. or
  2952. use SOAP::Lite +trace => debug => sub {'do_what_I_want_here'};
  2953. Compare this with:
  2954. use SOAP::Lite +trace => transport;
  2955. which gives you access to B<actual> request/response objects, so you can even
  2956. set/read cookies or do whatever you want there.
  2957. The difference between C<debug> and C<transport> is that C<transport> will get
  2958. a HTTP::Request/HTTP::Response object and C<debug> will get a stringified request
  2959. (NOT OBJECT!). It can also be called in other places too.
  2960. =head2 SOAP::Fault
  2961. This class gives you access to Fault generated on server side. To make a
  2962. Fault message you might simply die on server side and SOAP processor will
  2963. wrap you message as faultstring element and will transfer Fault on client
  2964. side. But in some cases you need to have more control over this process and
  2965. SOAP::Fault class gives it to you. To use it, simply die with SOAP::Fault
  2966. object as a parameter:
  2967. die SOAP::Fault->faultcode('Server.Custom') # will be qualified
  2968. ->faultstring('Died in server method')
  2969. ->faultdetail(bless {code => 1} => 'BadError')
  2970. ->faultactor('http://www.soaplite.com/custom');
  2971. faultdetail() and faultactor() methods are optional and since faultcode and
  2972. faultstring are required to represent fault message SOAP::Lite will use
  2973. default values ('Server' and 'Application error') if not specified.
  2974. =head1 FEATURES AND OPTIONS
  2975. =head2 DEFAULT SETTINGS
  2976. Though this feature looks similar to L<autodispatch|/"AUTODISPATCHING AND SOAP:: PREFIX"> they have (almost)
  2977. nothing in common. It lets you create default object and all objects
  2978. created after that will be cloned from default object and hence get its
  2979. properties. If you want to provide common proxy() or uri() settings for
  2980. all SOAP::Lite objects in your application you may do:
  2981. use SOAP::Lite
  2982. proxy => 'http://localhost/cgi-bin/soap.cgi',
  2983. uri => 'http://my.own.com/My/Examples'
  2984. ;
  2985. my $soap1 = new SOAP::Lite; # will get the same proxy()/uri() as above
  2986. print $soap1->getStateName(1)->result;
  2987. my $soap2 = SOAP::Lite->new; # same thing as above
  2988. print $soap2->getStateName(2)->result;
  2989. # or you may override any settings you want
  2990. my $soap3 = SOAP::Lite->proxy('http://localhost/');
  2991. print $soap3->getStateName(1)->result;
  2992. B<Any> SOAP::Lite properties can be propagated this way. Changes in object
  2993. copies will not affect global settings and you may still change global
  2994. settings with C<< SOAP::Lite->self >> call which returns reference to
  2995. global object. Provided parameter will update this object and you can
  2996. even set it to C<undef>:
  2997. SOAP::Lite->self(undef);
  2998. The C<use SOAP::Lite> syntax also lets you specify default event handlers
  2999. for your code. If you have different SOAP objects and want to share the
  3000. same C<on_action()> (or C<on_fault()> for that matter) handler. You can
  3001. specify C<on_action()> during initialization for every object, but
  3002. you may also do:
  3003. use SOAP::Lite
  3004. on_action => sub {sprintf '%s#%s', @_}
  3005. ;
  3006. and this handler will be the default handler for all your SOAP objects.
  3007. You can override it if you specify a handler for a particular object.
  3008. See F<t/*.t> for example of on_fault() handler.
  3009. Be warned, that since C<use ...> is executed at compile time B<all> C<use>
  3010. statements will be executed B<before> script execution that can make
  3011. unexpected results. Consider code:
  3012. use SOAP::Lite proxy => 'http://localhost/';
  3013. print SOAP::Lite->getStateName(1)->result;
  3014. use SOAP::Lite proxy => 'http://localhost/cgi-bin/soap.cgi';
  3015. print SOAP::Lite->getStateName(1)->result;
  3016. B<BOTH> SOAP calls will go to C<'http://localhost/cgi-bin/soap.cgi'>. If
  3017. you want to execute C<use> at run-time, put it in C<eval>:
  3018. eval "use SOAP::Lite proxy => 'http://localhost/cgi-bin/soap.cgi'; 1" or die;
  3019. or use
  3020. SOAP::Lite->self->proxy('http://localhost/cgi-bin/soap.cgi');
  3021. =head2 IN/OUT, OUT PARAMETERS AND AUTOBINDING
  3022. SOAP::Lite gives you access to all parameters (both in/out and out) and
  3023. also does some additional work for you. Lets consider following example:
  3024. <mehodResponse>
  3025. <res1>name1</res1>
  3026. <res2>name2</res2>
  3027. <res3>name3</res3>
  3028. </mehodResponse>
  3029. In that case:
  3030. $result = $r->result; # gives you 'name1'
  3031. $paramout1 = $r->paramsout; # gives you 'name2', because of scalar context
  3032. $paramout1 = ($r->paramsout)[0]; # gives you 'name2' also
  3033. $paramout2 = ($r->paramsout)[1]; # gives you 'name3'
  3034. or
  3035. @paramsout = $r->paramsout; # gives you ARRAY of out parameters
  3036. $paramout1 = $paramsout[0]; # gives you 'res2', same as ($r->paramsout)[0]
  3037. $paramout2 = $paramsout[1]; # gives you 'res3', same as ($r->paramsout)[1]
  3038. Generally, if server returns C<return (1,2,3)> you will get C<1> as the result
  3039. and C<2> and C<3> as out parameters.
  3040. If the server returns C<return [1,2,3]> you will get an ARRAY from C<result()> and
  3041. C<undef> from C<paramsout()> .
  3042. Results can be arbitrary complex: they can be an array of something, they can
  3043. be objects, they can be anything and still be returned by C<result()> . If only
  3044. one parameter is returned, C<paramsout()> will return C<undef>.
  3045. But there is more.
  3046. If you have in your output parameters a parameter with the same
  3047. signature (name+type) as in the input parameters this parameter will be mapped
  3048. into your input automatically. Example:
  3049. B<server>:
  3050. sub mymethod {
  3051. shift; # object/class reference
  3052. my $param1 = shift;
  3053. my $param2 = SOAP::Data->name('myparam' => shift() * 2);
  3054. return $param1, $param2;
  3055. }
  3056. B<client>:
  3057. $a = 10;
  3058. $b = SOAP::Data->name('myparam' => 12);
  3059. $result = $soap->mymethod($a, $b);
  3060. After that, C<< $result == 10 and $b->value == 24 >>! Magic? Sort of.
  3061. Autobinding gives it to you. That will work with objects also with
  3062. one difference: you do not need to worry about the name and the type of
  3063. object parameter. Consider the C<PingPong> example (F<examples/My/PingPong.pm> and
  3064. F<examples/pingpong.pl>):
  3065. B<server>:
  3066. package My::PingPong;
  3067. sub new {
  3068. my $self = shift;
  3069. my $class = ref($self) || $self;
  3070. bless {_num=>shift} => $class;
  3071. }
  3072. sub next {
  3073. my $self = shift;
  3074. $self->{_num}++;
  3075. }
  3076. B<client>:
  3077. use SOAP::Lite +autodispatch =>
  3078. uri => 'urn:',
  3079. proxy => 'http://localhost/'
  3080. ;
  3081. my $p = My::PingPong->new(10); # $p->{_num} is 10 now, real object returned
  3082. print $p->next, "\n"; # $p->{_num} is 11 now!, object autobinded
  3083. =head2 AUTODISPATCHING AND SOAP:: PREFIX
  3084. B<WARNING>: C<autodispatch> feature can have side effects for your application
  3085. and can affect functionality of other modules/libraries because of overloading
  3086. UNIVERSAL::AUTOLOAD. All unresolved calls will be dispatched as SOAP calls,
  3087. however it could be not what you want in some cases. If so, consider using
  3088. object interface (see C<implementation of OO interface>).
  3089. SOAP::Lite provides an autodispatching feature that lets you create
  3090. code which looks the same for local and remote access.
  3091. For example:
  3092. use SOAP::Lite +autodispatch =>
  3093. uri => 'urn:/My/Examples',
  3094. proxy => 'http://localhost/'
  3095. ;
  3096. tells SOAP to 'autodispatch' all calls to the 'http://localhost/' endpoint with
  3097. the 'urn:/My/Examples' uri. All consequent method calls can look like:
  3098. print getStateName(1), "\n";
  3099. print getStateNames(12,24,26,13), "\n";
  3100. print getStateList([11,12,13,42])->[0], "\n";
  3101. print getStateStruct({item1 => 10, item2 => 4})->{item2}, "\n";
  3102. As you can see, there is no SOAP specific coding at all.
  3103. The same logic will work for objects as well:
  3104. print "Session iterator\n";
  3105. my $p = My::SessionIterator->new(10);
  3106. print $p->next, "\n";
  3107. print $p->next, "\n";
  3108. This will access the remote My::SessionIterator module, gets an object, and then
  3109. calls remote methods again. The object will be transferred to the server, the
  3110. method is executed there and the result (and the modified object!) will be
  3111. transferred back to the client.
  3112. Autodispatch will work B<only> if you do not have the same method in your
  3113. code. For example, if you have C<use My::SessionIterator> somewhere in your
  3114. code of our previous example, all methods will be resolved locally and no
  3115. SOAP calls will be done. If you want to get access to remote objects/methods
  3116. even in that case, use C<SOAP::> prefix to your methods, like:
  3117. print $p->SOAP::next, "\n";
  3118. See C<pingpong.pl> for example of a script, that works with the same object
  3119. locally and remotely.
  3120. C<SOAP::> prefix also gives you ability to access methods that have the same
  3121. name as methods of SOAP::Lite itself. For example, you want to call method
  3122. new() for your class C<My::PingPong> through OO interface.
  3123. First attempt could be:
  3124. my $s = SOAP::Lite
  3125. -> uri('http://www.soaplite.com/My/PingPong')
  3126. -> proxy('http://localhost/cgi-bin/soap.cgi')
  3127. ;
  3128. my $obj = $s->new(10);
  3129. but it won't work, because SOAP::Lite has method new() itself. To provide
  3130. a hint, you should use C<SOAP::> prefix and call will be dispatched remotely:
  3131. my $obj = $s->SOAP::new(10);
  3132. You can mix autodispatch and usual SOAP calls in the same code if
  3133. you need it. Keep in mind, that calls with SOAP:: prefix should always be a
  3134. method call, so if you want to call functions, use C<< SOAP->myfunction() >>
  3135. instead of C<SOAP::myfunction()>.
  3136. Be warned though Perl has very flexible syntax some versions will complain
  3137. Bareword "autodispatch" not allowed while "strict subs" in use ...
  3138. if you try to put 'autodispatch' and '=>' on separate lines. So, keep them
  3139. on the same line, or put 'autodispatch' in quotes:
  3140. use SOAP::Lite 'autodispatch' # DON'T use plus in this case
  3141. => ....
  3142. ;
  3143. =head2 ACCESSING HEADERS AND ENVELOPE ON SERVER SIDE
  3144. SOAP::Lite gives you direct access to all headers and the whole envelope on
  3145. the server side. Consider the following code from My::Parameters.pm:
  3146. sub byname {
  3147. my($a, $b, $c) = @{pop->method}{qw(a b c)};
  3148. return "a=$a, b=$b, c=$c";
  3149. }
  3150. You will get this functionality ONLY if you inherit your class from
  3151. the SOAP::Server::Parameters class. This should keep existing code working and
  3152. provides this feature only when you need it.
  3153. Every method on server side will be called as class/object method, so it will
  3154. get an B<object reference> or a B<class name> as the first parameter, then the
  3155. method parameters, and then an envelope as SOAP::SOM object. Shortly:
  3156. $self [, @parameters] , $envelope
  3157. If you have a fixed number of parameters, you can do:
  3158. my $self = shift;
  3159. my($param1, $param2) = @_;
  3160. and ignore the envelope. If you need access to the envelope you can do:
  3161. my $envelope = pop;
  3162. since the envelope is always the last element in the parameters list.
  3163. The C<byname()> method C<< pop->method >> will return a hash with
  3164. parameter names as hash keys and parameter values as hash values:
  3165. my($a, $b, $c) = @{pop->method}{qw(a b c)};
  3166. gives you by-name access to your parameters.
  3167. =head2 SERVICE DEPLOYMENT. STATIC AND DYNAMIC
  3168. Let us scrutinize the deployment process. When designing your SOAP server you
  3169. can consider two kind of deployment: B<static> and B<dynamic>.
  3170. For both, static and dynamic, you should specify C<MODULE>,
  3171. C<MODULE::method>, C<method> or C<PATH/> when creating C<use>ing the
  3172. SOAP::Lite module. The difference between static and dynamic deployment is
  3173. that in case of 'dynamic', any module which is not present will be loaded on
  3174. demand. See the L</"SECURITY"> section for detailed description.
  3175. Example for B<static> deployment:
  3176. use SOAP::Transport::HTTP;
  3177. use My::Examples; # module is preloaded
  3178. SOAP::Transport::HTTP::CGI
  3179. # deployed module should be present here or client will get 'access denied'
  3180. -> dispatch_to('My::Examples')
  3181. -> handle;
  3182. Example for B<dynamic> deployment:
  3183. use SOAP::Transport::HTTP;
  3184. # name is unknown, module will be loaded on demand
  3185. SOAP::Transport::HTTP::CGI
  3186. # deployed module should be present here or client will get 'access denied'
  3187. -> dispatch_to('/Your/Path/To/Deployed/Modules', 'My::Examples')
  3188. -> handle;
  3189. For static deployment you should specify the MODULE name directly.
  3190. For dynamic deployment you can specify the name either directly (in that
  3191. case it will be C<require>d without any restriction) or indirectly, with a PATH
  3192. In that case, the ONLY path that will be available will be the PATH given
  3193. to the dispatch_to() method). For information how to handle this situation
  3194. see L</"SECURITY"> section.
  3195. You should also use static binding when you have several different classes
  3196. in one file and want to make them available for SOAP calls.
  3197. B<SUMMARY>:
  3198. dispatch_to(
  3199. # dynamic dispatch that allows access to ALL modules in specified directory
  3200. PATH/TO/MODULES
  3201. # 1. specifies directory
  3202. # -- AND --
  3203. # 2. gives access to ALL modules in this directory without limits
  3204. # static dispatch that allows access to ALL methods in particular MODULE
  3205. MODULE
  3206. # 1. gives access to particular module (all available methods)
  3207. # PREREQUISITES:
  3208. # module should be loaded manually (for example with 'use ...')
  3209. # -- OR --
  3210. # you can still specify it in PATH/TO/MODULES
  3211. # static dispatch that allows access to particular method ONLY
  3212. MODULE::method
  3213. # same as MODULE, but gives access to ONLY particular method,
  3214. # so there is not much sense to use both MODULE and MODULE::method
  3215. # for the same MODULE
  3216. )
  3217. In addition to this SOAP::Lite also supports experimental syntax that
  3218. allows you bind specific URL or SOAPAction to CLASS/MODULE or object:
  3219. dispatch_with({
  3220. URI => MODULE, # 'http://www.soaplite.com/' => 'My::Class',
  3221. SOAPAction => MODULE, # 'http://www.soaplite.com/method' => 'Another::Class',
  3222. URI => object, # 'http://www.soaplite.com/obj' => My::Class->new,
  3223. })
  3224. URI is checked before SOAPAction. You may use both C<dispatch_to()> and
  3225. C<dispatch_with()> syntax and C<dispatch_with()> has more priority, so
  3226. first checked URI, then SOAPAction and only then will be checked
  3227. C<dispatch_to()>. See F<t/03-server.t> for more information and examples.
  3228. =head2 SECURITY
  3229. Due to security reasons, the current path for perl modules (C<@INC>) will be disabled
  3230. once you have chosen dynamic deployment and specified your own C<PATH/>.
  3231. If you want to access other modules in your included package you have
  3232. several options:
  3233. =over 4
  3234. =item 1
  3235. Switch to static linking:
  3236. use MODULE;
  3237. $server->dispatch_to('MODULE');
  3238. It can be useful also when you want to import something specific
  3239. from the deployed modules:
  3240. use MODULE qw(import_list);
  3241. =item 2
  3242. Change C<use> to C<require>. The path is unavailable only during
  3243. the initialization part, and it is available again during execution.
  3244. So, if you do C<require> somewhere in your package, it will work.
  3245. =item 3
  3246. Same thing, but you can do:
  3247. eval 'use MODULE qw(import_list)'; die if $@;
  3248. =item 4
  3249. Assign a C<@INC> directory in your package and then make C<use>.
  3250. Don't forget to put C<@INC> in C<BEGIN{}> block or it won't work:
  3251. BEGIN { @INC = qw(my_directory); use MODULE }
  3252. =back
  3253. =head2 COMPRESSION
  3254. SOAP::Lite provides you option for enabling compression on wire (for HTTP
  3255. transport only). Both server and client should support this capability,
  3256. but this logic should be absolutely transparent for your application.
  3257. Compression can be enabled by specifying threshold for compression on client
  3258. or server side:
  3259. =over 4
  3260. =item Client
  3261. print SOAP::Lite
  3262. -> uri('http://localhost/My/Parameters')
  3263. -> proxy('http://localhost/', options => {compress_threshold => 10000})
  3264. -> echo(1 x 10000)
  3265. -> result
  3266. ;
  3267. =item Server
  3268. my $server = SOAP::Transport::HTTP::CGI
  3269. -> dispatch_to('My::Parameters')
  3270. -> options({compress_threshold => 10000})
  3271. -> handle;
  3272. =back
  3273. For more information see L<COMPRESSION section|SOAP::Transport::HTTP/"COMPRESSION">
  3274. in HTTP transport documentation.
  3275. =head2 OBJECTS-BY-REFERENCE
  3276. SOAP::Lite implements an experimental (yet functional) support for
  3277. objects-by-reference. You should not see any difference on the client side
  3278. when using this. On the server side you should specify the names of the
  3279. classes you want to be returned by reference (instead of by value) in the
  3280. C<objects_by_reference()> method for your server implementation (see
  3281. soap.pop3, soap.daemon and Apache.pm).
  3282. Garbage collection is done on the server side (not earlier than after 600
  3283. seconds of inactivity time), and you can overload the default behavior with
  3284. specific functions for any particular class.
  3285. Binding does not have any special syntax and is implemented on server side
  3286. (see the differences between My::SessionIterator and My::PersistentIterator).
  3287. On the client side, objects will have same type/class as before
  3288. (C<< My::SessionIterator->new() >> will return an object of class
  3289. My::SessionIterator). However, this object is just a stub with an object ID
  3290. inside.
  3291. =head2 INTEROPERABILITY
  3292. =over 4
  3293. =item Microsoft's .NET
  3294. To use .NET client and SOAP::Lite server
  3295. =over 4
  3296. =item qualify all elements
  3297. use fully qualified names for your return values, e.g.:
  3298. return SOAP::Data->name('{http://namespace.here/}myname')->type('string')->value($output);
  3299. Use namespace that you specify for URI instead of 'http://namespace.here/'.
  3300. In addition see comment about default incoding in .NET Web Services below.
  3301. =back
  3302. To use SOAP::Lite client and .NET server
  3303. =over 4
  3304. =item declare proper soapAction (uri/method) in your call
  3305. For example, use C<on_action(sub{join '', @_})>.
  3306. =item qualify all elements
  3307. Any of following actions should work:
  3308. =over 4
  3309. =item use fully qualified name for method parameters
  3310. Use C<< SOAP::Data->name('{http://namespace.here/}Query' => 'biztalk') >> instead of
  3311. C<< SOAP::Data->name('Query' => 'biztalk') >>.
  3312. Example of SOAPsh call (all parameters should be in one line):
  3313. > perl SOAPsh.pl
  3314. "http://beta.search.microsoft.com/search/mscomsearchservice.asmx"
  3315. "http://tempuri.org/"
  3316. "on_action(sub{join '', @_})"
  3317. "GetVocabulary(SOAP::Data->name('{http://tempuri.org/}Query' => 'biztalk'))"
  3318. =item make method in default namespace
  3319. instead of
  3320. my @rc = $soap->call(add => @parms)->result;
  3321. # -- OR --
  3322. my @rc = $soap->add(@parms)->result;
  3323. use
  3324. my $method = SOAP::Data->name('add')
  3325. ->attr({xmlns => 'http://tempuri.org/'});
  3326. my @rc = $soap->call($method => @parms)->result;
  3327. =item modify .NET server if you are in charge for that
  3328. Stefan Pharies <[email protected]>:
  3329. SOAP::Lite uses the SOAP encoding (section 5 of the soap 1.1 spec), and
  3330. the default for .NET Web Services is to use a literal encoding. So
  3331. elements in the request are unqualified, but your service expects them to
  3332. be qualified. .Net Web Services has a way for you to change the expected
  3333. message format, which should allow you to get your interop working.
  3334. At the top of your class in the asmx, add this attribute (for Beta 1):
  3335. [SoapService(Style=SoapServiceStyle.RPC)]
  3336. Another source said it might be this attribute (for Beta 2):
  3337. [SoapRpcService]
  3338. Full Web Service text may look like:
  3339. <%@ WebService Language="C#" Class="Test" %>
  3340. using System;
  3341. using System.Web.Services;
  3342. using System.Xml.Serialization;
  3343. [SoapService(Style=SoapServiceStyle.RPC)]
  3344. public class Test : WebService {
  3345. [WebMethod]
  3346. public int add(int a, int b) {
  3347. return a + b;
  3348. }
  3349. }
  3350. Another example from Kirill Gavrylyuk <[email protected]>:
  3351. "You can insert [SoapRpcService()] attribute either on your class or on
  3352. operation level".
  3353. <%@ WebService Language=CS class="DataType.StringTest"%>
  3354. namespace DataType {
  3355. using System;
  3356. using System.Web.Services;
  3357. using System.Web.Services.Protocols;
  3358. using System.Web.Services.Description;
  3359. [SoapRpcService()]
  3360. public class StringTest: WebService {
  3361. [WebMethod]
  3362. [SoapRpcMethod()]
  3363. public string RetString(string x) {
  3364. return(x);
  3365. }
  3366. }
  3367. }
  3368. Example from Yann Christensen <[email protected]>:
  3369. using System;
  3370. using System.Web.Services;
  3371. using System.Web.Services.Protocols;
  3372. namespace Currency {
  3373. [WebService(Namespace="http://www.yourdomain.com/example")]
  3374. [SoapRpcService]
  3375. public class Exchange {
  3376. [WebMethod]
  3377. public double getRate(String country, String country2) {
  3378. return 122.69;
  3379. }
  3380. }
  3381. }
  3382. =back
  3383. =back
  3384. Thanks to
  3385. Petr Janata <[email protected]>,
  3386. Stefan Pharies <[email protected]>, and
  3387. Brian Jepson <[email protected]>
  3388. for description and examples.
  3389. =back
  3390. =head2 TROUBLESHOOTING
  3391. =over 4
  3392. =item HTTP transport
  3393. See L<TROUBLESHOOTING|SOAP::Transport::HTTP/"TROUBLESHOOTING"> section in
  3394. documentation for HTTP transport.
  3395. =item COM interface
  3396. =over 4
  3397. =item Can't call method "server" on undefined value
  3398. Probably you didn't register Lite.dll with 'regsvr32 Lite.dll'
  3399. =item Failed to load PerlCtrl runtime
  3400. Probably you have two Perl installations in different places and
  3401. ActiveState's Perl isn't the first Perl specified in PATH. Rename the
  3402. directory with another Perl (at least during the DLL's startup) or put
  3403. ActiveState's Perl on the first place in PATH.
  3404. =back
  3405. =item XML Parsers
  3406. =over 4
  3407. =item SAX parsers
  3408. SAX 2.0 has a known bug in org.xml.sax.helpers.ParserAdapter
  3409. rejects Namespace prefix used before declaration
  3410. (http://www.megginson.com/SAX/index.html).
  3411. That means that in some cases SOAP messages created by SOAP::Lite may not
  3412. be parsed properly by SAX2/Java parser, because Envelope
  3413. element contains namespace declarations and attributes that depends on this
  3414. declarations. According to XML specification order of these attributes is
  3415. not significant. SOAP::Lite does NOT have a problem parsing such messages.
  3416. Thanks to Steve Alpert (Steve_Alpert@idx.com) for pointing on it.
  3417. =back
  3418. =back
  3419. =head2 PERFORMANCE
  3420. =over 4
  3421. =item Processing of XML encoded fragments
  3422. SOAP::Lite is based on XML::Parser which is basically wrapper around James
  3423. Clark's expat parser. Expat's behavior for parsing XML encoded string can
  3424. affect processing messages that have lot of encoded entities, like XML
  3425. fragments, encoded as strings. Providing low-level details, parser will call
  3426. char() callback for every portion of processed stream, but individually for
  3427. every processed entity or newline. It can lead to lot of calls and additional
  3428. memory manager expenses even for small messages. By contrast, XML messages
  3429. which are encoded as base64, don't have this problem and difference in
  3430. processing time can be significant. For XML encoded string that has about 20
  3431. lines and 30 tags, number of call could be about 100 instead of one for
  3432. the same string encoded as base64.
  3433. Since it is parser's feature there is NO fix for this behavior (let me know
  3434. if you find one), especially because you need to parse message you already
  3435. got (and you cannot control content of this message), however, if your are
  3436. in charge for both ends of processing you can switch encoding to base64 on
  3437. sender's side. It will definitely work with SOAP::Lite and it B<may> work with
  3438. other toolkits/implementations also, but obviously I cannot guarantee that.
  3439. If you want to encode specific string as base64, just do
  3440. C<< SOAP::Data->type(base64 => $string) >> either on client or on server
  3441. side. If you want change behavior for specific instance of SOAP::Lite, you
  3442. may subclass C<SOAP::Serializer>, override C<as_string()> method that is
  3443. responsible for string encoding (take a look into C<as_base64()>) and
  3444. specify B<new> serializer class for your SOAP::Lite object with:
  3445. my $soap = new SOAP::Lite
  3446. serializer => My::Serializer->new,
  3447. ..... other parameters
  3448. or on server side:
  3449. my $server = new SOAP::Transport::HTTP::Daemon # or any other server
  3450. serializer => My::Serializer->new,
  3451. ..... other parameters
  3452. If you want to change this behavior for B<all> instances of SOAP::Lite, just
  3453. substitute C<as_string()> method with C<as_base64()> somewhere in your
  3454. code B<after> C<use SOAP::Lite> and B<before> actual processing/sending:
  3455. *SOAP::Serializer::as_string = \&SOAP::Serializer::as_base64;
  3456. Be warned that last two methods will affect B<all> strings and convert them
  3457. into base64 encoded. It doesn't make any difference for SOAP::Lite, but it
  3458. B<may> make a difference for other toolkits.
  3459. =back
  3460. =head2 WEBHOSTING INSTALLATION
  3461. As soon as you have telnet access to the box and XML::Parser is already
  3462. installed there (or you have Perl 5.6 and can use XML::Parser::Lite) you
  3463. may install your own copy of SOAP::Lite even if hosting provider doesn't
  3464. want to do it.
  3465. Setup C<PERL5LIB> environment variable. Depending on your shell it may
  3466. look like:
  3467. PERL5LIB=/you/home/directory/lib; export PERL5LIB
  3468. C<lib> here is the name of directory where all libraries will be installed
  3469. under your home directory.
  3470. Run CPAN module with
  3471. perl -MCPAN -e shell
  3472. and run three commands from CPAN shell
  3473. > o conf make_arg -I~/lib
  3474. > o conf make_install_arg -I~/lib
  3475. > o conf makepl_arg LIB=~/lib PREFIX=~ INSTALLMAN1DIR=~/man/man1 INSTALLMAN3DIR=~/man/man3
  3476. C<LIB> will specify directory where all libraries will reside.
  3477. C<PREFIX> will specify prefix for all directories (like F<lib>, F<bin>, F<man>,
  3478. though it doesn't work in all cases for some reason).
  3479. C<INSTALLMAN1DIR> and C<INSTALLMAN3DIR> specify directories for manuals
  3480. (if you don't specify them, install will fail because it'll try to setup
  3481. it in default directory and you don't have permissions for that).
  3482. Then run:
  3483. > install SOAP::Lite
  3484. Now in your scripts you need to specify:
  3485. use lib '/your/home/directory/lib';
  3486. somewhere before C<'use SOAP::Lite;'>
  3487. =head1 BUGS AND LIMITATIONS
  3488. =over 4
  3489. =item *
  3490. No support for multidimensional, partially transmitted and sparse arrays
  3491. (however arrays of arrays are supported, as well as any other data
  3492. structures, and you can add your own implementation with SOAP::Data).
  3493. =item *
  3494. Limited support for WSDL schema.
  3495. =item *
  3496. XML::Parser::Lite relies on Unicode support in Perl and doesn't do
  3497. entity decoding.
  3498. =item *
  3499. Limited support for mustUnderstand and Actor attributes.
  3500. =back
  3501. =head1 PLATFORMS
  3502. =over 4
  3503. =item MacOS
  3504. Information about XML::Parser for MacPerl could be found here:
  3505. http://bumppo.net/lists/macperl-modules/1999/07/msg00047.html
  3506. Compiled XML::Parser for MacOS could be found here:
  3507. http://www.perl.com/CPAN-local/authors/id/A/AS/ASANDSTRM/XML-Parser-2.27-bin-1-MacOS.tgz
  3508. =back
  3509. =head1 AVAILABILITY
  3510. You can download the latest version SOAP::Lite for Unix or SOAP::Lite for Win32 from http://soaplite.com/ .
  3511. SOAP::Lite is available also from CPAN ( http://search.cpan.org/search?dist=SOAP-Lite ).
  3512. You are very welcome to write mail to the author (paulclinger@yahoo.com)
  3513. with your comments, suggestions, bug reports and complaints.
  3514. =head1 SEE ALSO
  3515. L<SOAP> SOAP/Perl library from Keith Brown ( http://www.develop.com/soap/ ) or
  3516. ( http://search.cpan.org/search?dist=SOAP )
  3517. =head1 ACKNOWLEDGMENTS
  3518. A lot of thanks to
  3519. Tony Hong <[email protected]>,
  3520. Petr Janata <[email protected]>,
  3521. Murray Nesbitt <[email protected]>,
  3522. Robert Barta <[email protected]>,
  3523. Gisle Aas <[email protected]>,
  3524. Carl K. Cunningham <[email protected]>,
  3525. Graham Glass <[email protected]>,
  3526. Chris Radcliff <[email protected]>,
  3527. Arun Kumar <[email protected]>,
  3528. and many many others
  3529. for provided help, feedback, support, patches and comments.
  3530. =head1 COPYRIGHT
  3531. Copyright (C) 2000-2001 Paul Kulchenko. All rights reserved.
  3532. This library is free software; you can redistribute it and/or modify
  3533. it under the same terms as Perl itself.
  3534. =head1 AUTHOR
  3535. Paul Kulchenko (paulclinger@yahoo.com)
  3536. =cut