File: LibXML.pm

package info (click to toggle)
libxml-rpc-fast-perl 0.8-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 336 kB
  • sloc: perl: 3,246; makefile: 2
file content (575 lines) | stat: -rw-r--r-- 15,047 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package XML::RPC::Enc::LibXML;

use strict;
use warnings;
use base 'XML::RPC::Enc';
use XML::LibXML;
use XML::Hash::LX;
use Carp;
#use Encode ();

use XML::RPC::Fast ();
our $VERSION = $XML::RPC::Fast::VERSION;
BEGIN {
	if (eval { my $x = pack 'q', -1; 1 }) {
		*_HAVE_BIGINT = sub () { 1 };
		my $maxint = eval q{ 0+"9223372036854775807" };
		*_MAX_BIGINT = sub () { $maxint };
	} else {
		require Math::BigInt;
		*_HAVE_BIGINT = sub () { 0 };
		my $maxint = Math::BigInt->new("0x7fffffffffffffff");
		*_MAX_BIGINT  = sub () { $maxint };
	}
}


=head1 NAME

XML::RPC::Enc::LibXML - Encode/decode XML-RPC using LibXML

=head1 SYNOPSIS

    use XML::RPC::Fast;
    use XML::RPC::Enc::LibXML;
    
    my $rpc = XML::RPC::Fast->new(
        $uri,
        encoder => XML::RPC::Enc::LibXML->new(
            # internal_encoding currently not implemented, always want wide chars
            internal_encoding => undef,
            external_encoding => 'windows-1251',
        )
    );

    $rpc->registerType( base64 => sub {
        my $node = shift;
        return MIME::Base64::decode($node->textContent);
    });

    $rpc->registerType( 'dateTime.iso8601' => sub {
        my $node = shift;
        return DateTime::Format::ISO8601->parse_datetime($node->textContent);
    });

    $rpc->registerClass( DateTime => sub {
        return ( 'dateTime.iso8601' => $_[0]->strftime('%Y%m%dT%H%M%S.%3N%z') );
    });

    $rpc->registerClass( DateTime => sub {
        my $node = XML::LibXML::Element->new('dateTime.iso8601');
        $node->appendText($_[0]->strftime('%Y%m%dT%H%M%S.%3N%z'));
        return $node;
    });

=head1 DESCRIPTION

Default encoder/decoder for L<XML::RPC::Fast>

If MIME::Base64 is installed, decoder for C<XML-RPC> type C<base64> will be setup

If DateTime::Format::ISO8601 is installed, decoder for C<XML-RPC> type C<dateTime.iso8601> will be setup

Also will be setup by default encoders for L<Class::Date> and L<DateTime> (will be encoded as C<dateTime.iso8601>)

Ty avoid default decoders setup:

    BEGIN {
        $XML::RPC::Enc::LibXML::TYPES{base64} = 0;
        $XML::RPC::Enc::LibXML::TYPES{'dateTime.iso8601'} = 0;
    }
    use XML::RPC::Enc::LibXML;

=head1 IMPLEMENTED METHODS

=head2 new

=head2 request

=head2 response

=head2 fault

=head2 decode

=head2 registerType

=head2 registerClass

=head1 SEE ALSO

=over 4

=item * L<XML::RPC::Enc>

Base class (also contains documentation)

=back

=cut

# xml => perl
# args: xml-nodes (children of <value><$type> ... </$type></value>)
# retv: any scalar
our %TYPES;

# perl => xml
# args: object
# retv: ( type => string ) || xml-node
our %CLASS;

our $E;

BEGIN {
	if ( !exists $TYPES{base64} and eval{ require MIME::Base64;1 } ) {
		$TYPES{base64} = sub {
			#defined $E ? $E->encode(
			MIME::Base64::decode(shift->textContent);
		};
	}
	# DateTime is the most "standart" datetime object in perl, try to use it
	if ( !exists $TYPES{'dateTime.iso8601'} and eval{ require DateTime::Format::ISO8601;1 } ) {
		$TYPES{'dateTime.iso8601'} = sub {
			DateTime::Format::ISO8601->parse_datetime(shift->textContent)
		};
	}
}

#%TYPES = (
#	custom => sub { ... },
#	%TYPES,
#);

# We need no modules to predefine encoders for dates
%CLASS = (
	DateTime => sub {
		'dateTime.iso8601',$_[0]->strftime('%Y%m%dT%H%M%S.%3N%z');
	},
	'Class::Date' => sub {
		'dateTime.iso8601',$_[0]->strftime('%Y%m%dT%H%M%S').sprintf( '%+03d%02d', $_[0]->tzoffset / 3600, ( $_[0]->tzoffset % 3600 ) / 60  );
	},
	%CLASS,
);

