UDDI/HalfDecent.pm untested

filter: Statementstmt 0.0% 0 / 187 Branchbran 0.0% 0 / 68 Conditioncond 0.0% 0 / 17 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 330 CC 34 SCAR 39.3
CC
34
Cov
0%
_send_and_receive
156.0
_find
110.0
_uddi_namespace
20.0
CRAP 50.8
1 package UDDI::HalfDecent;
2 use strict;
3 use warnings;
4  
5 use HTML::Entities;
6 use LWP::UserAgent;
7 use HTTP::Request::Common qw();
8 use XML::LibXML;
9 use XML::LibXML::XPathContext; # Included separately for pre-1.61 XML::LibXML
10 use Data::Dumper; $Data::Dumper::Indent = 1;
11  
12 use Exception::Class (UDDIException => { fields => [ 'detail' ],
13 alias => 'oops' });
14 UDDIException->Trace(1) if $ENV{UDDI_TRACE};
15  
16 package UDDIException;
17 sub full_message {
18 my $this = shift();
19 return __PACKAGE__ . ": " . $this->message . " (" . $this->detail . ")";
20 }
21 package UDDI::HalfDecent;
22  
23 use UDDI::HalfDecent::ResultSet;
24  
25  
26 =head1 NAME
27  
28 UDDI::HalfDecent - a half-decent implementation of UDDI
29  
30 =head1 SYNOPSIS
31  
32 use UDDI::HalfDecent;
33 $endpoint = "http://uddi.csiss.gmu.edu:6060/soar/uddi/inquire";
34 $uddi = new UDDI::HalfDecent($endpoint);
35 $rs = $uddi->find_business(name => 'frog');
36 $n = $rs->count();
37 foreach $i (0 .. $n-1) {
38 $rec = $rs->record($i);
39 $key = $rec->xpath('@businessKey');
40 $rs2 = $uddi->find_service(businessKey => $key);
41 }
42  
43 =head1 DESCRIPTION
44  
45 I have tried to use and love C<UDDI::Lite>, honestly I have. I have
46 tried to use the underlying C<SOAP::Lite>, which package C<UDDI::Lite>
47 is part of, and ploughed countless futile man-hours into the effort.
48 There is no doubt that that suite of modules is a I<tour de force> of
49 intellectual effort, startling in its strange, crystalline beauty and
50 innovative to a degree one hardly thought possible. All of this is,
51 however, marred by the one tiny flaw that it doesn't work. And worse,
52 it doesn't diagnose its failures: error-handling callbacks don't get
53 invoked, global error-indication objects don't get set, and SOAP
54 faults perfectly visible in the protocol XML go unreported.
55  
56 So the obvious thing to do is go into that code and fix it, right?
57 Except you can't because the code is so obviously a work of genius
58 that no mortal being can understand it. (I am not just being feeble
59 here: this is the overwhelming feeling of the broader community). The
60 C<SOAP::Lite> code, including C<UDDI::Lite>, is a fantastic
61 illustration of Kernighan and Pike's observation: "Everyone knows that
62 debugging is twice as hard at writing a program in the first place.
63 So if you're as clever as you can be be when you write it, how will
64 you ever debug it?" (from I<The Elements of Programming Style>, 1978 -
65 very nearly thirty years old as I write this, but as fresh and
66 relevant as ever. And very funny, which is not something you can say
67 about most programming books.)
68  
69 So the C<SOAP::Lite> package is a write-off, and my attempts to
70 interact with its community underline that: the email address of the
71 package maintainer no longer works, and the mailing list consists
72 entirely of forlorn souls such as myself asking "has anyone got I<x>
73 to work?" and never receiving replies.
74  
75 And the only other UDDI package on CPAN is one just called C<UDDI>,
76 the most recent release of which is 0.03 from the year 2000, and which
77 fails its test-suite.
78  
79 So that leaves only one option, which is to start from the ground and
80 roll my own. At least that way I'll be ablet to debug it.
81  
82 The number one design principle with this module (and anyone who's
83 used C<SOAP::Lite> will understand why I make a big deal of this) is
84 that B<all errors are reported immediately>, through the throwing of a
85 C<Exception::Class::UDDI> object. If something goes wrong, you
86 will know it; and you will know it immediately; and you will know
87 I<what> went wrong. Just imagine!
88  
89 On the downside, this module has no pretention to the flexibility and
90 generality that C<SOAP::Lite> and C<UDDI::Lite> would offer, if only
91 they worked. Those modules set out to encompass RPC-style and
92 document-style SOAP, XML-RPC, UDDI versions 1, 2 and 3 (although not
93 really 3) and of course a hundred different ways of expressing
94 everything. This module will offer only those facilities required to
95 access actual UDDI servers - and, more precisely, those facilities
96 needed by C<z2uddi>.
97  
98 =head1 METHODS
99  
100 =head2 new()
101  
102 $uddi = new UDDI::HalfDecent($endpoint);
103  
104 Creates and returns a new UDDI object for communicating with the
105 specified endpoint.
106  
107 =cut
108  
109 sub new {
110 my $class = shift();
111 my($endpoint) = @_;
112  
113 my $this = bless {
114 endpoint => $endpoint,
115 options => {
116 "http-version" => 1.1,
117 "uddi-version" => 3,
118 },
119 loglevels => {},
120 ua => undef,
121 parser => undef,
122 }, $class;
123  
124 my $levels = $ENV{UDDI_LOG};
125 $this->loglevel(split /[,\s]+/, $levels)
126 if defined $levels;
127  
128 return $this;
129 }
130  
131  
132 =head2 option()
133  
134 $val = $uddi->option($key);
135 $oldval = $uddi->option($key, $newval);
136 do_some_stuff($uddi);
137 $uddi->option($key, $oldval);
138  
139 Gets and gets the values of named options in the UDDI object. When
140 called with a single argument, the current value of the specified
141 option is returned; when called with two arguments the option named by
142 the first is set to the value specified by the second, and the I<old>
143 value of the named option is returned.
144  
145 Options affect the functioning of the UDDI object as follows:
146  
147 =over 4
148  
149 =item http-version
150  
151 Specifies the version of HTTP to use. Valid values are C<1.0> and
152 C<1.1>; if not specified, HTTP 1.1 is used.
153  
154 =item uddi-version
155  
156 Specifies the version of UDDI to use. Valid values are C<1>, C<2> and
157 C<3>; if not specified, UDDI version 3 is used. Note that C<some
158 servers are arses> when it comes to this: for example, if you send a
159 v3 request to C<http://uddi.microsoft.com/inquire>, it will send a v2
160 response whose fault information will therefore not be readable. So
161 if you get funny results from a server, try playing with this.
162  
163 =item proxy
164  
165 If this is set then it is the URL of a proxy which will be used for
166 all HTTP transactions. Not set by default.
167  
168 =item loglabel
169  
170 If set to a true value, the all log messages emitted will have a
171 .prefix of the form C<_log(>I<level>C<)> and the messages themselves
172 will be enclosed in square brackets. This makes the logging more
173 explicit, and in particular makes it possible to see zero-length log
174 messages such as empty C<response>s. Not set by default.
175  
176 =back
177  
178 =cut
179  
180 sub option {
181 my $this = shift();
182 my($key, $value) = @_;
183  
184 my $oldval = $this->{options}->{$key};
185 $this->{options}->{$key} = $value
186 if defined $value;
187  
188 return $oldval;
189 }
190  
191  
192 =head2 loglevel()
193  
194 $uddi->loglevel(qw(-- request response));
195  
196 Sets the logging level of the UDDI object, controlling what logging
197 information is emitted on the standard error stream. Zero or more
198 levels may be specified, each as a separate argument: each specified
199 level is added to the current set unless it is prefixed with a minus
200 sign in which case it is removed from the current set. The special
201 option C<--> clears all currently set levels.
202  
203 Supported logging levels include:
204  
205 =over 4
206  
207 =item request
208  
209 The XML of UDDI requests is emitted.
210  
211 =item response
212  
213 The XML of UDDI responses is emitted.
214  
215 =item requestheaders
216  
217 The headers associated with the requests sent
218  
219 =item responseheaders
220  
221 The headers associated with the requests sent
222  
223 =back 4
224  
225 =cut
226  
227 sub loglevel {
228 my $this = shift();
229  
230 foreach my $level (@_) {
231 if ($level eq "--") {
232 $this->{loglevels} = {};
233 } elsif ($level =~ s/^-//) {
234 $this->{loglevels}->{$level} = 0;
235 } else {
236 $this->{loglevels}->{$level} = 1;
237 }
238 }
239 }
240  
241  
242 # Logs the specified data to stderr if the relevant level is set
243 sub _log {
244 my $this = shift();
245 my($level, @message) = @_;
246  
247 my $message = join('', @message);
248 $message =~ s/\n$//s;
249 return if !$this->{loglevels}->{$level};
250  
251 if ($this->option("loglabel")) {
252 print STDERR "_log($level) [$message]\n";
253 } else {
254 print STDERR "$message\n";
255 }
256 }
257  
258  
259 # Returns a Web user-agent to be used by the UDDI object
260 sub _ua {
261 my $this = shift();
262  
263 my $ua = $this->{ua};
264 if (!defined $ua) {
265 $this->{ua} = $ua = new LWP::UserAgent();
266 my $proxy = $this->option("proxy");
267 $ua->proxy(http => $proxy)
268 if defined $proxy;
269 }
270  
271 return $ua;
272 }
273  
274  
275 # Returns an XML parser to be used by the UDDI object
276 sub _parser {
277 my $this = shift();
278  
279 my $parser = $this->{parser};
280 if (!defined $parser) {
281 $this->{parser} = $parser = new XML::LibXML();
282 }
283  
284 return $parser;
285 }
286  
287  
288 # If feel horrible about how this protocol selection is done, but LWP
289 # leaves me with no choice. Selection is done modally via the
290 # installation of global protocol handlers, in code in LWP::UserAgent
291 # (very near the top). That code I have copied, as it was in version
292 # 2.033 , into _select_http_10(); I have made the obvious derivative
293 # for _select_http_11(). The rest of this code invokes one or other
294 # of these are required before each operation, crosses its fingers and
295 # hopes like hell that it doesn't get called re-entrantly.
296  
297 sub _select_http_10 {
298 require LWP::Protocol::http10;
299 LWP::Protocol::implementor('http', 'LWP::Protocol::http10');
300 eval {
301 require LWP::Protocol::https10;
302 LWP::Protocol::implementor('https', 'LWP::Protocol::https10');
303 };
304 }
305  
306 sub _select_http_11 {
307 require LWP::Protocol::http;
308 LWP::Protocol::implementor('http', 'LWP::Protocol::http');
309 eval {
310 require LWP::Protocol::https;
311 LWP::Protocol::implementor('https', 'LWP::Protocol::https');
312 };
313 }
314  
315  
316 =head2 find_business(), find_service(), find_binding(), find_tModel()
317  
318 $rs = $uddi->find_business(name => 'frog');
319 $rs = $uddi->find_business(name => 'fish',
320 qualifiers => [ qw(sortByNameAsc caseSensitiveMatch) ]);
321 $rs = $uddi->find_service(businessKey => "0123456789abcdef");
322 $rs = $uddi->find_binding(serviceKey => "0123456789abcdef");
323 $rs = $uddi->find_tModel(name => 'uddi');
324  
325 These four similar methods search in the UDDI repository indicated by
326 C<$uddi> for businesses, services, bindings and tModels matching the
327 specified criteria. These criteria consist of key-value pairs, in
328 which the key may be any of the following (though not all keys are
329 valid for all four kinds of search):
330  
331 =over 4
332  
333 =item name
334  
335 The name, or partial name, of the business or businesses to search
336 for. It exactly interpretation is specified by the qualifiers. By
337 default, the name is searched for case-sensitively and for an exact
338 match.
339  
340 =item qualifiers
341  
342 A set of zero or more qualifier tokens which modify the interpretation
343 of C<name>, separated by spaces or commas. The acceptable qualifiers
344 are:
345 C<andAllKeys>,
346 C<approximateMatch>,
347 C<binarySort>,
348 C<bindingSubset>,
349 C<caseInsensitiveSort>,
350 C<caseInsensitiveMatch>,
351 C<caseSensitiveSort>,
352 C<caseSensitiveMatch>,
353 C<combineCategoryBags>,
354 C<diacriticInsensitiveMatch>,
355 C<diacriticSensitiveMatch>,
356 C<exactMatch>,
357 C<signaturePresent>,
358 C<orAllKeys>,
359 C<orLikeKeys>,
360 C<serviceSubset>,
361 C<sortByNameAsc>,
362 C<sortByNameDesc>,
363 C<sortByDateAsc>,
364 C<sortByDateDesc>,
365 C<suppressProjectedServices>
366 and
367 C<UTS-10>.
368 The meanings of these are defined in section 5.1.4.3 of the UDDI
369 specification.
370  
371 =item businessKey
372  
373 The unique key of a business whose services are sought. This may be
374 obtained from the result of an earlier C<find_business()> call using
375 C<$record-E<gt>xpath('@businessKey')>.
376  
377 =item serviceKey
378  
379 The unique key of a service whose bindings are sought. This may be
380 obtained from the result of an earlier C<find_service()> call using
381 C<$record-E<gt>xpath('@serviceKey')>.
382  
383 =item tModelBag
384  
385 A bag of tModels, separated by spaces or commas.
386  
387 =item identifierBag
388  
389 A bag of identifiers, separated by spaces or commas.
390  
391 =item categoryBag
392  
393 A bag of categories, separated by spaces or commas.
394  
395 =back
396  
397 On success, these methods return a C<UDDI::HalfDecent::ResultSet>
398 object which may be further interrogated. On failure, they throw an
399 exception of type C<UDDIException> describing what went wrong.
400  
401 =cut
402  
403 sub find_business {
404 my $this = shift();
405 return $this->_find('find_business', 'uddi:businessList', 'business', @_);
406 }
407  
408  
409 sub find_service {
410 my $this = shift();
411 return $this->_find('find_service', 'uddi:serviceList', 'service', @_);
412 }
413  
414  
415 sub find_binding {
416 my $this = shift();
417 return $this->_find('find_binding', 'uddi:bindingDetail', 'binding', @_);
418 }
419  
420  
421 sub find_tModel {
422 my $this = shift();
423 return $this->_find('find_tModel', 'uddi:tModelList', 'tModel', @_);
424 }
425  
426  
427 sub _find {
428 my $this = shift();
429 my($method, $wrapper, $class, @criteria) = @_;
430  
431 my $elements = "";
432 my %attrs;
433 while (@criteria) {
434 my $key = shift @criteria;
435 my $value = shift @criteria;
436 oops error => "missing value", detail => $key
437 if !defined $value;
438  
439 if ($key eq "businessKey") {
440 $attrs{businessKey} = $value;
441 } elsif ($key eq "serviceKey") {
442 $attrs{serviceKey} = $value;
443 } elsif ($key eq "name") {
444 $elements .= "<name>" . encode_entities($value) . "</name>\n";
445 } elsif ($key eq "qualifiers") {
446 $elements .= $this->_bag("findQualifiers", "findQualifier",
447 $value);
448 } elsif ($key eq "tModelBag") {
449 $elements .= $this->_bag("tModelBag", "tModelKey", $value);
450 } elsif ($key eq "identifierBag") {
451 $elements .= $this->_bag("identifierBag", "keyedReference", $value);
452 } elsif ($key eq "categoryBag") {
453 $elements .= $this->_bag("categoryBag", "keyedReference", $value);
454 } else {
455 oops error => "unknown key", detail => $key
456 }
457 }
458  
459 my $attrs = join('', map { " $_='" . $attrs{$_} . "'" } sort keys %attrs);
460 my $namespace = $this->_uddi_namespace();
461 my $xml = qq[<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
462 <soap:Body>
463 <$method xmlns='$namespace' maxRows="20" generic="2.0"$attrs>
464 ];
465 $elements =~ s/^/ /gm;
466 $xml .= $elements;
467 $xml .= qq[ </$method>
468 </soap:Body>
469 </soap:Envelope>
470 ];
471  
472 my $xpc = $this->_send_and_receive($xml);
473 my($list) = $xpc->findnodes("/env:Envelope/env:Body/$wrapper");
474 oops error => "no result list" if !defined $list;
475  
476 return new UDDI::HalfDecent::ResultSet($this, $xpc, $list, $class);
477 }
478  
479  
480 sub _bag {
481 my $this = shift();
482 my($outer, $inner, $value) = @_;
483  
484 oops error => "non-arrayref $outer", detail => $value
485 if !ref $value || ref $value ne "ARRAY";
486 my $res = "<$outer>\n";
487 foreach my $entry (@$value) {
488 $res .= " <$inner>" . encode_entities($entry) . "</$inner>\n";
489 }
490 $res .= "</$outer>\n";
491 return $res;
492 }
493  
494  
495 sub _send_and_receive {
496 my $this = shift();
497 my($postData) = @_;
498  
499 my $url = $this->{endpoint};
500 my $request;
501 if (defined $postData) {
502 $request = HTTP::Request::Common::POST($url, Content => $postData);
503 } else {
504 $request = HTTP::Request::Common::GET($url);
505 }
506 $request->header('Content-Type' => 'text/xml; charset="utf-8"');
507 $request->header(SOAPAction => '""');
508 $this->_log("requestheaders", $request->headers_as_string());
509 $this->_log("request", $postData);
510  
511 # Choose HTTP protocol variant in accordance with option
512 my $httpver = $this->option("http-version");
513 if ($httpver eq "1.1") {
514 $this->_select_http_11();
515 } elsif ($httpver eq "1.0") {
516 $this->_select_http_10();
517 } else {
518 oops error => "bad http version", detail =>
519 defined $httpver ? $httpver : "[undefined]";
520 }
521  
522 my $response = $this->_ua()->request($request);
523 $this->_log("responseheaders", $response->status_line(), "\n",
524 $response->headers_as_string());
525 my $content = $response->content();
526 $this->_log("response", $content);
527  
528 # We would like to fail if there is an HTTP-level message, but we
529 # get HTTP 500 when there is a SOAP error, which of course
530 # contains more detail that we won't see if we just refer to the
531 # HTTP header. It's not wholly clear what heuristic we should be
532 # using here, but the best we can do is probably to proceed with
533 # parsing if the content of the response is XML.
534  
535 my $ctype = $response->header("Content-type");
536 oops error => "HTTP", detail => $response->message()
537 if (!$response->is_success() &&
538 ($response->code() != 500 ||
539 $ctype !~ /^text\/xml/i ||
540 $content eq ""));
541  
542 oops error => "non-XML", detail => $ctype
543 if $ctype !~ /^text\/xml/i;
544  
545 # So if we got here, we have a good XML response that is either
546 # part of a "successful" response or accompanied a 500 in which
547 # case it's probably a SOAP error.
548 my $doc;
549 eval {
550 $doc = $this->_parser()->parse_string($content);
551 }; if ($@) {
552 oops error => "XML", detail => $@;
553 }
554  
555 my %namespaces = (
556 xsi => 'http://www.w3.org/2001/XMLSchema-instance',
557 enc => 'http://schemas.xmlsoap.org/soap/encoding/',
558 env => 'http://schemas.xmlsoap.org/soap/envelope/',
559 xsd => 'http://www.w3.org/2001/XMLSchema',
560 uddi => $this->_uddi_namespace(),
561 );
562
563 my $xpc = new XML::LibXML::XPathContext($doc->getDocumentElement());
564 foreach my $prefix (keys %namespaces) {
565 $xpc->registerNs($prefix, $namespaces{$prefix});
566 }
567  
568 if (!$response->is_success()) {
569 my($fault) = $xpc->findnodes('/env:Envelope/env:Body/env:Fault');
570 my($code, $string);
571 my($detail) = $xpc->findnodes('env:detail', $fault);
572  
573 # Some naughty servers omit the SOAP envelope namespace from
574 # the detail of their error reports, so we need to allow for
575 # them. For example, while Microsoft's server correctly
576 # namespaces faults pertaining to validation, it does not do
577 # so for errors such as "unsupported find qualifier". Nice
578 # work, Microsoft!
579 #warn "before: fault=$fault, detail=$detail";
580 ($detail) = $xpc->findnodes('detail', $fault) if !defined $detail;
581 #warn "after: fault=$fault, detail=$detail";
582  
583 if (defined $detail) {
584 $code = $xpc->findvalue('//uddi:result/@errno', $detail);
585 $string = $xpc->findvalue('//uddi:errInfo', $detail);
586 }
587  
588 if (!defined $code || $code eq "") {
589 $code = $fault->findvalue('faultcode');
590 $string = $fault->findvalue('faultstring');
591 }
592  
593 $code ||= "UNKNOWN"; # last ditch
594 oops error => $code, detail => $string;
595 }
596  
597 return $xpc;
598 }
599  
600  
601 sub _uddi_namespace {
602 my $this = shift();
603  
604 my $uddiver = $this->option("uddi-version");
605 if ($uddiver eq "3") {
606 return 'urn:uddi-org:api_v3';
607 } elsif ($uddiver eq "2") {
608 return 'urn:uddi-org:api_v2';
609 } else {
610 oops error => "bad uddi version", detail =>
611 defined $uddiver ? $uddiver : "[undefined]";
612 }
613 }
614  
615  
616 =head1 ENVIRONMENT
617  
618 The functioning of this module is affected by several environment
619 variables, all of having names beginning with C<UDDI_>:
620  
621 =over 4
622  
623 =item UDDI_LOG
624  
625 If this is set, then it is a comma- or space-separated list of levels
626 to be be included in the logging output on standard error. See the
627 description of the C<loglevel()> method for details.
628  
629 =item UDDI_TRACE
630  
631 If this is set to a true value, then when uncaught exceptions are
632 displayed, a full stack-trace will be included. That is helpful for
633 debugging, but a bit ugly for production.
634  
635 =back
636  
637 =head1 SEE ALSO
638  
639 C<Exception::Class>
640 provides the exception objects thrown by this package.
641  
642 C<Net::Z3950::UDDI>
643 is the module that uses this, and for which it was written.
644  
645 C<z2uddi> is the gateway program, built on C<Net::Z3950::UDDI>, that
646 is the I<raison d'etre> of this code.
647  
648 C<UDDI::Lite> is supposedly a UDDI library that is part of the
649 C<SOAP::Lite> distribution, although I can't testify to that since I
650 have never seen it actually do any UDDI.
651  
652 =head1 AUTHOR, COPYRIGHT AND LICENSE
653  
654 As for C<Net::Z3950::UDDI>.
655  
656 =cut
657  
658 1;