Implementing a restful SOA with XML

Source: Internet
Author: User
Tags representational state transfer ruby on rails

What is SOA?

If a company has a large number of applications that are used by staff in different departments who assume different responsibilities, then the service-oriented architecture (oriented Architecture,soa) is appropriate for use. These applications can share functionality, but the combination of features, user interface details, and ease-of-use requirements are different. Like many enterprise architectures, SOA also employs a multilayer model, but it is not just that. In the server, functionality is dispersed across separate services. One client can use one or more of these services, and a service can be used by many clients. The result is a loosely coupled architecture that greatly improves the reusability of existing software.

Common heavy-duty implementations

Common abbreviations
    • API: Application Programming Interface (application program Interface)
    • IT: Information Technology (Information technology)
    • XML: Extensible Markup Language (extensible Markup Language)

SOA is particularly well-suited for large companies, where large companies often have hundreds of applications and lack good integration between applications, so companies need to clean up the IT infrastructure. SOA is a proven practice that is especially effective for large environments. Companies that use SOA can transform legacy applications into services and turn service sets into the backend of modern applications. You can use middleware technology to combine services and access control over specific features in the service. Because the demand for SOA is strongest in large environments, manufacturers of middleware technologies typically focus their products on large and heavy-duty solutions.

SOA and light-weight technologies

The ideas behind SOA are also valuable to small businesses. The setup cost of the heavy-duty solution and the required personnel skills may make small companies dare not try soa-but that is not the answer. For the moment, don't think about heavy implementations, let's examine the basic concepts of SOA:

    • Extracting services from existing or new applications
    • Centralize services for use by many clients

There are few factors that prevent us from using lightweight technology to realize these ideas. You can build a small SOA and gradually extend it. If your company is later developed into a large multinational, you can move to heavy technology at any time.

Back to top of page

What is REST?

SOA is typically implemented with the SOAP protocol, and the service is described by a WSDL (Web services Description Language, Web Service Description Language) document. Although there are many development tools that greatly simplify the processing of soap and WSDL, I still think of them as heavy technology, because soap and WSDL are difficult to handle without using these tools.