sub new {
	my $pkg = shift;
	my $self = bless {
		@_,
		parser => XML::LibXML->new(),
		types  => { },
		class  => { },
		#internal_encoding => undef,
	}, $pkg;
	$self->{external_encoding} = 'utf-8' unless defined $self->{external_encoding};
	return $self;
}


sub registerType {
	my ( $self,$type,$decode ) = @_;
	my $old;
	if (ref $self) {
		$old = $self->{types}{$type};
		$self->{types}{$type} = $decode;
	} else {
		$old = $TYPES{$type};
		$TYPES{$type} = $decode;
	}
	$old;
}

sub registerClass {
	my ( $self,$class,$encode ) = @_;
	my $old;
	if (ref $self) {
		$old = $self->{class}{$class};
		$self->{class}{$class} = $encode;
	} else {
		$old = $CLASS{$class};
		$CLASS{$class} = $encode;
	}
	$old;
}

# Encoder part

sub _unparse_param {
	my $p = shift;
	my $r = XML::LibXML::Element->new('value');

	if ( ref($p) eq 'HASH' ) {
		# struct -> ( member -> { name, value } )*
		my $s = XML::LibXML::Element->new('struct');
		$r->appendChild($s);
		for ( keys %$p ) {
			my $m = XML::LibXML::Element->new('member');
			my $n = XML::LibXML::Element->new('name');
			$n->appendText(defined $E ? $E->decode($_) : $_);
			$m->appendChild($n);
			$m->appendChild(_unparse_param($p->{$_}));
			$s->appendChild($m);
		}
	}
	elsif ( ref($p) eq 'ARRAY' ) {
		my $a = XML::LibXML::Element->new('array');
		my $d = XML::LibXML::Element->new('data');
		$a->appendChild($d);
		$r->appendChild($a);
		for (@$p) {
			$d->appendChild( _unparse_param($_) )
		}
	}
	elsif ( ref($p) eq 'CODE' ) {
		$r->appendChild(hash2xml($p->(), doc => 1)->documentElement);
	}
	elsif (ref $p) {
		if (exists $CLASS{ ref $p }) {
			my ($t,$x) = $CLASS{ ref $p }->($p);
			if (ref $t and eval{ $t->isa('XML::LibXML::Node') }) {
				$r->appendChild($t);
			} else {
				my $v = XML::LibXML::Element->new($t);
				$v->appendText(defined $E ? $E->decode($x) : $x);
				$r->appendChild($v);
			}
		}
		elsif ( UNIVERSAL::isa($p,'SCALAR') ) {
			my $v = XML::LibXML::Element->new(ref $p);
			$v->appendText(defined $E ? $E->decode($$p) : $$p) if defined $$p;
			$r->appendChild($v);
		}
		elsif ( UNIVERSAL::isa($p,'REF') ) {
			my $v = XML::LibXML::Element->new(ref $p);
			$v->appendChild(hash2xml($$p, doc => 1)->documentElement);
			$r->appendChild($v);
		}
		else {
			warn "Bad reference: $p";
			#$result = undef;
		}
	}
	else {
		#no warnings;
		if (!defined $p) {
			my $v = XML::LibXML::Element->new('string');
			$r->appendChild($v);
		}

=for rem

Q: What is the legal syntax (and range) for integers?
   How to deal with leading zeros?
   Is a leading plus sign allowed?
   How to deal with whitespace?

A: An integer is a 32-bit signed number.
   You can include a plus or minus at the beginning of a string of numeric characters.
   Leading zeros are collapsed.
   Whitespace is not permitted.
   Just numeric characters preceded by a plus or minus.

Q: What is the legal syntax (and range) for floating point values (doubles)?
   How is the exponent represented?
   How to deal with whitespace?
   Can infinity and "not a number" be represented?

A: There is no representation for infinity or negative infinity or "not a number".
   At this time, only decimal point notation is allowed, a plus or a minus,
   followed by any number of numeric characters,
   followed by a period and any number of numeric characters.
   Whitespace is not allowed.
   The range of allowable values is implementation-dependent, is not specified.

		# int
		'+0' => 0
		'-0' => 0
		'+1234567' => 1234567
		'0777' => 777
		'0000000000000' => 0
		'0000000000000000000000000000000000000000000000000' => 0
		# not int
		'999999999999999999999999999999999999';

=cut
		elsif ($p =~ m/^([\-+]?)\d+(\.\d+|)$/) {
			my ($have_sign,$is_double) = ($1,$2);
			if ( $is_double ) {
				my $v = XML::LibXML::Element->new('double');
				$v->appendText( $p );
				$r->appendChild($v);
			}
			else {
				my $v;
				# TODO: should we pass sign "+"?
				if( $p == unpack "l", pack "l", $p ) {
					# i4
					$v = XML::LibXML::Element->new('i4');
					$v->appendText(int $p);
				}
				elsif ( _HAVE_BIGINT and $p == unpack "q", pack "q", $p ) {
					# i8
					$v = XML::LibXML::Element->new('i8');
					$v->appendText(int $p);
				}
				elsif ( !_HAVE_BIGINT and abs( my $bi = Math::BigInt->new($p) ) < _MAX_BIGINT ) {
					$v = XML::LibXML::Element->new('i8');
					$v->appendText($bi->bstr);
				}
				else {
					# string
					$v = XML::LibXML::Element->new('string');
					$v->appendText($p);
				}
				$r->appendChild($v);
			}
		}
		else {
			my $v = XML::LibXML::Element->new('string');
			$v->appendText(defined $E ? $E->decode($p) : $p);
			$r->appendChild($v);
		}
	}
	return $r;
}

