############################################################################### # # This file copyright (c) 2001 by Randy J. Ray, all rights reserved # # Copying and distribution are permitted under the terms of the Artistic # License as distributed with Perl versions 5.005 and later. See # http://www.opensource.org/licenses/artistic-license.php # ############################################################################### # # $Id: Procedure.pm,v 1.14 2005/05/02 10:03:10 rjray Exp $ # # Description: This class abstracts out all the procedure-related # operations from the RPC::XML::Server class # # Functions: new # name \ # code \ # signature \ These are the accessor functions for the # help / data in the object, though it's visible. # version / # hidden / # clone # is_valid # add_signature # delete_signature # make_sig_table # match_signature # reload # load_XPL_file # # Libraries: XML::Parser (used only on demand in load_XPL_file) # File::Spec # # Global Consts: $VERSION # # Environment: None. # ############################################################################### package RPC::XML::Procedure; use 5.005; use strict; use vars qw($VERSION); use subs qw(new is_valid name code signature help version hidden add_signature delete_signature make_sig_table match_signature reload load_XPL_file); use AutoLoader 'AUTOLOAD'; require File::Spec; $VERSION = do { my @r=(q$Revision: 1.14 $=~/\d+/g); sprintf "%d."."%02d"x$#r,@r }; ############################################################################### # # Sub Name: new # # Description: Create a new object of this class, storing the info on # regular keys (no obfuscation used here). # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $class in scalar Class to bless into # @argz in variable Disposition is variable; see # below # # Returns: Success: object ref # Failure: error string # ############################################################################### sub new { my $class = shift; my @argz = @_; my $data; # This will be a hashref that eventually gets blessed $class = ref($class) || $class; # # There are three things that @argz could be: # if (ref $argz[0]) { # 1. A hashref containing all the relevant keys $data = {}; %$data = %{$argz[0]}; } elsif (@argz == 1) { # 2. Exactly one non-ref element, a file to load # And here is where I cheat in a way that makes even me uncomfortable. # # Loading code from an XPL file, it can actually be of a type other # than how this constructor was called. So what we are going to do is # this: If $class is undef, that can only mean that we were called # with the intent of letting the XPL file dictate the resulting object. # If $class is set, then we'll call load_XPL_file normally, as a # method, to allow for subclasses to tweak things. if (defined $class) { $data = $class->load_XPL_file($argz[0]); return $data unless ref $data; # load_XPL_path signalled an error } else { # Spoofing the "class" argument to load_XPL_file makes me feel # even dirtier... $data = load_XPL_file(\$class, $argz[0]); return $data unless ref $data; # load_XPL_path signalled an error $class = "RPC::XML::$class"; } } else { # 3. If there is more than one arg, it's a sort-of-hash. That is, the # key 'signature' is allowed to repeat. my ($key, $val); $data = {}; $data->{signature} = []; while (@argz) { ($key, $val) = splice(@argz, 0, 2); if ($key eq 'signature') { # Since there may be more than one signature, we allow it to # repeat. Of course, that's also why we can't just take @argz # directly as a hash. *shrug* push(@{$data->{signature}}, ref($val) ? join(' ', @$val) : $val); } elsif (exists $data->{$key}) { return "${class}::new: Key '$key' may not be repeated"; } else { $data->{$key} = $val; } } } return "${class}::new: Missing required data" unless (exists $data->{signature} and (ref($data->{signature}) eq 'ARRAY') and scalar(@{$data->{signature}}) and $data->{name} and $data->{code}); bless $data, $class; # This needs to happen post-bless in case of error (for error messages) $data->make_sig_table; } ############################################################################### # # Sub Name: make_sig_table # # Description: Create a hash table of the signatures that maps to the # corresponding return type for that particular invocation. # Makes looking up call patterns much easier. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # # Returns: Success: $self # Failure: error message # ############################################################################### sub make_sig_table { my $self = shift; my ($sig, $return, $rest); delete $self->{sig_table}; for $sig (@{$self->{signature}}) { ($return, $rest) = split(/ /, $sig, 2); $rest = '' unless $rest; # If the key $rest already exists, then this is a collision return ref($self) . '::make_sig_table: Cannot have two different ' . "return values for one set of params ($return vs. " . "$self->{sig_table}->{$rest})" if $self->{sig_table}->{$rest}; $self->{sig_table}->{$rest} = $return; } $self; } # # These are basic accessor/setting functions for the various attributes # sub name { $_[0]->{name}; } # "name" cannot be changed at this level sub help { $_[1] and $_[0]->{help} = $_[1]; $_[0]->{help}; } sub version { $_[1] and $_[0]->{version} = $_[1]; $_[0]->{version}; } sub hidden { $_[1] and $_[0]->{hidden} = $_[1]; $_[0]->{hidden}; } sub code { ref $_[1] eq 'CODE' and $_[0]->{code} = $_[1]; $_[0]->{code}; } sub signature { if ($_[1] and ref $_[1] eq 'ARRAY') { my $old = $_[0]->{signature}; $_[0]->{signature} = $_[1]; unless (ref($_[0]->make_sig_table)) { # If it failed to re-init the table, restore the old list (and old # table). We don't have to check this return, since it had worked $_[0]->{signature} = $old; $_[0]->make_sig_table; } } # Return a copy of the array, not the original [ @{$_[0]->{signature}} ]; } package RPC::XML::Method; use strict; @RPC::XML::Method::ISA = qw(RPC::XML::Procedure); package RPC::XML::Procedure; 1; =head1 NAME RPC::XML::Procedure - Object encapsulation of server-side RPC procedures =head1 SYNOPSIS require RPC::XML::Procedure; ... $method_1 = RPC::XML::Procedure->new({ name => 'system.identity', code => sub { ... }, signature => [ 'string' ] }); $method_2 = RPC::XML::Procedure->new('/path/to/status.xpl'); =head1 IMPORTANT NOTE This package is comprised of the code that was formerly B. The package was renamed when the decision was made to support procedures and methods as functionally different entities. It is not necessary to include both this module and B -- this module provides the latter as an empty subclass. In time, B will be removed from the distribution entirely. =head1 DESCRIPTION The B package is designed primarily for behind-the-scenes use by the B class and any subclasses of it. It is documented here in case a project chooses to sub-class it for their purposes (which would require setting the C attribute when creating server objects, see L). This package grew out of the increasing need to abstract the operations that related to the methods a given server instance was providing. Previously, methods were passed around simply as hash references. It was a small step then to move them into a package and allow for operations directly on the objects themselves. In the spirit of the original hashes, all the key data is kept in clear, intuitive hash keys (rather than obfuscated as the other classes do). Thus it is important to be clear on the interface here before sub-classing this package. =head1 USAGE The following methods are provided by this class: =over 4 =item new(FILE|HASHREF|LIST) Creates a new object of the class, and returns a reference to it. The arguments to the constructor are variable in nature, depending on the type: =over 8 =item FILE If there is exactly on argument that is not a reference, it is assumed to be a filename from which the method is to be loaded. This is presumed to be in the B format descibed below (see L). If the file cannot be opened, or if once opened cannot be parsed, an error is raised. =item HASHREF If there is exactly one argument that is a reference, it is assumed to be a hash with the relevant information on the same keys as the object itself uses. This is primarily to support backwards-compatibility to code written when methods were implemented simply as hash references. =item LIST If there is more than one argument in the list, then the list is assumed to be a sort of "ersatz" hash construct, in that one of the keys (C) is allowed to occur multiple times. Otherwise, each of the following is allowed, but may only occur once: =over 12 =item name The name of the method, as it will be presented to clients =item code A reference to a subroutine, or an anonymous subroutine, that will receive calls for the method =item signature (May appear more than once) Provides one calling-signature for the method, as either a space-separated string of types or a list-reference =item help The help-text for a method, which is generally used as a part of the introspection interface for a server =item version The version number/string for the method =item hidden A boolean (true or false) value indicating whether the method should be hidden from introspection and similar listings =back Note that all of these correspond to the values that can be changed via the accessor methods detailed later. =back If any error occurs during object creation, an error message is returned in lieu of the object reference. =item clone Create a copy of the calling object, and return the new reference. All elements are copied over cleanly, except for the code reference stored on the C hash key. The clone will point to the same code reference as the original. Elements such as C are copied, so that changes to the clone will not impact the original. =item name Returns the name by which the server is advertising the method. Unlike the next few accessors, this cannot be changed on an object. In order to streamline the managment of methods within the server classes, this must persist. However, the other elements may be used in the creation of a new object, which may then be added to the server, if the name absolutely must change. =item code([NEW]) Returns or sets the code-reference that will receive calls as marshalled by the server. The existing value is lost, so if it must be preserved, then it should be retrieved prior to the new value being set. =item signature([NEW]) Return a list reference containing the signatures, or set it. Each element of the list is a string of space-separated types (the first of which is the return type the method produces in that calling context). If this is being used to set the signature, then an array reference must be passed that contains one or more strings of this nature. Nested list references are not allowed at this level. If the new signatures would cause a conflict (a case in which the same set of input types are specified for different output types), the old set is silently restored. =item help([NEW]) Returns or sets the help-text for the method. As with B, the previous value is lost. =item hidden([NEW]) Returns or sets the hidden status of the method. Setting it loses the previous value. =item version([NEW]) Returns or sets the version string for the method (overwriting as with the other accessors). =item is_valid Returns a true/false value as to whether the object currently has enough content to be a valid method for a server to publish. This entails having at the very least a name, one or more signatures, and a code-reference to route the calls to. A server created from the classes in this software suite will not accept a method that is not valid. =item add_signature(LIST) Add one or more signatures (which may be a list reference or a string) to the internal tables for this method. Duplicate signatures are ignored. If the new signature would cause a conflict (a case in which the same set of input types are specified for different output types), the old set is restored and an error message is returned. =item delete_signature(LIST) Deletes the signature or signatures (list reference or string) from the internal tables. Quietly ignores any signature that does not exist. If the new signature would cause a conflict (a case in which the same set of input types are specified for different output types), the old set is restored and an error message is returned. =item match_signature(SIGNATURE) Check that the passed-in signature is known to the method, and if so returns the type that the method should be returning as a result of the call. Returns a zero (0) otherwise. This differs from other signature operations in that the passed-in signature (which may be a list-reference or a string) B>. This method is provided so that servers may check a list of arguments against type when marshalling an incoming call. For example, a signature of C<'int int'> would be tested for by calling C<$M-Ematch_signature('int')> and expecting the return value to be C. =item call(SERVER, PARAMLIST) Execute the code that this object encapsulates, using the list of parameters passed in PARAMLIST. The SERVER argument should be an object derived from the B class. For some types of procedure objects, this becomes the first argument of the parameter list to simulate a method call as if it were on the server object itself. The return value should be a data object (possibly a B), but may not always be pre-encoded. Errors trapped in C<$@> are converted to fault objects. This method is generally used in the C method of the server class, where the return value is subsequently wrapped within a B object. =item reload Instruct the object to reload itself from the file it originally was loaded from, assuming that it was loaded from a file to begin with. Returns an error if the method was not originally loaded from a file, or if an error occurs during the reloading operation. =back =head2 Additional Hash Data In addition to the attributes managed by the accessors documented earlier, the following hash keys are also available for use. These are also not strongly protected, and the same care should be taken before altering any of them: =over 4 =item file When the method was loaded from a file, this key contains the path to the file used. =item mtime When the method was loaded from a file, this key contains the modification-time of the file, as a UNIX-style C