NodeFactory.pm untested

filter: Statementstmt 0.0% 0 / 129 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 229 CC 19 SCAR 24.0
CC
19
Cov
0%
getTag
42.0
new
12.0
attr
12.0
CRAP 11.1
1 package Jabber::NodeFactory;
2  
3 # $Id: NodeFactory.pm,v 1.3 2002/02/22 20:02:58 dj Exp $
4  
5 use XML::Parser;
6  
7 =head1 NAME
8  
9 Jabber::NodeFactory - Simple XML Node Factory for Jabber
10  
11 =head1 SYNOPSIS
12  
13 my $nf = new Jabber::NodeFactory(fromstr => 1);
14 print $nf->newNode('presence')->toStr;
15  
16 -> <presence/>
17  
18 my $tag1 = $nf->newNode('iq');
19 $tag1->attr('type', 'get');
20 my $query = $tag1->insertTag('query', 'jabber:iq:auth');
21 $query->insertTag('username')->data('qmacro');
22 print $tag1->toStr;
23  
24 -> <iq type='get'><query xmlns='jabber:iq:auth'>
25 <username>qmacro</username></query></iq>
26  
27 my $tag2 = $nf->newNodeFromStr("<message><body>hi</body></message>");
28 $tag2->attr('to','qmacro@jabber.org');
29 my $msg = $tag2->getTag('body')->data;
30 print $tag2->toStr, "\n";
31 print $msg;
32  
33 -> <message to='qmacro@jabber.org'><body>hi</body></message>
34 -> hi
35  
36 =head1 DESCRIPTION
37  
38 Jabber::NodeFactory is a library for creating and
39 manipulating XML nodes. It was created to offer similar functions
40 to the xmlnode library in the Jabber server implementation.
41  
42 It provides enough functions to create and manipulate XML fragments
43 (nodes) in the Jabber XML stream world. The functions are low level,
44 RISC-style :-)
45  
46 =head1 ORGANISATION
47  
48 There are two packages - Jabber::NodeFactory and Jabber::NodeFactory::Node.
49 The former is a wrapper which offers two node construction methods;
50 the latter is the package that represents the actual node objects
51 that are created and manipulated.
52  
53 Use Jabber::NodeFactory to contruct new nodes (which will be
54 Jabber::NodeFactory::Node objects) and
55 Jabber::NodeFactory::Node to manipulate those nodes.
56  
57 The Connection package will present stream fragments received in
58 the form of Jabber::NodeFactory::Node objects; use
59 Jabber::NodeFactory::Node to parse and manipulate these fragments.
60  
61 =head1 METHODS in Jabber::NodeFactory
62  
63 =over 4
64  
65 =item new()
66  
67 The Jabber::NodeFactory constructor. Call this to create a
68 new Jabber::NodeFactory, with which you can build nodes.
69  
70 You can create nodes in one of two ways - building them up starting
71 from the tagname (C<newNode()>), or creating them from a string
72 (C<newNodeFromStr()>). If you want to be
73 able to do the latter, you need to specify the flag
74  
75 fromstr => 1
76  
77 like this
78  
79 my $nf = new Jabber::NodeFactory(fromstr => 1)
80  
81 Creating nodes from strings requires the strings to be parsed; an
82 XML parser is only created as part of the Jabber::NodeFactory object being
83 constructed if you set this flag. If you don't set the flag and
84 subsequently try to call C<newNodeFromStr()>, you'll get an error.
85  
86 =cut
87  
88 sub new {
89  
90 # debug => 1
91 # fromstr => 1
92  
93 my ($class, %args) = @_;
94 my $self = {};
95 if ($args{fromstr}) {
96 $self->{parser} = new XML::Parser
97 (
98 Handlers => {
99 Start => sub { $self->_startTag(@_) },
100 End => sub { $self->_endTag(@_) },
101 Char => sub { $self->_charData(@_) },
102 }
103 );
104 $self->{nodedepth} = 0;
105 }
106  
107 $self->{debug} = 1 if $args{debug};
108  
109 return bless $self, $class;
110  
111 }
112  
113  
114 sub _debug {
115  
116 my $self = shift;
117 my $string = shift;
118 print STDERR $string,"\n" if $self->{debug};
119  
120 }
121  
122  
123 =item newNode()
124  
125 Call this to create a new node. This will return a new
126 Jabber::NodeFactory::Node object. There is one mandatory argument to
127 this call - the name of the tag for the node being created.
128  
129 my $node = $nf->newNode('tag');
130  
131 will create a node that looks like this:
132  
133 <tag/>
134  
135 If you want to create a node like this, by specifying a tag name,
136 you can also use the C<new> method in Jabber::NodeFactory::Node to achieve
137 the same thing; the C<newNode> method has been made available here just to
138 have some consistency with C<newNodeFromStr>.
139  
140 =cut
141  
142 sub newNode {
143  
144 my $self = shift;
145 my $name = shift;
146 my $xmlns = shift;
147  
148 return Jabber::NodeFactory::Node->new($name, $xmlns);
149
150 }
151  
152  
153 =item newNodeFromStr()
154  
155 Like C<newNode>, this also returns a new Jabber::NodeFactory::Node object.
156 The single argument to be passed is a string. The NodeFactory will
157 use an XML parser to parse this string and create a node or hierarchy
158 of nodes.
159  
160 my $node =
161 $nf->newNodeFromStr(qq[<test><child attr1='a'/></test>]);
162  
163 will create a node object that represents the <test> node having a
164 child node as shown.
165  
166 =cut
167  
168 sub newNodeFromStr {
169  
170 my $self = shift;
171 my $string = shift;
172  
173 unless ($self->{parser}) {
174 die "Cannot create node from string - create nodefactory with fromstr => 1\n";
175 }
176  
177 $self->{node} = undef;
178 $self->{parser}->parse($string);
179 return $self->{node};
180  
181 }
182  
183  
184 sub _startTag {
185  
186 my ($self, $expat, $tag, %attr) = @_;
187 $self->_debug("START: $tag");
188 $self->{depth} += 1;
189 if ($self->{depth} == 1) {
190 $self->{node} = Jabber::NodeFactory::Node->new($tag);
191 $self->{node}->attr($_, $attr{$_}) foreach keys %attr;
192 $self->{currnode} = $self->{node};
193 }
194 else {
195 my $kid = $self->{currnode}->insertTag($tag);
196 $kid->attr($_, $attr{$_}) foreach keys %attr;
197 $self->{currnode} = $kid;
198 }
199  
200 }
201  
202 sub _endTag {
203  
204 my ($self, $expat, $tag) = @_;
205 $self->_debug("END : $tag");
206 $self->{depth} -= 1;
207 # $self->{currnode} = $self->{node}->parent();
208 $self->{currnode} = $self->{currnode}->parent();
209  
210 }
211  
212 sub _charData {
213  
214 my ($self, $expat, $data) = @_;
215 $self->_debug("DATA : $data");
216 $self->{currnode}->data($self->{currnode}->data().$data);
217  
218 }
219  
220 =back
221  
222 =cut
223  
224 ############################################################################
225  
226 package Jabber::NodeFactory::Node;
227  
228 =head1 METHODS in Jabber::NodeFactory::Node
229  
230 =over 4
231  
232 =item new()
233  
234 Construct a new node. Returns a Jabber::NodeFactory::Node object. You must
235 specify a tag name for the node.
236  
237 Example:
238  
239 my $tag1 = new Jabber::NodeFactory::Node('tag1');
240  
241 $tag1 represents a node that looks like this:
242  
243 <tag1/>
244  
245 =cut
246  
247 use Scalar::Util qw(weaken);
248  
249 sub new {
250  
251 my ($class, $name, $xmlns, $parent) = @_;
252  
253 my $node = {
254 name => $name,
255 attrs => {},
256 data => '',
257 kids => [],
258 parent => $parent,
259 };
260  
261 weaken($node->{parent}); # XXX
262 bless $node => $class;
263 $node->attr('xmlns' => $xmlns) if $xmlns;
264 return $node;
265  
266 }
267  
268  
269 =item name()
270  
271 Returns the name (the tag name) of the node, in the form of a string.
272  
273 =cut
274  
275 sub name {
276 my $self = shift;
277 return $self->{name};
278 }
279  
280  
281 =item parent()
282  
283 Returns the node's parent. This will be a node object or undef (if
284 it doesn't have a parent).
285  
286 =cut
287  
288 sub parent {
289 my $self = shift;
290 return $self->{parent};
291 }
292  
293  
294 # sets parent; called from insertTag()
295 sub _setParent {
296 my $self = shift;
297 my $parent = shift;
298 $self->{parent} = $parent;
299 return $self->{parent};
300 }
301  
302  
303 =item attr()
304  
305 Sets or gets a node attribute. Pass one argument - an attribute
306 name - to get the value, or two arguments - the name and a value -
307 to set the value. In both cases the value is returned.
308  
309 Example:
310  
311 $tag1->attr('colour' => 'red');
312 print $tag1->attr('colour');
313  
314 prints
315  
316 red
317  
318 =cut
319  
320 sub attr {
321  
322 my ($self, $attr, $val) = @_;
323  
324 if (defined $val) {
325 if ($val eq '') {
326 delete $self->{attrs}->{$attr};
327 }
328 else {
329 $self->{attrs}->{$attr} = $val;
330 }
331 }
332  
333 return $self->{attrs}->{$attr};
334
335 }
336  
337
338 =item data()
339  
340 Sets or gets a node's data. Pass no arguments to get the data,
341 or one argument - the data - to set the data.
342 In both cases the data is returned.
343  
344 Example:
345  
346 $tag1->data('hello world');
347  
348 results in $tag1 representing
349  
350 <tag1 colour='red'>hello world</tag1>
351  
352 The common character entities will be encoded/decoded on the fly.
353 These are & (&amp;), " (&quot;), ' (&apos;), < (&lt;) and > (&gt;).
354 This means that if you call data() with the string "this & that",
355 what actually will get stored is "this &amp; that". If you receive
356 a string containing "--&gt; this way", calling data() to retrieve
357 it will give you "--> this way".
358  
359 See the rawdata() function for a contrast.
360  
361 =cut
362  
363 sub data {
364  
365 my $self = shift;
366 if (my $data = shift) {
367 $self->{data} = _encode($data);
368 }
369  
370 return _decode($self->{data});
371
372 }
373  
374  
375 sub _encode {
376  
377 my $data = shift;
378  
379 $data =~ s/&/&amp;/g;
380 $data =~ s/</&lt;/g;
381 $data =~ s/>/&gt;/g;
382 $data =~ s/'/&apos;/g;
383 $data =~ s/"/&quot;/g;
384  
385 return $data;
386  
387 }
388  
389
390 sub _decode {
391  
392 my $data = shift;
393  
394 $data =~ s/&amp;/&/g;
395 $data =~ s/&lt;/</g;
396 $data =~ s/&gt;/>/g;
397 $data =~ s/&apos;/'/g;
398 $data =~ s/&quot;/"/g;
399  
400 return $data;
401  
402 }
403  
404
405 =item rawdata()
406  
407 Similar to data(), this function allows you to get and set the data
408 for a node. Unlike data(), there is no encoding or decoding of character
409 entities. It's up to you to make sure you don't break the XML stream by
410 sending a stray "<" or something.
411  
412 =cut
413  
414 sub rawdata {
415  
416 my $self = shift;
417 if (my $data = shift) {
418 $self->{data} = $data;
419 }
420  
421 return $self->{data};
422
423 }
424  
425  
426 =item insertTag()
427  
428 This will insert a tag - with the name given in
429 the first (mandatory) argument - into the node object on which
430 the method call is made.
431  
432 A namespace can be specified in an optional second argument.
433  
434 Example:
435  
436 my $tag2 = new Jabber::NodeFactory::Node('tag2');
437 $tag2->insertTag('a');
438 $tag2->insertTag('b', 'fish:face');
439 $tag2->insertTag('c')->data('hello');
440  
441 results in $tag2 looking like this:
442  
443 <tag2><a/><b xmlns='fish:face'/><c>hello</c></tag2>
444  
445 =cut
446  
447 sub insertTag {
448  
449 my ($self, $tagname, $ns) = @_;
450  
451 # Can pass a Node to insert too
452 my $tag = ref($tagname) eq ref($self)
453 ? $tagname->_setParent($self) && $tagname
454 : new Jabber::NodeFactory::Node($tagname, $ns, $self);
455  
456 push @{$self->{kids}}, $tag;
457  
458 return $tag;
459  
460 }
461  
462  
463 =item toStr()
464  
465 Returns a string representation of the node (and all its children).
466  
467 Example:
468  
469 my $x = new Jabber::NodeFactory::Node('tag');
470 my $y = $x->insertTag('anothertag');
471 $y->attr('number',3);
472  
473 print $x->toStr, "\n";
474 print $y->toStr, "\n";
475  
476 results in:
477  
478 <tag><anothertag number='3'/></tag>
479 <anothertag number='3'/>
480  
481 =cut
482  
483 sub toStr {
484  
485 my $self = shift;
486 my $str = '<'.$self->name();
487 foreach my $attr (keys %{$self->{attrs}}) {
488 $str .= ' '.$attr."='".$self->{attrs}->{$attr}."'";
489 }
490 if ($self->{data} or @{$self->{kids}}) {
491 $str .= '>'.$self->{data};
492 foreach my $kid (@{$self->{kids}}) {
493 $str .= $kid->toStr();
494 }
495 $str .= '</'.$self->name().'>';
496 }
497 else {
498 $str .= '/>';
499 }
500 return $str;
501
502 }
503  
504  
505 =item getTag()
506  
507 Retrieves a child tag and returns it as a node. Specify the name of the
508 tag to retrieve, and an optional namespace attribute (that must be
509 explicitly specified as an xmlns attribute in the child tag you want)
510 to distinguish it from other tags of the same name.
511  
512 If you don't know the tagname but know what namespace you want (common
513 in Jabber), then specify an empty string for the tagname.
514  
515 Example:
516  
517 $node->getTag('x','jabber:x:event');
518  
519 Will return the <x> tag(s) that have xmlns='jabber:x:event'.
520 If you only want the first one, make the call in scalar context:
521  
522 my $event = $node->getTag('x','jabber:x:event');
523  
524 otherwise make it in array context:
525  
526 my @xtags = $node->getTag('x');
527  
528 to get multiple tags (node objects).
529
530  
531 Another example:
532  
533 my $query = $node->getTag('', 'jabber:iq:version');
534  
535 This gets a 'query' node that's qualified by the iq:version namespace.
536  
537 =cut
538  
539 sub getTag {
540  
541 my ($self, $tagname, $ns) = @_;
542  
543 my @tags;
544  
545 foreach my $kid (@{$self->{kids}}) {
546 if (length($tagname)) {
547 next unless $kid->name eq $tagname;
548 }
549 if (defined($ns) and length($ns)) {
550 next unless defined($kid->attr('xmlns')) and $kid->attr('xmlns') eq $ns;
551 }
552 push @tags, $kid;
553 }
554  
555 # Potentially only return the first one
556 return wantarray ? @tags : $tags[0];
557  
558 }
559  
560  
561 =item hide()
562  
563 Use this method to remove a child tag. Use getTag to identify the tag
564 to remove.
565  
566 Example:
567  
568 my $tag = $nf->newNodeFromStr(qq[<a><b fruit='banana'>yellow</b></a>]);
569 $tag->getTag('b')->hide;
570 print $tag->toStr;
571  
572 outputs this:
573  
574 <a/>
575  
576 =cut
577  
578 sub hide {
579  
580 my ($self) = @_;
581 my @newkids;
582 foreach my $kid (@{$self->{parent}->{kids}}) {
583 push(@newkids, $kid) unless $kid eq $self;
584 }
585 $self->{parent}->{kids} = \@newkids;
586  
587 }
588  
589  
590 =item getChildren()
591  
592 This returns a list (array) of the direct child tags of the tag
593 on which the method is called.
594  
595 Example:
596  
597 my $node = $nf->newNodeFromStr(qq[<a><a1/><a2/><a3><a31/></a3></a>]);
598 print $_->name, "\n" foreach $
599  
600 =cut
601  
602 sub getChildren {
603  
604 my ($self) = @_;
605 return @{$self->{kids}};
606  
607 }
608  
609  
610 =back
611  
612 =head1 SEE ALSO
613  
614 Jabber::Connection, Jabber::NS
615  
616 =head1 AUTHOR
617  
618 DJ Adams
619  
620 =head1 VERSION
621  
622 early
623  
624 =head1 COPYRIGHT
625  
626 This module is free software; you can redistribute it and/or modify
627 it under the same terms as Perl itself.
628  
629 =cut
630  
631  
632  
633 1;
634  
635  
636