sub request {
	my $self = shift;
	local @CLASS{keys %{ $self->{class} }} = values %{ $self->{class} };
	local $E = Encode::find_encoding($self->{internal_encoding})
		or croak "Could not find encoding $self->{internal_encoding}"
		if defined $self->{internal_encoding};
	my $method = shift;
	my $doc = XML::LibXML::Document->new('1.0',$self->{external_encoding});
	my $root = XML::LibXML::Element->new('methodCall');
	$doc->setDocumentElement($root);
	my $n = XML::LibXML::Element->new('methodName');
	$n->appendText(defined $E ? $E->decode($method) : $method);
	$root->appendChild($n);
	my $prms = XML::LibXML::Element->new('params');
	$root->appendChild($prms);
	for my $v (@_) {
		my $p = XML::LibXML::Element->new('param');
		$p->appendChild( _unparse_param($v) );
		$prms->appendChild($p);
	}
	my $x = $doc->toString;
	utf8::encode($x) if utf8::is_utf8($x);
	return $x;
}

sub response {
	my $self = shift;
	local @CLASS{keys %{ $self->{class} }} = values %{ $self->{class} };
	local $E = Encode::find_encoding($self->{internal_encoding})
		or croak "Could not find encoding $self->{internal_encoding}"
		if defined $self->{internal_encoding};
	my $doc = XML::LibXML::Document->new('1.0',$self->{external_encoding});
	my $root = XML::LibXML::Element->new('methodResponse');
	$doc->setDocumentElement($root);
	my $prms = XML::LibXML::Element->new('params');
	$root->appendChild($prms);
	for my $v (@_) {
		my $p = XML::LibXML::Element->new('param');
		$p->appendChild( _unparse_param($v) );
		$prms->appendChild($p);
	}
	my $x = $doc->toString;
	utf8::encode($x) if utf8::is_utf8($x);
	return $x;
}

sub fault {
	my $self = shift;
	local @CLASS{keys %{ $self->{class} }} = values %{ $self->{class} };
	local $E = Encode::find_encoding($self->{internal_encoding})
		or croak "Could not find encoding $self->{internal_encoding}"
		if defined $self->{internal_encoding};
	my ($code,$err) = @_;
	my $doc = XML::LibXML::Document->new('1.0',$self->{external_encoding});
	my $root = XML::LibXML::Element->new('methodResponse');
	$doc->setDocumentElement($root);
	my $f = XML::LibXML::Element->new('fault');
	my $v = XML::LibXML::Element->new('value');
	my $s = XML::LibXML::Element->new('struct');
	for (qw(faultCode faultString)){
		my $m = XML::LibXML::Element->new('member');
		my $n = XML::LibXML::Element->new('name');
		$n->appendText(defined $E ? $E->decode($_) : $_);
		$m->appendChild($n);
		$m->appendChild(_unparse_param(shift));
		$s->appendChild($m);
	}
	$v->appendChild($s);
	$f->appendChild($v);
	$root->appendChild($f);
	my $x = $doc->toString;
	utf8::encode($x) if utf8::is_utf8($x);
	return $x;
}

# Decoder part
our $src;
sub decode {
	my $self = shift;
	my $string = shift;
	#utf8::encode $string if utf8::is_utf8($string);
	local $src = $string;
	$self->_parse( $self->{parser}->parse_string($string) )
}

