A.3 RPC::XML


The RPC::XML package is the newest player in the Perl/XML-RPC field. The classes described here cover data encoding, client and server functionality, and features geared specifically towards the Apache/mod_perl environment.

The following is based on Release 0.44 of RPC::XML .

A.3.1 RPC::XML

The actual RPC::XML module itself is an umbrella for all the data-oriented classes that support the client and server classes described here. In general, it isn't necessary to load this package directly because the client and all the server classes do so themselves .

The first group defined include the data classes. These encapsulate Perl data prior to serialization into an XML-RPC message. The data classes are:

RPC::XML::int
RPC::XML::i4
RPC::XML::double
RPC::XML::string
RPC::XML::boolean
RPC::XML::datetime_iso8601
RPC::XML::base64
RPC::XML::array
RPC::XML::struct
RPC::XML::fault

The methods common to all these classes are:

new( value )

Creates a new object that encapsulates the given Perl value. In most cases, the input value is a simple scalar. The main purpose of the data classes is to allow forced-typing of data that doesn't match the automatic typing (such as using the value 10 as a string instead of an integer). However, the following exceptions exist:

  • The RPC::XML::boolean class may take any of the values: yes , true , or 1 for a true value; no , false , or for a false value.

  • If RPC::XML::datetime_iso8601 is passed a value with only digits, it is assumed to be the value from the time built-in function and is converted to an ISO 8601 representation in Universal Coordinated Time.

  • RPC::XML::array may take an array reference or a list of values. Any leading array reference causes the rest of the list to be ignored. The list reference will be expanded when creating the object.

  • The RPC::XML::struct class may take a hash reference as a single argument or a set of key/value pairs. RPC::XML::fault is a subclass of the struct class and may take either an existing RPC::XML::struct object (from which values are copied ), exactly two arguments (the code and string, in that order), or two key/value pairs with the requisite keys of faultCode and faultString .

  • The RPC::XML::base64 class takes the (presumably binary) data chunk as a first argument and an optional second argument. If the second argument evaluates to non-null, it signifies that the chunk of data is already Base64 encoded. Otherwise , it is assumed to be clear text.

value

Returns the value encapsulated within the object. Both the RPC::XML::array and RPC::XML::struct classes accept an optional argument to this method. If that argument is non-null, the values returned are shallow copies. This means that any data objects contained as values (either within the array or as values in the hash) aren't recursively expanded but instead returned as references to the original.

type

Returns the object's type, as defined in the XML-RPC specification. In most classes, this is the same as the last element in the class name . The RPC::XML::datetime_iso8601 class actually returns the string dateTime.iso8601 .

as_string

Generates and returns the XML fragment to represent the object's value within a XML-RPC message.

is_fault

In all classes except RPC::XML::fault , this returns false (0). In the fault class, it returns true (1). This allows simple testing of return values from remote calls for fault status without having to explicitly check the type.

In addition to the previous data classes, there are two message classes provided by this module:

RPC::XML::request
RPC::XML::response

Both support the following methods:

new( parameters )

Creates new objects and returns them. The response class takes only a single argument, the value to be returned to the caller. The request class requires at least one argument. The first parameter is taken to be the name of the remote method to be called. Any additional arguments are encoded as parameters to the call.

as_string

Returns the XML representation of the message as a complete valid XML document.

In addition to these methods, RPC::XML::request supports:

name

Returns the method name that the request is coded to call.

args

Returns the list of arguments to be passed to in the method call as a list reference. If there are no arguments, a reference to an empty list is returned.

The RPC::XML::response class supports:

value

Returns the data object that contains the return value from the response.

is_fault

Returns a true / false value that indicates whether the response contains a fault.

The package exports some convenience functions, if requested . In the following list of functions in the RPC::XML namespace, each indicates which tag an application may use to import the symbol. Symbols may be directly imported, as well.

time2iso8601( optional time, optional time zone )

Takes the time value passed in as seconds (presumably from the built-in time function) and converts it to an ISO 8601 string in UTC. If the second parameter is passed, it is assumed to be an offset in hours from UTC that the value should represent. If no parameters are given, the value from time is used directly. This may be imported with the tag :all , as well as being directly imported.

