Soap programming in ruby

Source: Internet
Author: User
Tags sigint signal soap client

3. Ruby and soap

Simple Object Access Protocol (SOAP) quickly becomes the standard protocol for Remote Procedure Call (RPC. (For more information about soap, see http://www.linuxmagazine.com/2001-10/soap_04.html and http://www.linuxmagazine.com/2002-08/webs_01.html, respectively)

Ruby provides powerful support for soap, both on the client and server. To use soap4r, you only need four parts to create a SOAP request:

  1. An endpoint, or a network address for processing SOAP requests, is generally the code running in the web server environment, but there are also some other soap transmission, including mail.
  2. A namespace defines an environment context and resolves the called method name here.
  3. A method name. The name of the method called by the remote process.
  4. A group of parameters.


UseSoap4rWe need to specify the first two parameters when creating the soap driver, and the third parameter is used to bind the method to the driver, the final parameter is used to call the actually needed method.

 

For example, we have a soap processing a sales order running on the http://my.server.com, we want to access this service on the client, first createSoap: DriverObject. When creating this object, you must specify the namespace and server address (the first two parameters of the method for creating this object are related to the record log. Here we can skip the test rate)

NS  = "urn:ordersService"SVR = "http://my.server.com/orders"drv = SOAP::Driver.new(nil, nil, NS, SVR)

Once this driver is created, we can use its addmethod method to add the name of the method we need to call to the server. The first parameter is the name of this method, the other parameters are the parameter names required for this method. Here, the method name we need to access isOrders_for_product(Note: should it be orders_for ?), Parameter 10 Customer Account and Product Code passed to it. (Ruby does not use WSDL to describe the soap Interface)

 

drv.addMethod("orders_for", "cust_acct","prod_code")

Once everything is done, we can use this method to call the server any number of times:

customers.each do |cust_acct|  products.each do |prod_code|    orders = drv.orders_for(cust_acct, prod_code)    process(orders)  endend

This example also benefits from the dynamic nature of the Ruby language. For example, the orders_for method is dynamically added to the soap driver object, so we can use DRV. orders_for to call this method. In addition, we do not need to define the form of the return value of this method. The soap driver will automatically convert the result obtained from the server to an appropriate Ruby object.

For more details, let's look at a real example. Listing 4 shows how to use soap to obtain query results from the googel search engine. This Code is based on Ian Macdonald'sGoogle. Rb. Before running this program, you need to register it on Google (http://www.google.com/accounts), then get a key, specify the key you get in the third line.

 

 

Listing 4: using soap to query Google

 1   require "soap/driver" 2   ENDPOINT = 'http://api.google.com/search/beta2' 3   NS = 'urn:GoogleSearch' 4   KEY = "get_a_key_from_google" 5 6   fail "Missing query args" if ARGV.empty? 7 8   query = ARGV.join(" ") 910   soap = SOAP::Driver.new(nil, nil, NS, ENDPOINT)11   soap.addMethodWithSOAPAction(12     'doGoogleSearch', NS, 'key', 'q', 'start', 'maxResults', 13       'filter','restrict', 'safeSearch', 'lr', 'ie', 'oe')14   res = soap.doGoogleSearch(15     KEY, query, 0, 10, false, nil, false, nil, 'latin1', 'latin1')1617   puts "Estimated result count: " + res.estimatedTotalResultsCount1819   res.resultElements.each do |entry|20     puts21     puts "#{entry.URL}: #{entry.title}"22     puts entry.snippet23   end

The actual Google query is performed on the Google server by the methodDogooglesearchExecuted, this method receives 10 parameters (for specific meanings of these 10 parameters, refer to Google's web API documentation), but in our example, we only specify the query conditions, and we use the default values for other parameters. In row 3, we added a method to the soap driver.Dogooglesearch, We will call this method in Row 3 to execute a real query.

The results returned by Google are very complex objects. From the perspective of the top layer, the results include some information about the query itself, such as the index values for the start and end, and the conditions used for the query, the time consumed by the query. The query result is in an array. This is the same as the result of the serial number displayed on the Google Page. Each query result record is a complex object. In our example, we only retrieve its title, URL, and part of the text.

 

The soap interface makes our work very simple. It automatically creates an iteration of the result object and creates access methods for various attributes of the returned result object. Then, we can simply use:

res.resultElements.each do |element|  ...end

If you run the program in Listing 4 at the command prompt, the query parameter is "Ruby soap" and the result is as follows:

 

$ ruby google_search.rb ruby languageEstimated result count: 206000http://www.ruby-lang.org/en/: <b>Ruby</b> Home Page  <b>...</b> Japanese Page If you can read this oriental 
<b>language</b>, <br> you can get more information about <b>Ruby</b>.
Site <b>...</b>http://slashdot.org/developers/01/08/11/2211254.shtml: Slashdot
| Progra.... <b>...</b> Programming in the <b>Ruby</b> <b>Language</b>.
<b>...</b> This discussion has<br> been archived. No new comments
can be posted.http://dev.rubycentral.com/faq/rubyfaq.html: The
<b>Ruby Language</b> FAQ The <b>Ruby</b> <b>Language</b> FAQ. Originally by:
Shugo Maeda.<br> Now maintained by Dave Thomas with help
from Andy Hunt. <b>...</b>

(Note: This table is the result after the translator's line breaks. The original content may exceed the width and affect reading)

Writing a SOAP server in ruby is also very simple. All you need to do is to release the interface objects and then release these objects to the servlet of the soap server. The object you write does not need to know anything about soap. For example, listing 5 represents a simple class. There is a simple double method that receives a parameter and returns the result of adding the two parameters.

Listing 5: The file Doubler. RB, the ruby soap doubling class

class Doubler  def double(arg)    arg + arg  endend

To access this method on the SOAP server, we need to assemble it into the namespace of the soap server. In Ruby, the simplest method is to use webrick, the web server toolbox. Combined with the servlet code soaplet. Rb (in the soap4r packageSamples/webrickDirectory), we can use a small amount of code to implement a complete SOAP server. For the code, seeListing 6.

 

Listing 6: A ruby SOAP server

 1   require 'webrick' 2   require 'soaplet' 3   require 'doubler' 4 5   server = WEBrick::HTTPServer.new(:Port => 2001) 6 7   soaplet = SOAP::WEBrickSOAPlet.new 8   soaplet.addServant('urn:doublerService', Doubler.new) 9   server.mount("/doubler", soaplet)1011   trap("INT") { server.shutdown }12   server.start

The first three rows simply introduce the required libraries, soaplet, and double classes. Row 5th is required to create a web server (port 2001 in this example), and line 7th creates a soaplet (a servlet that sends a SOAP request to an object ). Line 3 sets the servlet to a Doubler object, and line 3 maps the soaplet to the/Doubler of the Web server. Line 3 started the server program, but what is the use of Line 3? When you start a webrick service, this server program will process the request and return the result. However, we want our server program to be completely closed, and line 4 is to complete this function, this line registers a processor for processing SIGINT signals to the server. When such a signal is received, the shutdown method of the server is called. In most operating systems, control-C generates a SIGINT signal, therefore, we can control our web servers at the command prompt.

We can use the soap client program in listing 7 to test the server. Row 10th also shows another feature of rescue: This statement first tries to convert the parameter (which is a string when passed) to an integer. If the conversion fails, rescue will capture this exception, and the original parameters are returned. The result is that the parameters that the double method can receive can be integer or string. Let's see what is different when the client is running.

$ ruby soap_client.rb 12 wiki24wikiwiki$

The input parameter is 12, and the result we get is 24. When we pass in the string wiki, we get wikiwiki. Types of polymorphism in ruby are also transmitted to the soap interface. Because the double method is Arg + Arg, if the parameter is an integer, the result of adding two numbers is returned. If the parameter is a string, the result of two string connections is returned.

 

Listing 7: The Doubler soap Client

 1   require "soap/driver" 2 3   SVR = 'http://localhost:2001/doubler' 4   NS  = 'urn:doublerService' 5 6   soap = SOAP::Driver.new(nil, nil, NS, SVR) 7   soap.addMethod('double', 'arg') 8 9   ARGV.each do |arg|10     arg = (Integer(arg) rescue arg)11     puts soap.double(arg)12   end
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.