sub _parse_param {
	my $v = shift;
	for my $t ($v->childNodes) {
		next if ref $t eq 'XML::LibXML::Text';
		my $type = $t->nodeName;
		#print $t->nodeName,"\n";
		if ($type eq 'string') {
			return defined $E ? $E->encode(''.$t->textContent) : ''.$t->textContent;
		}
		elsif ($type eq 'i4' or $type eq 'int') {
			return int $t->textContent;
		}
		elsif ($type eq 'double') {
			return 0+$t->textContent;
		}
		elsif ($type eq 'bool') {
			$v = $t->textContent;
			return $v eq 'false' ? 0 : !!$v ? 1 : 0;
		}
		elsif ($type eq 'struct') {
			my $r = {};
			for my $m ($t->childNodes) {
				my ($mn,$mv);
				if ($m->nodeName eq 'member') {
					for my $x ($m->childNodes) {
						#print "\tmember:".$x->nodeName,"\n";
						if ($x->nodeName eq 'name') {
							$mn = $x->textContent;
							#last;
						}
						elsif ($x->nodeName eq 'value') {
							$mv = _parse_param ($x);
							$mn and last;
						}
					}
					if (defined $E) {
						$mn = $E->encode($mn);
						$mv = $E->encode($mv);
					}
					$r->{$mn} = $mv;
				}
			}
			return $r;
		}
		elsif ($type eq 'array') {
			my $r = [];
			for my $d ($t->childNodes) {
				#print "\tdata:".$d->nodeName,"\n";
				unless (defined $d) {
					warn "!!! Internal bug: childNodes return undef. XML=\n$src";
					next;
				}
				if ($d->nodeName eq 'data') {
					for my $x ($d->childNodes) {
						#print "\tdata:".$x->nodeName,"\n";
						if ($x->nodeName eq 'value') {
							push @$r, _parse_param ($x);
						}
					}
				}
			}
			return $r;
		}
#		elsif ($type eq 'base64') {
#			return decode_base64($t->textContent);
#		}
#		elsif ($type eq 'dateTime.iso8601') {
#			return $t->textContent;
#		}
		else {
			if (exists $TYPES{$type} and $TYPES{$type}) {
				return $TYPES{$type}( $t->childNodes );
			} else {
				my @children = $t->childNodes;
				@children or return bless( \do{ my $o }, $type );
				if (( @children > 1 ) xor ( ref $children[0] ne 'XML::LibXML::Text' )) {
					#print STDERR + (0+@children)."; $type => ",ref $children[0], ' ', $children[0]->nodeName, "\n";
					return bless \(xml2hash($t)->{$type}),$type;
				} else {
					#print STDERR + "*** ".(0+@children)."; $type => ",ref $children[0], ' ', $children[0]->nodeName, "\n";
					return bless \(
						defined $E ? $E->encode($children[0]->textContent) : $children[0]->textContent
					),$type;
				}
			}
		}
		last;
	}
	return defined $E ? $E->encode($v->textContent) : $v->textContent
}

sub _parse {
	my $self = shift;
	my $doc = shift;
	my @r;
	my $root = $doc->documentElement;
	local @TYPES{keys %{ $self->{types} }} = values %{ $self->{types} };
	local $E = Encode::find_encoding($self->{internal_encoding})
		or croak "Could not find encoding $self->{internal_encoding}"
		if defined $self->{internal_encoding};
	for my $p ($doc->findnodes('//param')) {
	#for my $ps ($root->childNodes) {
	#	if ($ps->nodeName eq 'params') {
	#		for my $p ($ps->childNodes) {
	#			if ($p->nodeName eq 'param') {
					#print $p->nodeName,"\n";
					for my $v ($p->childNodes) {
						if ($v->nodeName eq 'value') {
							#print $p->nodeName,'=',_parse_param($v),"\n";
							push @r, _parse_param ($v);
						}
					}
	#			}
	#		}
	#	}
	}
	for my $m ($doc->findnodes('//methodName')) {
		unshift @r, defined $E ? $E->encode($m->textContent) : $m->textContent;
		last;
	}
	unless(@r) {
	for my $f ($doc->findnodes('//fault')) {
		my ($c,$e);
		
		for ($f->childNodes) {
			if ( $_->nodeName eq 'value' ) {
				my $flt  = _parse_param ( $_ );
				$c = $flt->{faultCode};
				$e = $flt->{faultString};
				last;
			} else {
				$c = defined $E ? $E->encode($_->textContent) : $_->textContent if $_->nodeName eq 'faultCode';
				$e = defined $E ? $E->encode($_->textContent) : $_->textContent if $_->nodeName eq 'faultString';
			}
		}
		return { fault => { faultCode => $c, faultString => $e } };
	}
	}
	#warn "@r";
	return @r;
}

=head1 COPYRIGHT & LICENSE

Copyright (c) 2008-2009 Mons Anderson.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=head1 AUTHOR

Mons Anderson, C<< <mons@cpan.org> >>

=cut

1;