You can also implement SOA by sending a simple message via Hypertext Transfer Protocol (HTTP). This is basically how RESTful Web services (RESTful Web service) work. Representational State Transfer (REST, Chinese translation "Representational status transfer". The name REST, pioneered by Roy Fielding, is not a protocol or technology; it is an architectural style. REST is a lightweight alternative to SOAP, which is resource-oriented, not action-oriented. It is often attributed to remote procedures that use HTTP calls GET , POST ,, PUT and DELETE statements. I think this is just the second important step.

The first (and most important) step is to model all resources in the form of URLs. URLs are easy to remember and can access countless Web pages at the same time. At the very least, URLs (such as http://www.ibm.com/developerworks/xml/) are easy to remember if the modeling method is appropriate. If too much attention, GET POST PUT and DELETE , can produce a URL that is not easy to remember, such as http://www.longfakeurl.com/pol_srdm/70612/9,3993.32?id=78688 &lang=cz&st=idx.

In practice, the use of HTTP can be further limited to GET POST two methods, because most browsers support them very well. Can be executed against the http://domain.com/myresources/new POST , in lieu of http://domain.com/myresources execution PUT ; http://domain.com/ Myresources/oldresource/delete is executed to POST replace the Http://domain.com/myresources/oldresource execution DELETE .

REST-style design process

When designing a RESTful Web service, there are four steps to follow:

    1. Determines the resource and its descriptive URL.
    2. Select a data format for the traffic on each URL.
    3. Specify the methods on each resource.
    4. Specifies the returned data and status code.

The following is a detailed design process. Suppose you are a developer of an airline. The company has software for booking flights, as well as components for processing payments (cash and credit cards). It uses software to track parcels, perform internal resource planning, and perform many other tasks.

Suppose the clerk at the airport registry uses a client application that accesses the parcel tracking service and uses a service to assign a seat to the passenger. The ground crew handling the parcel only needs to package the tracking service and does not need any other services. Their clients only allow them to confirm that the packages that have been registered have arrived. They are not allowed to register new parcels.

In this example, we will design a package tracking service. First, decide on the resources: travelers, flights and parcels (note that {id} any number can be filled in wherever it appears):

Select a data format for each resource:

Package:

<bag id= "{id}" >   <traveller id= "{traveller-id}"/> <flight   id= "{Flight-id}"/>   

Flight:

<flight id= "{id}" >   <travellers> <traveller id= "{traveller-id-0}"/> <traveller id= "{ Traveller-id-1} "/> <traveller id=" {traveller-id-2} "/>   </travellers>   <bags> <bag ID = "{bag-id-0}"/> <bag id= "{bag-id-1}"/> <bag id= "{bag-id-2}"/>   

Passengers:

<traveller id= "{id}" >   <flight id= "{flight-id}"/>   <bags> <bag id= "{bag-id-0}"/> < Bag id= "{bag-id-1}"/> <bag id= "{bag-id-2}"/>   

Obviously, this model is too simple. For the current example, only two methods are supported, so this model is sufficient. The registry should be able to register new parcels for passengers. The ground crew should be able to modify the status of the package when it is loaded into the aircraft:

    • Executes on Http://luggagetrackingairlinecompany.com/travellers/{id}/newbag POST , returning an <bag> XML structure.
    • Executes on Http://luggagetracking.airlinecompany.com/bags/{id}/status/{newstatus} POST , returning the modified XML structure.

Use the standard HTTP status as the status code. A successful operation will return 200. If the system cannot find it based on the ID of the resource, it returns 404. Any errors caused by a system failure will return 500.

code example: URL mapping

There are several ways to map URLs to implementation methods. More advanced methods may be more flexible and should be used in larger applications. This small example uses the simplest method: regular expressions. The following is an example of the Post method on Bagservlet, which passes the URL parameter to the underlying servlet. You can find the full servlet code in the download file for this article. Note that the actual underlying service is not implemented here. The following is the example:

protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { C1/>pattern Pattern = Pattern.compile ("^/?. *?/bags/(. *)/status/(. *) $ "); Matcher Matcher = Pattern.matcher (Request.getrequesturi ());  if (Matcher.matches ()) {String Bagid =  matcher.group (1); String newstatus = Matcher.group (2); Bagservice.changebagstatus (Bagid, newstatus); } }          

When this URL is called, the status code 200 is implicitly returned if successful. More to the point, the code returns the XML structure. This example uses the XStream API to convert a Java™ object into an XML structure. This API requires very little configuration and mainly selects the element name based on the field name in the class.

This sample code uses the following simple classes:

Flight:

Package Eu.adraandejonge.restfulsoa;  public class Flight {String id;  

Passengers:

Package Eu.adraandejonge.restfulsoa;  public class Traveller {private String ID;  Public Traveller (String ID) {super (); this.id = ID;}}  

Package:

Package Eu.adraandejonge.restfulsoa;  public class Bag {private string id; private Flight Flight; private Traveller Traveller; private string status;  

Suppose the underlying bagservice returns a package with a flight ID of 1, a passenger ID of 1, and a status of new. Consider the following GET implementation:

protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { C1/>pattern Pattern = Pattern.compile ("^/?. *?/bags/(. *) $ "); Matcher Matcher = Pattern.matcher (Request.getrequesturi ());   if (Matcher.matches ()) {String Bagid = Matcher.group (1);  Bag bag = bagservice.retrievebag (bagid);  XStream XStream = new XStream (); Xstream.alias ("Bag", bag.class); Xstream.alias ("Traveller", Traveller.class); Xstream.alias ("Flight", Flight.class);   Xstream.useattributefor (Bag.class, "id"); Xstream.useattributefor (Traveller.class, "id"); Xstream.useattributefor (Flight.class, "id");  

When you query this URL, it returns the following information:

<bag id= "1" >   <flight id= "1"/>   <traveller id= "1"/>   

Back to top of page

What else can you do?

I chose these sample codes to illustrate that there is no need for a lot of underlying communication and that URLs can implement many functions. For other services, you may need to handle the XML structure that is passed to the REST service. XStream can also help complete this task. For example, to de-serialize the XML structure of a package, you should call:

Applications on the client

So far, this article has discussed the server-side implementation. The code on the client is very similar. Clients can share data classes Flight , Traveller and Bag , and use the XStream API to serialize and de-serialize XML. The only new part of the client is to connect the URL and read the content or send the content. This task is easy to accomplish by using the URL connection provided by the Java class library:

String XML = "<newinput>input</newinput>";  URL url = new URL ("Http://luggagetracking.airlinecompany.com/bags/1/newmethod"); URLConnection connection = Url.openconnection ();  Set POST Connection.setdooutput (true); Writer output = new OutputStreamWriter (Connectiongetoutputstream ()); Output.write (XML); Output.close ();  Display result BufferedReader input = new BufferedReader (New InputStreamReader (Connection.getinputstream ()));  

Interoperability with technologies such as Ruby on Rails

While rest does not have a clear specification of how to implement it, there is a growing number of out-of-the-box support for rest. Therefore, although there are no standards to follow, you need to comply with some conventions. For example, Ruby on Rails provides activeresource. It is easy to connect a rails Web client to a Java REST Web service with minimal overhead if you adhere to rails ' conventions for URLs and output formats.

Scalability and migration to a heavy SOA

As the application environment grows, more and more of the REST implementation details are likely to be abstracted. As growth and abstraction evolve to a certain extent, it may be cost-efficient to move from lightweight technology to heavy-duty SOA technologies. This requires extracting the actual business logic behind the service and repackaging it in a SOAP package in the new environment, which should not be too difficult.

Find opportunities to apply restful SOA

Airlines are just an example of what this article uses. The actual size of the airlines is large, they should be directly using heavy technology. If you work for a small company, you may need to be imaginative in finding the best way to apply SOA and REST principles in practice. Take some time to think about it, and that will bring long-term rewards!

Implementing a restful SOA with XML

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.