smart_encode( one or more values )

Takes one or more Perl values and attempts to "smartly" convert them to data objects. This routine is used by the RPC::XML::array and RPC::XML::struct constructors to handle their values. Any passed-in values that are already data objects are returned unchanged. This too may be imported with the :all tag.

RPC_BOOLEAN , RPC_STRING , RPC_I4 , RPC_INT , RPC_DOUBLE , RPC_DATETIME_ISO8601 , RPC_BASE64

These encoding functions may be used as shortcuts rather than explicitly creating an object of the appropriate data class with new . All are imported with the tag :types , as well as being included in the :all tag. Each takes a single Perl value as an argument and returns an object of the appropriate data-type class as a result. Note that most constructors make no effort to validate their data, so it is up to the application to send correct data for classes such as RPC::XML::double or RPC::XML::datetime_iso8601 . Also note that the two-argument form of the RPC::XML::base64 constructor isn't available via this function.

A.3.2 RPC::XML::Client

The client class provides all the functionality needed to initiate remote connects, make requests and obtain the responses from them. It's a container class, encapsulating a LWP:: UserAgent object, a HTTP::Request object, and a RPC::XML::Parser object. The first two are from the LWP package, while the last is a part of the RPC::XML package (it isn't documented in this chapter because currently it can't be manipulated at the application level). The LWP::UserAgent object manages all communications for the client object, while the HTTP::Request object is prepopulated with all the headers needed for XML-RPC compliance. This keeps the client from having to create a new request object for every remote call.

The client class recognizes the following methods:

new( URL, optional key/value pairs )

Creates new objects of the class. It requires at least one parameter, the URL of the server that requests will be sent to. Any additional arguments are treated as key/value pairs. The known parameters are listed here and any not in the list are copied onto the object unchanged (allowing for subclasses to have their own instance values). Here are the known parameters:

error_handler , fault_handler , combined_handler

These set the error and/or fault handlers to a code reference given as the value of the pair. combined_handler sets both handlers to the same reference. It is applied first, so also passing one of the others overrides the combined handler setting.

url( optional new URL )

Returns the current URL that the client is connecting to for requests. If a new value is passed as an argument, it sets that as the URL. The old value is returned in the latter case should the application wish to restore it at some point.

useragent

Returns the LWP::UserAgent object that the client encapsulates. This allows the application to call methods on that object directly, such as setting proxy information, etc.

request

Returns the HTTP::Request object contained within the client, allowing the application to call methods on the object directly.

simple_request( argument list )

Makes a request to the remote server and returns the response as a native Perl value. Faults will be returned as hash references, and internal errors will result in undef being returned, and the error message stored in the global scalar, $RPC::XML::ERROR . This is a wrapper around the send_request method to ease short applications by returning Perl data rather than data objects. Any configured error or fault handlers will be triggered if so needed.

The arguments to the method may take one of two forms: either a method name (an ordinary Perl string) followed by zero or more arguments or an object of the RPC::XML::request class. In the former case, any arguments already in object form aren't converted; those that aren't pass to smart_encode (defined earlier).

send_request( argument list )

Also sends requests to the remote server, but the return value is a data object or a nonreference value if an error occurred. The argument type and disposition are the same as for the previous method. Any fault response from the server triggers the fault handler, if set. Any error in transport triggers the error handler, if that is set. Should either handler throw an exception by using die , the method never returns.

credentials( realm, user name, password )

Sets the credentials used for Basic Authentication, for requests against a URL that uses this form of authentication. This is a proxy into the credentials method of LWP::UserAgent , and is more convenient than retrieving the user-agent object and calling the same method.

compress_requests( optional boolean )

The client objects attempt to use content compression if the Compress::Zlib module from CPAN is available, and if the server supports it. Because the client can't know in advance if a server supports compression, this method allows an application to force the use of compression if it's known for certain that the server supports it. If no argument is passed, it returns the current setting. This method doesn't preserve the old setting as other methods in the class do.

compress_thresh( optional new value )

Gets (and optionally sets) the threshold value when compression is applied to an outgoing message. The default value is 4096 (4K), meaning that any XML message body greater than number of bytes in length is compressed. When setting the value, the old value is returned in case the application intends to restore it at a later point.

