From d17d1b111341f2c8979cf8fbd63ec7ec9db7c3ad Mon Sep 17 00:00:00 2001 From: nobu Date: Fri, 6 Mar 2009 03:56:38 +0000 Subject: * {ext,lib,test}/**/*.rb: removed trailing spaces. git-svn-id: http://svn.ruby-lang.org/repos/ruby/trunk@22784 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- lib/xmlrpc/base64.rb | 22 +++--- lib/xmlrpc/client.rb | 142 +++++++++++++++++------------------ lib/xmlrpc/config.rb | 8 +- lib/xmlrpc/create.rb | 70 ++++++++--------- lib/xmlrpc/datetime.rb | 18 ++--- lib/xmlrpc/httpserver.rb | 44 +++++------ lib/xmlrpc/marshal.rb | 6 +- lib/xmlrpc/parser.rb | 132 ++++++++++++++++---------------- lib/xmlrpc/server.rb | 190 +++++++++++++++++++++++------------------------ lib/xmlrpc/utils.rb | 30 ++++---- 10 files changed, 331 insertions(+), 331 deletions(-) (limited to 'lib/xmlrpc') diff --git a/lib/xmlrpc/base64.rb b/lib/xmlrpc/base64.rb index f9a21c703..bfa8c0a2d 100644 --- a/lib/xmlrpc/base64.rb +++ b/lib/xmlrpc/base64.rb @@ -9,19 +9,19 @@ Released under the same term of license as Ruby. = XMLRPC::Base64 == Description -This class is necessary for (('xmlrpc4r')) to determine that a string should -be transmitted base64-encoded and not as a raw-string. -You can use (({XMLRPC::Base64})) on the client and server-side as a +This class is necessary for (('xmlrpc4r')) to determine that a string should +be transmitted base64-encoded and not as a raw-string. +You can use (({XMLRPC::Base64})) on the client and server-side as a parameter and/or return-value. == Class Methods --- XMLRPC::Base64.new( str, state = :dec ) Creates a new (({XMLRPC::Base64})) instance with string ((|str|)) as the - internal string. When ((|state|)) is (({:dec})) it assumes that the - string ((|str|)) is not in base64 format (perhaps already decoded), - otherwise if ((|state|)) is (({:enc})) it decodes ((|str|)) + internal string. When ((|state|)) is (({:dec})) it assumes that the + string ((|str|)) is not in base64 format (perhaps already decoded), + otherwise if ((|state|)) is (({:enc})) it decodes ((|str|)) and stores it as the internal string. - + --- XMLRPC::Base64.decode( str ) Decodes string ((|str|)) with base64 and returns that value. @@ -40,7 +40,7 @@ parameter and/or return-value. module XMLRPC class Base64 - + def initialize(str, state = :dec) case state when :enc @@ -51,11 +51,11 @@ class Base64 raise ArgumentError, "wrong argument; either :enc or :dec" end end - + def decoded - @str + @str end - + def encoded Base64.encode(@str) end diff --git a/lib/xmlrpc/client.rb b/lib/xmlrpc/client.rb index 9d0a8bbaf..65c9cd0c9 100644 --- a/lib/xmlrpc/client.rb +++ b/lib/xmlrpc/client.rb @@ -26,7 +26,7 @@ Released under the same term of license as Ruby. or require "xmlrpc/client" - + server = XMLRPC::Client.new("www.ruby-lang.org", "/RPC2", 80) ok, param = server.call2("michael.add", 4, 5) if ok then @@ -40,14 +40,14 @@ or == Description Class (({XMLRPC::Client})) provides remote procedure calls to a XML-RPC server. After setting the connection-parameters with (()) which -creates a new (({XMLRPC::Client})) instance, you can execute a remote procedure +creates a new (({XMLRPC::Client})) instance, you can execute a remote procedure by sending the (()) or (()) -message to this new instance. The given parameters indicate which method to +message to this new instance. The given parameters indicate which method to call on the remote-side and of course the parameters for the remote procedure. == Class Methods --- XMLRPC::Client.new( host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil, user=nil, password=nil, use_ssl=false, timeout =nil) - Creates an object which represents the remote XML-RPC server on the + Creates an object which represents the remote XML-RPC server on the given host ((|host|)). If the server is CGI-based, ((|path|)) is the path to the CGI-script, which will be called, otherwise (in the case of a standalone server) ((|path|)) should be (({"/RPC2"})). @@ -59,8 +59,8 @@ call on the remote-side and of course the parameters for the remote procedure. Default values for ((|host|)), ((|path|)) and ((|port|)) are 'localhost', '/RPC2' and '80' respectively using SSL '443'. - If ((|user|)) and ((|password|)) are given, each time a request is send, - a Authorization header is send. Currently only Basic Authentification is + If ((|user|)) and ((|password|)) are given, each time a request is send, + a Authorization header is send. Currently only Basic Authentification is implemented no Digest. If ((|use_ssl|)) is set to (({true})), comunication over SSL is enabled. @@ -76,9 +76,9 @@ call on the remote-side and of course the parameters for the remote procedure. : proxy Is of the form "host:port". - + : timeout - Defaults to 30. + Defaults to 30. --- XMLRPC::Client.new3( hash={} ) --- XMLRPC::Client.new_from_hash( hash={} ) @@ -97,10 +97,10 @@ call on the remote-side and of course the parameters for the remote procedure. == Instance Methods --- XMLRPC::Client#call( method, *args ) - Invokes the method named ((|method|)) with the parameters given by + Invokes the method named ((|method|)) with the parameters given by ((|args|)) on the XML-RPC server. - The parameter ((|method|)) is converted into a (({String})) and should - be a valid XML-RPC method-name. + The parameter ((|method|)) is converted into a (({String})) and should + be a valid XML-RPC method-name. Each parameter of ((|args|)) must be of one of the following types, where (({Hash})), (({Struct})) and (({Array})) can contain any of these listed ((:types:)): * (({Fixnum})), (({Bignum})) @@ -110,31 +110,31 @@ call on the remote-side and of course the parameters for the remote procedure. * (({Hash})), (({Struct})) * (({Array})) * (({Date})), (({Time})), (({XMLRPC::DateTime})) - * (({XMLRPC::Base64})) - * A Ruby object which class includes XMLRPC::Marshallable (only if Config::ENABLE_MARSHALLABLE is (({true}))). + * (({XMLRPC::Base64})) + * A Ruby object which class includes XMLRPC::Marshallable (only if Config::ENABLE_MARSHALLABLE is (({true}))). That object is converted into a hash, with one additional key/value pair "___class___" which contains the class name for restoring later that object. - - The method returns the return-value from the RPC - ((-stands for Remote Procedure Call-)). + + The method returns the return-value from the RPC + ((-stands for Remote Procedure Call-)). The type of the return-value is one of the above shown, only that a (({Bignum})) is only allowed when it fits in 32-bit and that a XML-RPC (('dateTime.iso8601')) type is always returned as - a ((<(({XMLRPC::DateTime}))|URL:datetime.html>)) object and + a ((<(({XMLRPC::DateTime}))|URL:datetime.html>)) object and a (({Struct})) is never returned, only a (({Hash})), the same for a (({Symbol})), where - always a (({String})) is returned. + always a (({String})) is returned. A (({XMLRPC::Base64})) is returned as a (({String})) from xmlrpc4r version 1.6.1 on. - - If the remote procedure returned a fault-structure, then a + + If the remote procedure returned a fault-structure, then a (({XMLRPC::FaultException})) exception is raised, which has two accessor-methods (({faultCode})) and (({faultString})) of type (({Integer})) and (({String})). --- XMLRPC::Client#call2( method, *args ) The difference between this method and (()) is, that this method do ((*not*)) raise a (({XMLRPC::FaultException})) exception. - The method returns an array of two values. The first value indicates if + The method returns an array of two values. The first value indicates if the second value is a return-value ((({true}))) or an object of type - (({XMLRPC::FaultException})). + (({XMLRPC::FaultException})). Both are explained in (()). Simple to remember: The "2" in "call2" denotes the number of values it returns. @@ -151,19 +151,19 @@ call on the remote-side and of course the parameters for the remote procedure. # => [7, -1] --- XMLRPC::Client#multicall2( *methods ) - Same as (()), but returns like (()) two parameters + Same as (()), but returns like (()) two parameters instead of raising an (({XMLRPC::FaultException})). --- XMLRPC::Client#proxy( prefix, *args ) Returns an object of class (({XMLRPC::Client::Proxy})), initialized with ((|prefix|)) and ((|args|)). A proxy object returned by this method behaves like (()), i.e. a call on that object will raise a - (({XMLRPC::FaultException})) when a fault-structure is returned by that call. + (({XMLRPC::FaultException})) when a fault-structure is returned by that call. --- XMLRPC::Client#proxy2( prefix, *args ) Almost the same like (()) only that a call on the returned (({XMLRPC::Client::Proxy})) object behaves like (()), i.e. - a call on that object will return two parameters. + a call on that object will return two parameters. @@ -175,21 +175,21 @@ call on the remote-side and of course the parameters for the remote procedure. --- XMLRPC::Client#proxy_async(...) --- XMLRPC::Client#proxy2_async(...) In contrast to corresponding methods without "_async", these can be - called concurrently and use for each request a new connection, where the + called concurrently and use for each request a new connection, where the non-asynchronous counterparts use connection-alive (one connection for all requests) - if possible. + if possible. - Note, that you have to use Threads to call these methods concurrently. + Note, that you have to use Threads to call these methods concurrently. The following example calls two methods concurrently: - + Thread.new { p client.call_async("michael.add", 4, 5) } - + Thread.new { p client.call_async("michael.div", 7, 9) } - + --- XMLRPC::Client#timeout --- XMLRPC::Client#user @@ -200,12 +200,12 @@ call on the remote-side and of course the parameters for the remote procedure. --- XMLRPC::Client#user= (new_user) --- XMLRPC::Client#password= (new_password) Set the corresponding attributes. - + --- XMLRPC::Client#set_writer( writer ) Sets the XML writer to use for generating XML output. Should be an instance of a class from module (({XMLRPC::XMLWriter})). - If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. + If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. --- XMLRPC::Client#set_parser( parser ) Sets the XML parser to use for parsing XML documents. @@ -220,7 +220,7 @@ call on the remote-side and of course the parameters for the remote procedure. Set extra HTTP headers that are included in the request. --- XMLRPC::Client#http_header_extra - Access the via (()) assigned header. + Access the via (()) assigned header. --- XMLRPC::Client#http_last_response Returns the (({Net::HTTPResponse})) object of the last RPC. @@ -240,31 +240,31 @@ call on the remote-side and of course the parameters for the remote procedure. == Description Class (({XMLRPC::Client::Proxy})) makes XML-RPC calls look nicer! -You can call any method onto objects of that class - the object handles +You can call any method onto objects of that class - the object handles (({method_missing})) and will forward the method call to a XML-RPC server. Don't use this class directly, but use instead method (()) or (()). == Class Methods ---- XMLRPC::Client::Proxy.new( server, prefix, args=[], meth=:call, delim="." ) +--- XMLRPC::Client::Proxy.new( server, prefix, args=[], meth=:call, delim="." ) Creates an object which provides (({method_missing})). ((|server|)) must be of type (({XMLRPC::Client})), which is the XML-RPC server to be used for a XML-RPC call. ((|prefix|)) and ((|delim|)) will be prepended to the methodname - called onto this object. + called onto this object. Parameter ((|meth|)) is the method (call, call2, call_async, call2_async) to use for a RPC. ((|args|)) are arguments which are automatically given to every XML-RPC call before the arguments provides through (({method_missing})). - + == Instance Methods Every method call is forwarded to the XML-RPC server defined in (()). - + Note: Inherited methods from class (({Object})) cannot be used as XML-RPC names, because they get around -(({method_missing})). - +(({method_missing})). + = History @@ -283,7 +283,7 @@ require "net/http" module XMLRPC class Client - + USER_AGENT = "XMLRPC::Client (Ruby #{RUBY_VERSION})" include ParserWriterChooseMixin @@ -292,11 +292,11 @@ module XMLRPC # Constructors ------------------------------------------------------------------- - def initialize(host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil, + def initialize(host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil, user=nil, password=nil, use_ssl=nil, timeout=nil) @http_header_extra = nil - @http_last_response = nil + @http_last_response = nil @cookie = nil @host = host || "localhost" @@ -325,7 +325,7 @@ module XMLRPC # HTTP object for synchronous calls Net::HTTP.version_1_2 - @http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port) + @http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port) @http.use_ssl = @use_ssl if @use_ssl @http.read_timeout = @timeout @http.open_timeout = @timeout @@ -341,7 +341,7 @@ module XMLRPC if match = /^([^:]+):\/\/(([^@]+)@)?([^\/]+)(\/.*)?$/.match(uri) proto = match[1] user, passwd = (match[3] || "").split(":") - host, port = match[4].split(":") + host, port = match[4].split(":") path = match[5] if proto != "http" and proto != "https" @@ -351,7 +351,7 @@ module XMLRPC else raise "Wrong URI as parameter!" end - + proxy_host, proxy_port = (proxy || "").split(":") self.new(host, path, port, proxy_host, proxy_port, user, passwd, (proto == "https"), timeout) @@ -384,7 +384,7 @@ module XMLRPC # Cookie support attr_accessor :cookie - + attr_reader :timeout, :user, :password @@ -407,13 +407,13 @@ module XMLRPC # Call methods -------------------------------------------------------------- def call(method, *args) - ok, param = call2(method, *args) + ok, param = call2(method, *args) if ok param else raise param end - end + end def call2(method, *args) request = create().methodCall(method, *args) @@ -422,13 +422,13 @@ module XMLRPC end def call_async(method, *args) - ok, param = call2_async(method, *args) + ok, param = call2_async(method, *args) if ok param else raise param end - end + end def call2_async(method, *args) request = create().methodCall(method, *args) @@ -467,7 +467,7 @@ module XMLRPC # Proxy generating methods ------------------------------------------ - + def proxy(prefix=nil, *args) Proxy.new(self, prefix, args, :call) end @@ -498,10 +498,10 @@ module XMLRPC end def do_rpc(request, async=false) - header = { + header = { "User-Agent" => USER_AGENT, "Content-Type" => "text/xml; charset=utf-8", - "Content-Length" => request.size.to_s, + "Content-Length" => request.size.to_s, "Connection" => (async ? "close" : "keep-alive") } @@ -512,41 +512,41 @@ module XMLRPC # add authorization header header["Authorization"] = @auth end - + resp = nil @http_last_response = nil if async - # use a new HTTP object for each call + # use a new HTTP object for each call Net::HTTP.version_1_2 - http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port) + http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port) http.use_ssl = @use_ssl if @use_ssl http.read_timeout = @timeout http.open_timeout = @timeout - + # post request http.start { - resp = http.post2(@path, request, header) + resp = http.post2(@path, request, header) } else # reuse the HTTP object for each call => connection alive is possible # we must start connection explicitely first time so that http.request # does not assume that we don't want keepalive @http.start if not @http.started? - + # post request - resp = @http.post2(@path, request, header) + resp = @http.post2(@path, request, header) end - + @http_last_response = resp data = resp.body if resp.code == "401" # Authorization Required - raise "Authorization failed.\nHTTP-Error: #{resp.code} #{resp.message}" + raise "Authorization failed.\nHTTP-Error: #{resp.code} #{resp.message}" elsif resp.code[0,1] != "2" - raise "HTTP-Error: #{resp.code} #{resp.message}" + raise "HTTP-Error: #{resp.code} #{resp.message}" end ct = parse_content_type(resp["Content-Type"]).first @@ -559,8 +559,8 @@ module XMLRPC end expected = resp["Content-Length"] || "" - if data.nil? or data.size == 0 - raise "Wrong size. Was #{data.size}, should be #{expected}" + if data.nil? or data.size == 0 + raise "Wrong size. Was #{data.size}, should be #{expected}" elsif expected != "" and expected.to_i != data.size and resp["Transfer-Encoding"].nil? raise "Wrong size. Was #{data.size}, should be #{expected}" end @@ -581,11 +581,11 @@ module XMLRPC meth = :call2 meth = :call2_async if async - ok, params = self.send(meth, "system.multicall", + ok, params = self.send(meth, "system.multicall", methods.collect {|m| {'methodName' => m[0], 'params' => m[1..-1]} } ) - if ok + if ok params = params.collect do |param| if param.is_a? Array param[0] @@ -593,7 +593,7 @@ module XMLRPC XMLRPC::FaultException.new(param["faultCode"], param["faultString"]) else raise "Wrong multicall return value" - end + end end end @@ -607,7 +607,7 @@ module XMLRPC def initialize(server, prefix, args=[], meth=:call, delim=".") @server = server @prefix = prefix ? prefix + delim : "" - @args = args + @args = args @meth = meth end diff --git a/lib/xmlrpc/config.rb b/lib/xmlrpc/config.rb index c4d2c41aa..34c3bbaf1 100644 --- a/lib/xmlrpc/config.rb +++ b/lib/xmlrpc/config.rb @@ -8,7 +8,7 @@ module XMLRPC module Config DEFAULT_WRITER = XMLWriter::Simple # or XMLWriter::XMLParser - + # available parser: # * XMLParser::NQXMLTreeParser # * XMLParser::NQXMLStreamParser @@ -21,16 +21,16 @@ module XMLRPC # enable tag ENABLE_NIL_CREATE = false ENABLE_NIL_PARSER = false - + # allows integers greater than 32-bit if true ENABLE_BIGINT = false # enable marshalling ruby objects which include XMLRPC::Marshallable - ENABLE_MARSHALLING = true + ENABLE_MARSHALLING = true # enable multiCall extension by default ENABLE_MULTICALL = false - + # enable Introspection extension by default ENABLE_INTROSPECTION = false diff --git a/lib/xmlrpc/create.rb b/lib/xmlrpc/create.rb index 530d229f6..2d38a44b3 100644 --- a/lib/xmlrpc/create.rb +++ b/lib/xmlrpc/create.rb @@ -1,6 +1,6 @@ # # Creates XML-RPC call/response documents -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) # # $Id$ @@ -41,7 +41,7 @@ module XMLRPC def element(name, attrs, *children) raise "attributes not yet implemented" unless attrs.nil? if children.empty? - "<#{name}/>" + "<#{name}/>" else "<#{name}>" + children.join("") + "" end @@ -69,7 +69,7 @@ module XMLRPC end def document(*params) - XML::SimpleTree::Document.new(*params) + XML::SimpleTree::Document.new(*params) end def pi(name, *params) @@ -120,9 +120,9 @@ module XMLRPC tree = @writer.document( @writer.pi("xml", 'version="1.0"'), - @writer.ele("methodCall", + @writer.ele("methodCall", @writer.tag("methodName", name), - @writer.ele("params", *parameter) + @writer.ele("params", *parameter) ) ) @@ -137,29 +137,29 @@ module XMLRPC # if is_ret == false then the params array must # contain only one element, which is a structure # of a fault return-value. - # - # if is_ret == true then a normal + # + # if is_ret == true then a normal # return-value of all the given params is created. # def methodResponse(is_ret, *params) - if is_ret + if is_ret resp = params.collect do |param| @writer.ele("param", conv2value(param)) end - + resp = [@writer.ele("params", *resp)] else - if params.size != 1 or params[0] === XMLRPC::FaultException + if params.size != 1 or params[0] === XMLRPC::FaultException raise ArgumentError, "no valid fault-structure given" end resp = @writer.ele("fault", conv2value(params[0].to_h)) end - + tree = @writer.document( @writer.pi("xml", 'version="1.0"'), - @writer.ele("methodResponse", resp) + @writer.ele("methodResponse", resp) ) @writer.document_to_str(tree) + "\n" @@ -178,7 +178,7 @@ module XMLRPC def conv2value(param) val = case param - when Fixnum + when Fixnum @writer.tag("i4", param.to_s) when Bignum @@ -194,10 +194,10 @@ module XMLRPC when TrueClass, FalseClass @writer.tag("boolean", param ? "1" : "0") - when Symbol + when Symbol @writer.tag("string", param.to_s) - when String + when String @writer.tag("string", param) when NilClass @@ -211,51 +211,51 @@ module XMLRPC @writer.tag("double", param.to_s) when Struct - h = param.members.collect do |key| + h = param.members.collect do |key| value = param[key] - @writer.ele("member", + @writer.ele("member", @writer.tag("name", key.to_s), - conv2value(value) + conv2value(value) ) end - @writer.ele("struct", *h) + @writer.ele("struct", *h) when Hash # TODO: can a Hash be empty? - + h = param.collect do |key, value| - @writer.ele("member", + @writer.ele("member", @writer.tag("name", key.to_s), - conv2value(value) + conv2value(value) ) end - @writer.ele("struct", *h) + @writer.ele("struct", *h) when Array # TODO: can an Array be empty? a = param.collect {|v| conv2value(v) } - - @writer.ele("array", + + @writer.ele("array", @writer.ele("data", *a) ) when Time, Date, ::DateTime - @writer.tag("dateTime.iso8601", param.strftime("%Y%m%dT%H:%M:%S")) + @writer.tag("dateTime.iso8601", param.strftime("%Y%m%dT%H:%M:%S")) when XMLRPC::DateTime - @writer.tag("dateTime.iso8601", + @writer.tag("dateTime.iso8601", format("%.4d%02d%02dT%02d:%02d:%02d", *param.to_a)) - + when XMLRPC::Base64 - @writer.tag("base64", param.encoded) + @writer.tag("base64", param.encoded) - else + else if Config::ENABLE_MARSHALLING and param.class.included_modules.include? XMLRPC::Marshallable # convert Ruby object into Hash ret = {"___class___" => param.class.name} - param.instance_variables.each {|v| + param.instance_variables.each {|v| name = v[1..-1] val = param.instance_variable_get(v) @@ -266,16 +266,16 @@ module XMLRPC end } return conv2value(ret) - else + else ok, pa = wrong_type(param) if ok return conv2value(pa) - else + else raise "Wrong type!" end end end - + @writer.ele("value", val) end @@ -283,7 +283,7 @@ module XMLRPC false end - + end # class Create end # module XMLRPC diff --git a/lib/xmlrpc/datetime.rb b/lib/xmlrpc/datetime.rb index f66ef8963..d6c80a2cb 100644 --- a/lib/xmlrpc/datetime.rb +++ b/lib/xmlrpc/datetime.rb @@ -10,19 +10,19 @@ Released under the same term of license as Ruby. = XMLRPC::DateTime == Description This class is important to handle XMLRPC (('dateTime.iso8601')) values, -correcly, because normal UNIX-dates (class (({Date}))) only handle dates +correcly, because normal UNIX-dates (class (({Date}))) only handle dates from year 1970 on, and class (({Time})) handles dates without the time -component. (({XMLRPC::DateTime})) is able to store a XMLRPC +component. (({XMLRPC::DateTime})) is able to store a XMLRPC (('dateTime.iso8601')) value correctly. == Class Methods --- XMLRPC::DateTime.new( year, month, day, hour, min, sec ) Creates a new (({XMLRPC::DateTime})) instance with the - parameters ((|year|)), ((|month|)), ((|day|)) as date and + parameters ((|year|)), ((|month|)), ((|day|)) as date and ((|hour|)), ((|min|)), ((|sec|)) as time. Raises (({ArgumentError})) if a parameter is out of range, or ((|year|)) is not of type (({Integer})). - + == Instance Methods --- XMLRPC::DateTime#year --- XMLRPC::DateTime#month @@ -50,7 +50,7 @@ component. (({XMLRPC::DateTime})) is able to store a XMLRPC --- XMLRPC::DateTime#to_time Return a (({Time})) object of the date/time which (({self})) represents. - If the (('year')) is below 1970, this method returns (({nil})), + If the (('year')) is below 1970, this method returns (({nil})), because (({Time})) cannot handle years below 1970. The used timezone is GMT. @@ -68,7 +68,7 @@ require "date" module XMLRPC class DateTime - + attr_reader :year, :month, :day, :hour, :min, :sec def year= (value) @@ -102,14 +102,14 @@ class DateTime end alias mon month - alias mon= month= - + alias mon= month= + def initialize(year, month, day, hour, min, sec) self.year, self.month, self.day = year, month, day self.hour, self.min, self.sec = hour, min, sec end - + def to_time if @year >= 1970 Time.gm(*to_a) diff --git a/lib/xmlrpc/httpserver.rb b/lib/xmlrpc/httpserver.rb index 020e6cbcd..66d52139d 100644 --- a/lib/xmlrpc/httpserver.rb +++ b/lib/xmlrpc/httpserver.rb @@ -1,7 +1,7 @@ # -# Implements a simple HTTP-server by using John W. Small's (jsmall@laser.net) +# Implements a simple HTTP-server by using John W. Small's (jsmall@laser.net) # ruby-generic-server. -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) # # $Id$ @@ -14,8 +14,8 @@ class HttpServer < GServer ## # handle_obj specifies the object, that receives calls to request_handler - # and ip_auth_handler - def initialize(handle_obj, port = 8080, host = DEFAULT_HOST, maxConnections = 4, + # and ip_auth_handler + def initialize(handle_obj, port = 8080, host = DEFAULT_HOST, maxConnections = 4, stdlog = $stdout, audit = true, debug = true) @handler = handle_obj super(port, host, maxConnections, stdlog, audit, debug) @@ -24,7 +24,7 @@ class HttpServer < GServer private # Constants ----------------------------------------------- - + CRLF = "\r\n" HTTP_PROTO = "HTTP/1.0" SERVER_NAME = "HttpServer (Ruby #{RUBY_VERSION})" @@ -46,27 +46,27 @@ private } # Classes ------------------------------------------------- - + class Request attr_reader :data, :header, :method, :path, :proto - + def initialize(data, method=nil, path=nil, proto=nil) @header, @data = Table.new, data @method, @path, @proto = method, path, proto end - + def content_length len = @header['Content-Length'] return nil if len.nil? - return len.to_i + return len.to_i end - + end - + class Response attr_reader :header attr_accessor :body, :status, :status_message - + def initialize(status=200) @status = status @status_message = nil @@ -82,7 +82,7 @@ private include Enumerable def initialize(hash={}) - @hash = hash + @hash = hash update(hash) end @@ -113,7 +113,7 @@ private def http_header(header=nil) new_header = Table.new(DEFAULT_HEADER) - new_header.update(header) unless header.nil? + new_header.update(header) unless header.nil? new_header["Connection"] = "close" new_header["Date"] = http_date(Time.now) @@ -127,7 +127,7 @@ private def http_resp(status_code, status_message=nil, header=nil, body=nil) status_message ||= StatusCodeMapping[status_code] - + str = "" str << "#{HTTP_PROTO} #{status_code} #{status_message}" << CRLF http_header(header).writeTo(str) @@ -137,8 +137,8 @@ private end # Main Serve Loop ----------------------------------------- - - def serve(io) + + def serve(io) # perform IP authentification unless @handler.ip_auth_handler(io) io << http_resp(403, "Forbidden") @@ -149,10 +149,10 @@ private if io.gets =~ /^(\S+)\s+(\S+)\s+(\S+)/ request = Request.new(io, $1, $2, $3) else - io << http_resp(400, "Bad Request") + io << http_resp(400, "Bad Request") return end - + # parse HTTP headers while (line=io.gets) !~ /^(\n|\r)/ if line =~ /^([\w-]+):\s*(.*)$/ @@ -160,15 +160,15 @@ private end end - io.binmode + io.binmode response = Response.new # execute request handler @handler.request_handler(request, response) - + # write response back to the client io << http_resp(response.status, response.status_message, - response.header, response.body) + response.header, response.body) rescue Exception => e io << http_resp(500, "Internal Server Error") diff --git a/lib/xmlrpc/marshal.rb b/lib/xmlrpc/marshal.rb index 26510124c..d12182831 100644 --- a/lib/xmlrpc/marshal.rb +++ b/lib/xmlrpc/marshal.rb @@ -1,6 +1,6 @@ # # Marshalling of XML-RPC methodCall and methodResponse -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) # # $Id$ @@ -17,7 +17,7 @@ module XMLRPC include ParserWriterChooseMixin # class methods ------------------------------- - + class << self def dump_call( methodName, *params ) @@ -52,7 +52,7 @@ module XMLRPC create.methodCall( methodName, *params ) end - def dump_response( param ) + def dump_response( param ) create.methodResponse( ! param.kind_of?( XMLRPC::FaultException ) , param ) end diff --git a/lib/xmlrpc/parser.rb b/lib/xmlrpc/parser.rb index 2cf0530c9..d078de2f4 100644 --- a/lib/xmlrpc/parser.rb +++ b/lib/xmlrpc/parser.rb @@ -1,6 +1,6 @@ # # Parser for XML-RPC call and response -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) # # $Id$ @@ -60,7 +60,7 @@ module XMLRPC @faultCode = faultCode @faultString = faultString end - + # returns a hash def to_h {"faultCode" => @faultCode, "faultString" => @faultString} @@ -77,7 +77,7 @@ module XMLRPC when "0" then false when "1" then true else - raise "RPC-value of type boolean is wrong" + raise "RPC-value of type boolean is wrong" end end @@ -122,7 +122,7 @@ module XMLRPC def self.struct(hash) # convert to marhalled object klass = hash["___class___"] - if klass.nil? or Config::ENABLE_MARSHALLING == false + if klass.nil? or Config::ENABLE_MARSHALLING == false hash else begin @@ -130,9 +130,9 @@ module XMLRPC klass.split("::").each {|const| mod = mod.const_get(const.strip)} obj = mod.allocate - + hash.delete "___class___" - hash.each {|key, value| + hash.each {|key, value| obj.instance_variable_set("@#{ key }", value) if key =~ /^([\w_][\w_0-9]*)$/ } obj @@ -143,11 +143,11 @@ module XMLRPC end def self.fault(hash) - if hash.kind_of? Hash and hash.size == 2 and - hash.has_key? "faultCode" and hash.has_key? "faultString" and + if hash.kind_of? Hash and hash.size == 2 and + hash.has_key? "faultCode" and hash.has_key? "faultString" and hash["faultCode"].kind_of? Integer and hash["faultString"].kind_of? String - XMLRPC::FaultException.new(hash["faultCode"], hash["faultString"]) + XMLRPC::FaultException.new(hash["faultCode"], hash["faultString"]) else raise "wrong fault-structure: #{hash.inspect}" end @@ -182,9 +182,9 @@ module XMLRPC # TODO: add nil? unless %w(i4 int boolean string double dateTime.iso8601 base64).include? node.nodeName - if node.nodeName == "value" + if node.nodeName == "value" if not node.childNodes.to_a.detect {|n| _nodeType(n) == :ELEMENT}.nil? - remove << nd if nd.nodeValue.strip == "" + remove << nd if nd.nodeValue.strip == "" end else remove << nd if nd.nodeValue.strip == "" @@ -194,7 +194,7 @@ module XMLRPC remove << nd else removeWhitespacesAndComments(nd) - end + end end remove.each { |i| node.removeChild(i) } @@ -203,13 +203,13 @@ module XMLRPC def nodeMustBe(node, name) cmp = case name - when Array + when Array name.include?(node.nodeName) when String name == node.nodeName else raise "error" - end + end if not cmp then raise "wrong xml-rpc (name)" @@ -233,7 +233,7 @@ module XMLRPC def assert(b) if not b then - raise "assert-fail" + raise "assert-fail" end end @@ -249,21 +249,21 @@ module XMLRPC raise "wrong xml-rpc (size)" end end - + def integer(node) #TODO: check string for float because to_i returnsa # 0 when wrong string - nodeMustBe(node, %w(i4 int)) + nodeMustBe(node, %w(i4 int)) hasOnlyOneChild(node) - + Convert.int(text(node.firstChild)) end def boolean(node) - nodeMustBe(node, "boolean") + nodeMustBe(node, "boolean") hasOnlyOneChild(node) - + Convert.boolean(text(node.firstChild)) end @@ -274,36 +274,36 @@ module XMLRPC end def string(node) - nodeMustBe(node, "string") + nodeMustBe(node, "string") text_zero_one(node) end def double(node) #TODO: check string for float because to_f returnsa # 0.0 when wrong string - nodeMustBe(node, "double") + nodeMustBe(node, "double") hasOnlyOneChild(node) - + Convert.double(text(node.firstChild)) end def dateTime(node) nodeMustBe(node, "dateTime.iso8601") hasOnlyOneChild(node) - + Convert.dateTime( text(node.firstChild) ) end def base64(node) nodeMustBe(node, "base64") #hasOnlyOneChild(node) - + Convert.base64(text_zero_one(node)) end def member(node) nodeMustBe(node, "member") - assert( node.childNodes.to_a.size == 2 ) + assert( node.childNodes.to_a.size == 2 ) [ name(node[0]), value(node[1]) ] end @@ -311,13 +311,13 @@ module XMLRPC def name(node) nodeMustBe(node, "name") #hasOnlyOneChild(node) - text_zero_one(node) + text_zero_one(node) end def array(node) nodeMustBe(node, "array") - hasOnlyOneChild(node, "data") - data(node.firstChild) + hasOnlyOneChild(node, "data") + data(node.firstChild) end def data(node) @@ -325,15 +325,15 @@ module XMLRPC node.childNodes.to_a.collect do |val| value(val) - end + end end def param(node) nodeMustBe(node, "param") hasOnlyOneChild(node, "value") - value(node.firstChild) + value(node.firstChild) end - + def methodResponse(node) nodeMustBe(node, "methodResponse") hasOnlyOneChild(node, %w(params fault)) @@ -341,7 +341,7 @@ module XMLRPC case child.nodeName when "params" - [ true, params(child,false) ] + [ true, params(child,false) ] when "fault" [ false, fault(child) ] else @@ -353,13 +353,13 @@ module XMLRPC def methodName(node) nodeMustBe(node, "methodName") hasOnlyOneChild(node) - text(node.firstChild) + text(node.firstChild) end def params(node, call=true) nodeMustBe(node, "params") - if call + if call node.childNodes.to_a.collect do |n| param(n) end @@ -372,7 +372,7 @@ module XMLRPC def fault(node) nodeMustBe(node, "fault") hasOnlyOneChild(node, "value") - f = value(node.firstChild) + f = value(node.firstChild) Convert.fault(f) end @@ -388,13 +388,13 @@ module XMLRPC end def struct(node) - nodeMustBe(node, "struct") + nodeMustBe(node, "struct") hash = {} node.childNodes.to_a.each do |me| - n, v = member(me) + n, v = member(me) hash[n] = v - end + end Convert.struct(hash) end @@ -403,9 +403,9 @@ module XMLRPC def value(node) nodeMustBe(node, "value") nodes = node.childNodes.to_a.size - if nodes == 0 + if nodes == 0 return "" - elsif nodes > 1 + elsif nodes > 1 raise "wrong xml-rpc (size)" end @@ -423,14 +423,14 @@ module XMLRPC when "dateTime.iso8601" then dateTime(child) when "base64" then base64(child) when "struct" then struct(child) - when "array" then array(child) - when "nil" + when "array" then array(child) + when "nil" if Config::ENABLE_NIL_PARSER v_nil(child) else raise "wrong/unknown XML-RPC type 'nil'" end - else + else raise "wrong/unknown XML-RPC type" end else @@ -441,7 +441,7 @@ module XMLRPC def methodCall(node) nodeMustBe(node, "methodCall") - assert( (1..2).include?( node.childNodes.to_a.size ) ) + assert( (1..2).include?( node.childNodes.to_a.size ) ) name = methodName(node[0]) if node.childNodes.to_a.size == 2 then @@ -461,7 +461,7 @@ module XMLRPC raise "No valid method response!" if parser.method_name != nil if parser.fault != nil # is a fault structure - [false, parser.fault] + [false, parser.fault] else # is a normal return value raise "Missing return value!" if parser.params.size == 0 @@ -508,7 +508,7 @@ module XMLRPC @value = nil when "nil" raise "wrong/unknown XML-RPC type 'nil'" unless Config::ENABLE_NIL_PARSER - @value = :nil + @value = :nil when "array" @val_stack << @values @values = [] @@ -517,7 +517,7 @@ module XMLRPC @name = [] @structs << @struct - @struct = {} + @struct = {} end end @@ -538,7 +538,7 @@ module XMLRPC @value = Convert.base64(@data) when "value" @value = @data if @value.nil? - @values << (@value == :nil ? nil : @value) + @values << (@value == :nil ? nil : @value) when "array" @value = @values @values = @val_stack.pop @@ -548,9 +548,9 @@ module XMLRPC @name = @names.pop @struct = @structs.pop when "name" - @name[0] = @data + @name[0] = @data when "member" - @struct[@name[0]] = @values.pop + @struct[@name[0]] = @values.pop when "param" @params << @values[0] @@ -560,7 +560,7 @@ module XMLRPC @fault = Convert.fault(@values[0]) when "methodName" - @method_name = @data + @method_name = @data end @data = nil @@ -592,7 +592,7 @@ module XMLRPC @parser_class = XMLRPCParser end - class XMLRPCParser + class XMLRPCParser include StreamParserMixin def parse(str) @@ -620,9 +620,9 @@ module XMLRPC def initialize require "xmltreebuilder" - # The new XMLParser library (0.6.2+) uses a slightly different DOM implementation. + # The new XMLParser library (0.6.2+) uses a slightly different DOM implementation. # The following code removes the differences between both versions. - if defined? XML::DOM::Builder + if defined? XML::DOM::Builder return if defined? XML::DOM::Node::DOCUMENT # code below has been already executed klass = XML::DOM::Node klass.const_set("DOCUMENT", klass::DOCUMENT_NODE) @@ -637,8 +637,8 @@ module XMLRPC def _nodeType(node) tp = node.nodeType if tp == XML::SimpleTree::Node::TEXT then :TEXT - elsif tp == XML::SimpleTree::Node::COMMENT then :COMMENT - elsif tp == XML::SimpleTree::Node::ELEMENT then :ELEMENT + elsif tp == XML::SimpleTree::Node::COMMENT then :COMMENT + elsif tp == XML::SimpleTree::Node::ELEMENT then :ELEMENT else :ELSE end end @@ -647,14 +647,14 @@ module XMLRPC def methodResponse_document(node) assert( node.nodeType == XML::SimpleTree::Node::DOCUMENT ) hasOnlyOneChild(node, "methodResponse") - + methodResponse(node.firstChild) end def methodCall_document(node) assert( node.nodeType == XML::SimpleTree::Node::DOCUMENT ) hasOnlyOneChild(node, "methodCall") - + methodCall(node.firstChild) end @@ -688,7 +688,7 @@ module XMLRPC end def createCleanedTree(str) - doc = ::NQXML::TreeParser.new(str).document.rootNode + doc = ::NQXML::TreeParser.new(str).document.rootNode removeWhitespacesAndComments(doc) doc end @@ -701,7 +701,7 @@ module XMLRPC @parser_class = StreamListener end - class StreamListener + class StreamListener include StreamParserMixin alias :tag_start :startElement @@ -716,7 +716,7 @@ module XMLRPC def parse(str) parser = REXML::Document.parse_stream(str, self) end - end + end end # --------------------------------------------------------------------------- @@ -751,7 +751,7 @@ module XMLRPC startElement(name) endElement(name) end - + def on_chardata(str) character(str) end @@ -784,7 +784,7 @@ module XMLRPC # valid_name? # valid_chardata? # valid_char? - # parse_error + # parse_error end end @@ -792,8 +792,8 @@ module XMLRPC XMLParser = XMLTreeParser NQXMLParser = NQXMLTreeParser - Classes = [XMLStreamParser, XMLTreeParser, - NQXMLStreamParser, NQXMLTreeParser, + Classes = [XMLStreamParser, XMLTreeParser, + NQXMLStreamParser, NQXMLTreeParser, REXMLStreamParser, XMLScanStreamParser] # yields an instance of each installed parser diff --git a/lib/xmlrpc/server.rb b/lib/xmlrpc/server.rb index 131173fa7..6b5c5d425 100644 --- a/lib/xmlrpc/server.rb +++ b/lib/xmlrpc/server.rb @@ -14,23 +14,23 @@ Released under the same term of license as Ruby. = XMLRPC::BasicServer == Description Is the base class for all XML-RPC server-types (CGI, standalone). -You can add handler and set a default handler. +You can add handler and set a default handler. Do not use this server, as this is/should be an abstract class. === How the method to call is found -The arity (number of accepted arguments) of a handler (method or (({Proc})) object) is -compared to the given arguments submitted by the client for a RPC ((-Remote Procedure Call-)). -A handler is only called if it accepts the number of arguments, otherwise the search -for another handler will go on. When at the end no handler was found, +The arity (number of accepted arguments) of a handler (method or (({Proc})) object) is +compared to the given arguments submitted by the client for a RPC ((-Remote Procedure Call-)). +A handler is only called if it accepts the number of arguments, otherwise the search +for another handler will go on. When at the end no handler was found, the (()) will be called. With this technique it is possible to do overloading by number of parameters, but only for (({Proc})) handler, because you cannot define two methods of the same name in -the same class. +the same class. == Class Methods --- XMLRPC::BasicServer.new( class_delim="." ) - Creates a new (({XMLRPC::BasicServer})) instance, which should not be + Creates a new (({XMLRPC::BasicServer})) instance, which should not be done, because (({XMLRPC::BasicServer})) is an abstract class. This method should be called from a subclass indirectly by a (({super})) call in the method (({initialize})). The paramter ((|class_delim|)) is used @@ -40,24 +40,24 @@ the same class. == Instance Methods --- XMLRPC::BasicServer#add_handler( name, signature=nil, help=nil ) { aBlock } Adds ((|aBlock|)) to the list of handlers, with ((|name|)) as the name of the method. - Parameters ((|signature|)) and ((|help|)) are used by the Introspection method if specified, - where ((|signature|)) is either an Array containing strings each representing a type of it's - signature (the first is the return value) or an Array of Arrays if the method has multiple + Parameters ((|signature|)) and ((|help|)) are used by the Introspection method if specified, + where ((|signature|)) is either an Array containing strings each representing a type of it's + signature (the first is the return value) or an Array of Arrays if the method has multiple signatures. Value type-names are "int, boolean, double, string, dateTime.iso8601, base64, array, struct". Parameter ((|help|)) is a String with informations about how to call this method etc. A handler method or code-block can return the types listed at - (()). - When a method fails, it can tell it the client by throwing an + (()). + When a method fails, it can tell it the client by throwing an (({XMLRPC::FaultException})) like in this example: s.add_handler("michael.div") do |a,b| if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else - a / b + a / b end - end + end The client gets in the case of (({b==0})) an object back of type (({XMLRPC::FaultException})) that has a ((|faultCode|)) and ((|faultString|)) field. @@ -67,10 +67,10 @@ the same class. To add an object write: server.add_handler("michael", MyHandlerClass.new) All public methods of (({MyHandlerClass})) are accessible to - the XML-RPC clients by (('michael."name of method"')). This is - where the ((|class_delim|)) in (()) - has it's role, a XML-RPC method-name is defined by - ((|prefix|)) + ((|class_delim|)) + (('"name of method"')). + the XML-RPC clients by (('michael."name of method"')). This is + where the ((|class_delim|)) in (()) + has it's role, a XML-RPC method-name is defined by + ((|prefix|)) + ((|class_delim|)) + (('"name of method"')). --- XMLRPC::BasicServer#add_handler( interface, obj ) This is the third form of (()). @@ -91,11 +91,11 @@ the same class. It is a (({Proc})) object or (({nil})). --- XMLRPC::BasicServer#set_default_handler ( &handler ) - Sets ((|handler|)) as the default-handler, which is called when + Sets ((|handler|)) as the default-handler, which is called when no handler for a method-name is found. ((|handler|)) is a code-block. The default-handler is called with the (XML-RPC) method-name as first argument, and the other arguments are the parameters given by the client-call. - + If no block is specified the default of (({XMLRPC::BasicServer})) is used, which raises a XMLRPC::FaultException saying "method missing". @@ -103,7 +103,7 @@ the same class. --- XMLRPC::BasicServer#set_writer( writer ) Sets the XML writer to use for generating XML output. Should be an instance of a class from module (({XMLRPC::XMLWriter})). - If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. + If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used. --- XMLRPC::BasicServer#set_parser( parser ) Sets the XML parser to use for parsing XML documents. @@ -111,7 +111,7 @@ the same class. If this method is not called, then (({XMLRPC::Config::DEFAULT_PARSER})) is used. --- XMLRPC::BasicServer#add_introspection - Adds the introspection handlers "system.listMethods", "system.methodSignature" and "system.methodHelp", + Adds the introspection handlers "system.listMethods", "system.methodSignature" and "system.methodHelp", where only the first one works. --- XMLRPC::BasicServer#add_multicall @@ -123,7 +123,7 @@ the same class. --- XMLRPC::BasicServer#set_service_hook ( &handler ) A service-hook is called for each service request (RPC). You can use a service-hook for example to wrap existing methods and catch exceptions of them or - convert values to values recognized by XMLRPC. You can disable it by passing (({nil})) as parameter + convert values to values recognized by XMLRPC. You can disable it by passing (({nil})) as parameter ((|handler|)) . The service-hook is called with a (({Proc})) object and with the parameters for this (({Proc})). @@ -132,7 +132,7 @@ the same class. server.set_service_hook {|obj, *args| begin ret = obj.call(*args) # call the original service-method - # could convert the return value + # could convert the return value resuce # rescue exceptions end @@ -157,7 +157,7 @@ class BasicServer include ParserWriterChooseMixin include ParseContentType - ERR_METHOD_MISSING = 1 + ERR_METHOD_MISSING = 1 ERR_UNCAUGHT_EXCEPTION = 2 ERR_MC_WRONG_PARAM = 3 ERR_MC_MISSING_PARAMS = 4 @@ -169,7 +169,7 @@ class BasicServer def initialize(class_delim=".") @handler = [] - @default_handler = nil + @default_handler = nil @service_hook = nil @class_delim = class_delim @@ -183,7 +183,7 @@ class BasicServer def add_handler(prefix, obj_or_signature=nil, help=nil, &block) if block_given? # proc-handler - @handler << [prefix, block, obj_or_signature, help] + @handler << [prefix, block, obj_or_signature, help] else if prefix.kind_of? String # class-handler @@ -208,7 +208,7 @@ class BasicServer @service_hook = handler self end - + def get_default_handler @default_handler end @@ -216,18 +216,18 @@ class BasicServer def set_default_handler (&handler) @default_handler = handler self - end + end def add_multicall add_handler("system.multicall", %w(array array), "Multicall Extension") do |arrStructs| - unless arrStructs.is_a? Array + unless arrStructs.is_a? Array raise XMLRPC::FaultException.new(ERR_MC_WRONG_PARAM, "system.multicall expects an array") end arrStructs.collect {|call| if call.is_a? Hash methodName = call["methodName"] - params = call["params"] + params = call["params"] if params.nil? multicall_fault(ERR_MC_MISSING_PARAMS, "Missing params") @@ -246,16 +246,16 @@ class BasicServer [val] else # exception - multicall_fault(val.faultCode, val.faultString) + multicall_fault(val.faultCode, val.faultString) end end end - end - + end + else multicall_fault(ERR_MC_EXPECTED_STRUCT, "system.multicall expected struct") end - } + } end # end add_handler self end @@ -284,7 +284,7 @@ class BasicServer sig.each {|s| sigs << s} else # sig is a single signature, e.g. ["array"] - sigs << sig + sigs << sig end end end @@ -292,11 +292,11 @@ class BasicServer end add_handler("system.methodHelp", %w(string string), "Returns help on using this method") do |meth| - help = nil + help = nil @handler.each do |name, obj, sig, hlp| - if obj.kind_of? Proc and name == meth + if obj.kind_of? Proc and name == meth help = hlp - break + break end end help || "" @@ -306,18 +306,18 @@ class BasicServer end - + def process(data) - method, params = parser().parseMethodCall(data) + method, params = parser().parseMethodCall(data) handle(method, *params) end - + private # -------------------------------------------------------------- def multicall_fault(nr, str) {"faultCode" => nr, "faultString" => str} end - + # # method dispatch # @@ -333,17 +333,17 @@ class BasicServer if check_arity(obj, args.size) if @service_hook.nil? - return obj.call(*args) + return obj.call(*args) else return @service_hook.call(obj, *args) end end - end - + end + if @default_handler.nil? raise XMLRPC::FaultException.new(ERR_METHOD_MISSING, "Method #{methodname} missing or wrong number of parameters!") else - @default_handler.call(methodname, *args) + @default_handler.call(methodname, *args) end end @@ -357,7 +357,7 @@ class BasicServer if ary >= 0 n_args == ary else - n_args >= (ary+1).abs + n_args >= (ary+1).abs end end @@ -366,8 +366,8 @@ class BasicServer def call_method(methodname, *args) begin [true, dispatch(methodname, *args)] - rescue XMLRPC::FaultException => e - [false, e] + rescue XMLRPC::FaultException => e + [false, e] rescue Exception => e [false, XMLRPC::FaultException.new(ERR_UNCAUGHT_EXCEPTION, "Uncaught exception #{e.message} in method #{methodname}")] end @@ -388,8 +388,8 @@ end = XMLRPC::CGIServer == Synopsis require "xmlrpc/server" - - s = XMLRPC::CGIServer.new + + s = XMLRPC::CGIServer.new s.add_handler("michael.add") do |a,b| a + b @@ -399,15 +399,15 @@ end if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else - a / b + a / b end - end + end s.set_default_handler do |name, *args| raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + " or wrong number of parameters!") end - + s.serve == Description @@ -419,7 +419,7 @@ Implements a CGI-based XML-RPC server. == Class Methods --- XMLRPC::CGIServer.new( *a ) Creates a new (({XMLRPC::CGIServer})) instance. All parameters given - are by-passed to (()). You can only create + are by-passed to (()). You can only create ((*one*)) (({XMLRPC::CGIServer})) instance, because more than one makes no sense. @@ -427,7 +427,7 @@ Implements a CGI-based XML-RPC server. --- XMLRPC::CGIServer#serve Call this after you have added all you handlers to the server. This method processes a XML-RPC methodCall and sends the answer - back to the client. + back to the client. Make sure that you don't write to standard-output in a handler, or in any other part of your program, this would case a CGI-based server to fail! =end @@ -443,14 +443,14 @@ class CGIServer < BasicServer def initialize(*a) super(*a) end - + def serve catch(:exit_serve) { length = ENV['CONTENT_LENGTH'].to_i - http_error(405, "Method Not Allowed") unless ENV['REQUEST_METHOD'] == "POST" + http_error(405, "Method Not Allowed") unless ENV['REQUEST_METHOD'] == "POST" http_error(400, "Bad Request") unless parse_content_type(ENV['CONTENT_TYPE']).first == "text/xml" - http_error(411, "Length Required") unless length > 0 + http_error(411, "Length Required") unless length > 0 # TODO: do we need a call to binmode? $stdin.binmode if $stdin.respond_to? :binmode @@ -467,7 +467,7 @@ class CGIServer < BasicServer def http_error(status, message) err = "#{status} #{message}" - msg = <<-"MSGEND" + msg = <<-"MSGEND" #{err} @@ -487,7 +487,7 @@ class CGIServer < BasicServer h = {} header.each {|key, value| h[key.to_s.capitalize] = value} h['Status'] ||= "200 OK" - h['Content-length'] ||= body.size.to_s + h['Content-length'] ||= body.size.to_s str = "" h.each {|key, value| str << "#{key}: #{value}\r\n"} @@ -507,7 +507,7 @@ Use it in the same way as CGIServer! == Superclass (()) -=end +=end class ModRubyServer < BasicServer @@ -523,9 +523,9 @@ class ModRubyServer < BasicServer length = header['Content-length'].to_i - http_error(405, "Method Not Allowed") unless @ap.request_method == "POST" + http_error(405, "Method Not Allowed") unless @ap.request_method == "POST" http_error(400, "Bad Request") unless parse_content_type(header['Content-type']).first == "text/xml" - http_error(411, "Length Required") unless length > 0 + http_error(411, "Length Required") unless length > 0 # TODO: do we need a call to binmode? @ap.binmode @@ -542,7 +542,7 @@ class ModRubyServer < BasicServer def http_error(status, message) err = "#{status} #{message}" - msg = <<-"MSGEND" + msg = <<-"MSGEND" #{err} @@ -562,12 +562,12 @@ class ModRubyServer < BasicServer h = {} header.each {|key, value| h[key.to_s.capitalize] = value} h['Status'] ||= "200 OK" - h['Content-length'] ||= body.size.to_s + h['Content-length'] ||= body.size.to_s h.each {|key, value| @ap.headers_out[key] = value } - @ap.content_type = h["Content-type"] - @ap.status = status.to_i - @ap.send_http_header + @ap.content_type = h["Content-type"] + @ap.status = status.to_i + @ap.send_http_header @ap.print body end @@ -578,8 +578,8 @@ end = XMLRPC::Server == Synopsis require "xmlrpc/server" - - s = XMLRPC::Server.new(8080) + + s = XMLRPC::Server.new(8080) s.add_handler("michael.add") do |a,b| a + b @@ -589,15 +589,15 @@ end if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else - a / b + a / b end - end + end s.set_default_handler do |name, *args| raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + " or wrong number of parameters!") end - + s.serve == Description @@ -610,13 +610,13 @@ program. == Class Methods --- XMLRPC::Server.new( port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a ) Creates a new (({XMLRPC::Server})) instance, which is a XML-RPC server listening on - port ((|port|)) and accepts requests for the host ((|host|)), which is by default only the localhost. + port ((|port|)) and accepts requests for the host ((|host|)), which is by default only the localhost. The server is not started, to start it you have to call (()). Parameters ((|audit|)) and ((|debug|)) are obsolete! - All additionally given parameters in ((|*a|)) are by-passed to (()). - + All additionally given parameters in ((|*a|)) are by-passed to (()). + == Instance Methods --- XMLRPC::Server#serve Call this after you have added all you handlers to the server. @@ -624,7 +624,7 @@ program. --- XMLRPC::Server#shutdown Stops and shuts the server down. - + =end class WEBrickServlet < BasicServer; end # forward declaration @@ -634,22 +634,22 @@ class Server < WEBrickServlet def initialize(port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a) super(*a) require 'webrick' - @server = WEBrick::HTTPServer.new(:Port => port, :BindAddress => host, :MaxClients => maxConnections, + @server = WEBrick::HTTPServer.new(:Port => port, :BindAddress => host, :MaxClients => maxConnections, :Logger => WEBrick::Log.new(stdlog)) @server.mount("/", self) end - + def serve signals = %w[INT TERM HUP] & Signal.list.keys signals.each { |signal| trap(signal) { @server.shutdown } } @server.start end - + def shutdown @server.shutdown end - + end =begin @@ -668,16 +668,16 @@ end if b == 0 raise XMLRPC::FaultException.new(1, "division by zero") else - a / b + a / b end - end + end s.set_default_handler do |name, *args| raise XMLRPC::FaultException.new(-99, "Method #{name} missing" + " or wrong number of parameters!") end - httpserver = WEBrick::HTTPServer.new(:Port => 8080) + httpserver = WEBrick::HTTPServer.new(:Port => 8080) httpserver.mount("/RPC2", s) trap("HUP") { httpserver.shutdown } # use 1 instead of "HUP" on Windows httpserver.start @@ -691,7 +691,7 @@ end --- XMLRPC::WEBrickServlet#get_valid_ip Return the via method (()) specified valid IP addresses. - + == Description Implements a servlet for use with WEBrick, a pure Ruby (HTTP-) server framework. @@ -707,10 +707,10 @@ class WEBrickServlet < BasicServer @valid_ip = nil end - # deprecated from WEBrick/1.2.2. + # deprecated from WEBrick/1.2.2. # but does not break anything. def require_path_info? - false + false end def get_instance(config, *options) @@ -732,7 +732,7 @@ class WEBrickServlet < BasicServer def service(request, response) - if @valid_ip + if @valid_ip raise WEBrick::HTTPStatus::Forbidden unless @valid_ip.any? { |ip| request.peeraddr[3] =~ ip } end @@ -741,9 +741,9 @@ class WEBrickServlet < BasicServer "unsupported method `#{request.request_method}'." end - if parse_content_type(request['Content-type']).first != "text/xml" + if parse_content_type(request['Content-type']).first != "text/xml" raise WEBrick::HTTPStatus::BadRequest - end + end length = (request['Content-length'] || 0).to_i @@ -756,14 +756,14 @@ class WEBrickServlet < BasicServer end resp = process(data) - if resp.nil? or resp.size <= 0 + if resp.nil? or resp.size <= 0 raise WEBrick::HTTPStatus::InternalServerError end response.status = 200 response['Content-Length'] = resp.size response['Content-Type'] = "text/xml; charset=utf-8" - response.body = resp + response.body = resp end end @@ -773,6 +773,6 @@ end # module XMLRPC =begin = History - $Id$ + $Id$ =end diff --git a/lib/xmlrpc/utils.rb b/lib/xmlrpc/utils.rb index 4c2b63c9c..60d4ef5d9 100644 --- a/lib/xmlrpc/utils.rb +++ b/lib/xmlrpc/utils.rb @@ -1,12 +1,12 @@ # # Defines ParserWriterChooseMixin, which makes it possible to choose a # different XML writer and/or XML parser then the default one. -# The Mixin is used in client.rb (class Client) and server.rb (class +# The Mixin is used in client.rb (class Client) and server.rb (class # BasicServer) -# +# # Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de) # -# $Id$ +# $Id$ # module XMLRPC @@ -15,7 +15,7 @@ module XMLRPC # This module enables a user-class to be marshalled # by XML-RPC for Ruby into a Hash, with one additional # key/value pair "___class___" => ClassName - # + # module Marshallable end @@ -72,9 +72,9 @@ module XMLRPC mname = nil sig = [sig] if sig.kind_of? String - sig = sig.collect do |s| + sig = sig.collect do |s| name, si = parse_sig(s) - raise "Wrong signatures!" if mname != nil and name != mname + raise "Wrong signatures!" if mname != nil and name != mname mname = name si end @@ -83,12 +83,12 @@ module XMLRPC end private # --------------------------------- - + def parse_sig(sig) # sig is a String if sig =~ /^\s*(\w+)\s+([^(]+)(\(([^)]*)\))?\s*$/ params = [$1] - name = $2.strip + name = $2.strip $4.split(",").each {|i| params << i.strip} if $4 != nil return name, params else @@ -109,10 +109,10 @@ module XMLRPC instance_eval(&p) end - def get_methods(obj, delim=".") + def get_methods(obj, delim=".") prefix = @prefix + delim - @methods.collect { |name, meth, sig, help| - [prefix + name, obj.method(meth).to_proc, sig, help] + @methods.collect { |name, meth, sig, help| + [prefix + name, obj.method(meth).to_proc, sig, help] } end @@ -132,7 +132,7 @@ module XMLRPC def get_methods(obj, delim=".") prefix = @prefix + delim obj.class.public_instance_methods(false).collect { |name| - [prefix + name, obj.method(name).to_proc, nil, nil] + [prefix + name, obj.method(name).to_proc, nil, nil] } end end @@ -141,16 +141,16 @@ module XMLRPC end # module Service - # + # # short-form to create a Service::Interface # def self.interface(prefix, &p) - Service::Interface.new(prefix, &p) + Service::Interface.new(prefix, &p) end # short-cut for creating a PublicInstanceMethodsInterface def self.iPIMethods(prefix) - Service::PublicInstanceMethodsInterface.new(prefix) + Service::PublicInstanceMethodsInterface.new(prefix) end -- cgit