error_handler , fault_handler , combined_handler( optional code references )

These methods retrieve and set the handlers for errors and faults. Each returns the current handler (error or fault) when called, with the combined_handler method returning a two-item list. If called with an argument, the argument must be a code reference. It is set as the new handler of the given type, and the old value(s) returned.

A.3.3 RPC::XML::Server

The basic server class provides the core functionality for serving XML-RPC requests. It is subclassed by the Apache server code (covered later). The XML::RPC::Server class is also a container, holding an instance of the HTTP::Response class and possibly an instance of the HTTP::Daemon class as well. As with the client class's use of the HTTP::Request object, the HTTP::Response object here is created and prepopulated with the headers required for XML-RPC compliance, allowing the server to avoid creating and seeding a new response object for every incoming request. The class creates and stores an instance of HTTP::Daemon by default, but this can be prevented with arguments to the constructor. The server object may use the Net::Server module from CPAN (if available) to handle the communications, or in the case of the Apache::RPC::Server subclassing, it doesn't need a HTTP listener at all.

Here are the methods in this class:

new( optional key/value pairs )

This is the class constructor. It creates and returns a new object, using any of the following options. Options are passed as key/value pairs, not as a hash reference.

no_http

If passed with a non- false value, this inhibits the creation of the HTTP::Daemon object within the server object being built. This is used directly by the Apache::RPC::Server constructor and may be used by application developers intended to use Net::Server in place of HTTP::Daemon . This doesn't trigger loading of Net::Server ; see server_loop .

no_default

If passed with a non- false value, prevents the loading of the default server methods that are a part of the RPC::XML package. These are described later. The Apache server module uses this option, then later uses add_default_methods (also described later) to control the actual methods that are loaded.

path , host , port , queue

These four values control the settings on the underlying HTTP::Daemon object, or possibly the Net::Server object. The host and port values specify the host name (or IP address) and port to bind the listening socket to. The queue value specifies the size of the listening queue for the socket. The path value indicates what URL path components should be added to the URL string the server advertises in the url method (defined later).

Depending on how server_loop is called when Net::Server is being used, any of these values may be overridden.

xpl_path

Server objects can load their methods from specially formatted files. By default, the server object has a limited list of directories it searches for these files. This option provides an array reference as a value, and if passed the contents of the array reference, are added to the list of directories to search.

timeout

When HTTP::Daemon is reading an incoming request on a socket, it uses this value as the time-out value. The connection is dropped if the client doesn't get the full request to the server before the given amount of time has elapsed. The value is expressed in seconds, and the default value is 10 .

auto_methods

If passed with a non- false value, this tells the server to search for a method when a request comes in for an unknown name. The list of directories for XPL files are searched for a file whose name (minus the .xpl extension) matches the requested name. Note that this feature is a potential security issue.

auto_updates

When a method is loaded from an XPL file, the server records the modification time of the file. If this option is passed with a non- false value, each call to the given method checks its file to see if it has been updated, and if so rereads the file before dispatching the method. Note that this also presents a security risk.

version

Returns the version number of the package in use. Should be overridden in subclasses.

product_tokens

Returns the name of the class followed by the version number, in a style similar to other HTTP servers: NAME/VERSION . Useful for constructing Server : headers in outgoing messages.

url

Returns the URL address that is used to contact the server.

requests

Returns the number of requests the server has handled thus far.

response

Like the client object methods, this returns the HTTP::Response object that the server contains, so that methods may be called on it if needed.

started( optional boolean )

When called with a non-null value, this method calls the built-in time function and notes the time that the server (presumably) started waiting for requests. When called with no argument, the stored value is returned, which may then be used as a sort of "server up-time" meter.

add_method( method argument )

This is the primary way to add published methods to a server object. The argument may take one of three forms: the name of a XPL file, a precreated code object (see the section Server-Side Code Classes), or an ordinary hash reference. Both the XPL file and object forms are self-contained. The hash reference will be examined for the following keys:

name

(Required) This parameter gives the name of the new method, as it will be presented to clients .

code

(Required) The value of this parameter must be a code reference (symbolic references can't be used). It is stored as the actual Perl code to be invoked when the server dispatches a call to the particular method.

signature

(Usually required) The value for this parameter is an array reference containing the signatures that the method offers. Signatures provide information about the types and order of arguments, and the type of the return value a given call produces. The function type of code object doesn't use signatures, so this parameter is optional for that type; it's required for the others.

help

This key provides the help text for the method, which is used by the introspection API, particularly the system.methodHelp call.

type

This tells add_method whether the hash reference is defining a method , procedure , or function object. The difference between these types is explained later. The default value is method .

version

If passed, the value of this key is stored as the version of the method encapsulated by the underlying object. This value isn't used anywhere internally, but it is used in the Apache status module, described later.

hidden

If passed with a non- false value, this marks the new code object to be hidden from the provided introspection API.

add_default_methods( optional detail arguments )

Adds the server-side methods that are provided with the RPC::XML package; these implement the client/server introspection interface discussed in Chapter 3 and Chapter 4. The list of arguments can limit the list loaded by specifying filenames that are specifically looked for in the directory in which the XPL files are kept (if the .xpl extension is missing from a name, it is silently added). If the list of names contains the string except (or -except ), all names following that token are excluded from the list of methods to be loaded. These particular methods are searched for only in the directory in which the RPC::XML::Server module itself resides.

add_methods_in_dir( directory, optional detail arguments )

Similar in functionality to the previous, except that the first argument in the list is taken to be a specific directory to search, rather than defaulting to the module's installation directory. The nature of the rest of the parameters is the same as in add_default_methods .

delete_method( name )

Deletes the method whose external (published) name matches the input parameter. Returns the server object on success or an error message on failure.

get_method( name )

Retrieves the object that encapsulates the server method whose published name matches the input parameter. The return value is an object, not a hash reference. See the section Server-Side Code Classes.

list_methods

Returns a list of the published methods that the object has associated with it. The list is returned with names, not the underlying objects.

share_methods( server, list of names ) , copy_methods( server, list of names )

These two methods enable mingling of server-side method objects between two server instances. The share_methods call puts references to the same code objects into the calling server object. The copy_methods approach differs in that each target code object is cloned, creating a new object that points to the same underlying code reference. New code objects are then installed on the calling server object, but the compiled Perl code is still shared.

The first argument is a server object to get the code objects from. The list of names must be one or more published names of server-side code on the target object. Any of the values in the list of names may be a Regex object (created using qr// in Perl). If any of these are detected , the regular expression is evaluated against all the code object's names on the target server object, and all matching objects are added to the list. For example:

 ($S2->share_methods($S1, qr/^meerkat/) 

results in all methods on $S1 whose published names start with meerkat are shared onto $S2 .

Note that using either of these methods on a code object that contain closures (code references with binding to lexically scoped values) means that each server object shares the same lexically bound values.

server_loop( optional key/value pairs )

Enters the loop in which the socket is monitored for connections. When a HTTP::Daemon object is present, the only argument recognized in the parameters list is signal . This parameter, if passed, specifies a signal name (or an array reference containing several names) that should be set up as the monitored interrupt signal for the server loop. A signal handler is attached to the specified signal(s) to terminate the otherwise infinite loop and return to the caller.

If no HTTP listener is created ( no_http was set in the constructor), it attempts to load the Net::Server module. If successful, the class's @ISA hierarchy is changed to include Net::Server , and the run method of that class is entered with all the arguments passed in from the original call. See the documentation for that module for more on the range and meaning of the parameters to run .

dispatch( request )

A server object uses this method to actually turn a request into a server-side method call and result. The argument may be either an XML document, a scalar reference to the XML (to reduce the memory used in duplicating strings on the stack), or a RPC::XML::request object. If the argument is XML (or the scalar reference to XML), it is first converted to object form. The method then looks up the requested method and fashions the call to that method. The return value from this is an object of the RPC::XML::response class.

xpl_path( optional array reference )

Gets the search path for XPL files as an array reference. If passed with an array reference as an argument, it sets a new search path for XPL files. This completely replaces the existing list, so to augment a list, the application must first retrieve the current list and include it in the new one. The old path is returned as an array reference when setting a new path.

A.3.4 Server-Side Code Classes

Server-side code can behave as ordinary subroutines or as class methods, depending on the way the code is hooked into the server. The RPC::XML package uses a set of different code object classes to maintain the difference between the types.

Details of the XPL file format are provided in the module documentation and won't be covered here.

Each class supports the following methods:

new( arguments )

This is the constructor for the class. The arguments may be either a filename (if there is exactly one argument that isn't a reference), a hash reference, or a list of key/value pairs. The file is assumed to be a XPL file and the constructor will attempt to load it. The hash reference is assumed to be contain some subset of the keys listed here and will be copied to a new reference which is then blessed into the correct package. If the arguments are a series of key/value pairs, the following keys are recognized:

name

The name by which the code object is published on a server.

code

A code reference to the Perl subroutine/closure that is actually executed for requests. Symbolic references aren't accepted.

signature

This key may appear more than once. Each time, it specifies a signature that the new code object can accept. The signature may be a string or an array reference of types. If the argument to new was a hash reference, this key must point to an array reference whose items are also array references.

help

Provides the help text for the method, used by the introspection interface.

version

Provides a version string for the code being encapsulated, but it is used only in status reporting, not in any calls.

hidden

The value for this should be a boolean that tells whether the code object should be excluded from any listings generated by the introspection API.

clone

Creates a clone of the calling object and returns it. In the clone, everything is a copy of the original (including the array reference of signatures) except for the code reference, which is the same as in the original object.

name , code( optional code reference ) , signature( optional array reference ) , help( optional string ) , hidden( optional boolean ) , version( optional string )

These are accessors for the data within the object. The name field can't be changed, but the others may take a single argument that replaces the existing value for the given attribute. Unlike the accessors for the server and client classes, these always return the current value, even when setting it. To preserve old values, they must be retrieved before the new value is set.

is_valid

Returns a boolean value indicating whether the object has enough information to be added to a server object. Checks primarily for a valid name, code reference, and signature list (if signatures are used).

add_signature( list of new )

Adds one or more new signatures to the internal table. Each argument in the list of new signatures may be a string or an array reference. Strings must be space-separated type identifiers. The array references should contain one type identifier per element. If any of the new signature creates a conflict with an existing signature (cases in which the same set of input types is expected to yield a different return type), all changes are abandoned , and an error message is returned. The object reference is returned on success.

delete_signature( list to delete )

Removes the signatures specified in the list of arguments. The syntax of the arguments is the same as for add_signature . All signatures are deleted (nonexistent ones are silently ignored). An error message is returned if the resulting signature table is invalid (in this case, if it is now empty), otherwise the object reference is returned.

match_signature( signature )

Attempts to match a signature to the object's signature table. If found, the expected return type is passed back. If it isn't found, a false value is returned.

call( server object, parameters )

Calls the underlying Perl code, with the parameters passed in the arguments list. The first argument to call must be an object that derives from RPC::XML::Server . The server object is the initial parameter in the list when calling code that is supposed to behave like a class method. The return value is a data object of the type that matches the signature of the arguments passed in.

reload

Tells the object to reload the XPL file it was originally created from. If it isn't loaded from an XPL file, the method silently returns without doing anything.

A.3.4.1 RPC::XML::Method

Code objects created in the RPC::XML::Method class call their encapsulated code references in a fashion that emulates a method call. The server object is passed as the first parameter in the list to the Perl subroutine. Using this object reference, the code may interact with the server to get information about how it was called (by what name, and by what signature) or to call other routines on the server by their published interface, rather than requiring internal knowledge.

RPC::XML::Method derives from RPC::XML::Procedure .

A.3.4.2 RPC::XML::Procedure

The RPC::XML::Procedure class of code objects calls its encapsulated subroutines with an ordinary argument list. The server object isn't available to the code being invoked.

A.3.4.3 RPC::XML::Function

This class of code objects doesn't use signatures. It is designed for quick and simple creation of XML-RPC wrappers around existing code and libraries. Calls to the underlying Perl subroutine are done the same way as with the XML::RPC::Procedure class. As such, these routines don't have access to the server object.

RPC::XML::Function derives from XML::RPC::Procedure .

A.3.5 Apache::RPC::Server

The Apache::RPC::Server class is a subclass of XML::RPC::Server that is engineered especially for use as an Apache/mod_perl location handler. The following methods are unique to this package or significantly different from the parent class:

handler

This method is defined so that mod_perl can use the class directly as a location handler. It's prototyped as a method handler in mod_perl terms, allowing applications to subclass it if desired. It's called as a method (meaning that an object reference or package name is the first parameter passed in) with the Apache object (the request) as a parameter.

init_handler

This method is provided as a possible handler for the mod_perl PerlChildInitHandler phase. As implemented, it calls the child_started method only on each XML-RPC server object within the internal table Apache::RPC::Server maintains. It is also prototyped as a method handler, so it too may be overridden in a subclass.

new( key/value pairs )

The constructor for this class is a little different from its parent. It calls the parent constructor to create the actual object, and most of the parameters are passed through directly to the parent (along with setting no_http ). It also attempts to configure itself as much as possible from the Apache environment and then adds itself to an internal table that the class maintains, before returning the new object reference. Here are the parameters directly used by this constructor (not passed to the parent):

apache

A reference to an Apache object reference, which is used to access location configuration information and other needed internals.

server_id

The server ID is just a string that distinguishes XML-RPC servers within a single Apache server. Because multiple servers may be set up from Apache configuration blocks alone, this offers an alternative to using <Perl> blocks to set up such situations. If not passed, the URL location that Apache has the handler mapped to is used.

prefix

Provides a prefix that is applied to all the directory-level configuration options new attempts to locate and use. Overrides any value that might be set by the Apache configuration for the option prefix.

Configuration of the Apache::RPC::Server objects using directory configuration values is covered in detail in the manpage for this class.

child_started( optional boolean )

Similar to the started method in the parent class, but it keeps a separate value from the start time. Under mod_perl , the server objects may be created during initialization and passed to child processes when Apache creates them. This value notes when the given child started, versus when the server object itself may have started.

version

Identical to the parent method of the same name, except that it instead returns the version string for this package.

list_servers

Returns a list of the server objects by their server ID. May be called as a static method.

get_server( server ID )

Retrieves a server object by the unique server ID. Also may be called as a static method.

The manpage for the class contains examples for directly creating objects and assigning them as location handlers within <Perl> blocks in the Apache configuration. When the handlers are set up in this fashion, the handler method gets the server object rather than the class name in its argument list, which makes for faster handling of requests.

A.3.6 Apache::RPC::Status

This class isn't used within applications but deserves some attention here. It implements a status monitor similar to the Apache::Status package, for monitoring the XML-RPC servers on a given Apache installation. Like the Apache::RPC::Server class, the handlers are prototyped as method handlers, to allow for subclassing this package if desired. Installation of this monitor is covered in the manpage for the class. Here are the methods that a new derivative may wish to override or extend:

new( parameter list )

Creates a new object to handle requests for a location. The package maintains a default object internally if the status monitor is set up with just Apache configuration directives. The only recognized parameter is serverclass , which defaults to Apache::RPC::Server . This is needed because the status monitor has to call some static methods from the class in order to get the server objects, etc.

handler

The main location handler provided by this class handles generating all HTML pages, based on the CGI-style parameters passed in the URL.

init_handler

At present, this does nothing except check for a directory-configuration value called ServerClass , which has the same function as the serverclass parameter to new . Included to facilitate subclassing.

make_url( request, optional flag )

Creates a URL for generating hyperlinks . The first parameter must be either the Apache request object originally passed to handler or a CGI object (from the CGI class in the Perl core). The optional flag, if set to a true value, requests that the URL be suitable for use when Apache::RPC::Status is configured to be connected to the Apache::Status module.

apache_status_attach

Attempts to attach the XML-RPC status monitor to the main screen of the Apache::Status package.

More detail about the information the monitor provides is detailed in the manpage for the class. This includes guides for extending the monitoring capabilities themselves.



Programming Web Services with Perl
Programming Web Services with Perl
ISBN: 0596002068
EAN: 2147483647
Year: 2000
Pages: 123

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net