Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. SIMPLE JAVA AND .NET May 2006 SOA INTEROPERABILITY A discussion on REST and a simple, low dependency solution to interop between Java and .Net over the wire. By Paul Hammant and Ian Cartwright In this article, we intend to show how simple tech- forced a document approach and our java tools assumed nology coupled with a document-centric approach can the opposite, RPC. We also found issues with mixtures of be used to deliver valuable business services without the namespaces, inclusion of schemas and tools splitting the use of proprietary middle-ware or the complexities of WSDL into separate parts. In short the technology starts the web services stack. We take our inspiration from the to distract from the actual problem we are trying to REST architectural style, and the ability to move XML solve. over HTTP. To compound the issue, we also found inconsisten- cies within tools for web services. For example versions of Internet Information Server and Web Services En- The Web Service way hancements were only partially compatible with each The best way to introduce this approach is to con- other or their Java equivalents for automatically pub- trast it with a simple web service example. Imagine a lished WSDL documents. simple Weather Service exposing a web method called ‘WeatherQuery’ that returned the temperature and pres- .Net Java sure wrapped in an Server(s) Server(s) object. In most cases .Net people take existing code Client ! some and use a tool to expose Java a method and generate Client some some some WSDL. If you believe the We became very weary of something that may be hype all we need to do kludged to work today, but may break tomorrow if a now is point an equiva- more complicated web method were needed in later ver- lent Java tool at the sion of the service. WSDL and generate a stub-method. A more RESTful style Unfortunately things are not quite that simple, The above approach made two key assumptions: WSDL is a broad standard, in fact broad enough to be firstly that just exposing an existing method call would open to interpretation. In our case we found .Net en- give us a meaningful service, and secondly that tools This paper published in (
  2. 2. Simple Java & .NET Interop May 2006 would make getting at that service via web services triv- XStream xs = new XStream(); ial. Instead of thinking about the parameters of the String reqXML = xs.toXML(req); request and the type of the return, we can think of the request as a document that embodies the type of request Object req = xs.fromXML(reqXML); along with its parameters. Think of that document as Our Weather service currently only facilitates the something that represents part of the contract for the exchange of documents, business process you are trying to model. If we take the and as a consequence, we same WeatherQuery method, and describe it in an ele- could use plain HTTP ment normal XML we might see something like - instead of Web Services. With this shift, we are <WeatherQuery> <locn>chicago</locn> able to think about multi- <date>2006 02 12 18:52</date> ple document types using </WeatherQuery> the same entry-point into the system giving us a Also as a document, the return type may look like - more extensible approach <WeatherDetails> .Net Java <locn>chicago</locn> Server(s) Server(s) <date>2006 02 12 18:52</date> <temp>32</temp> .Net <pressure>30</pressure> Client ! ! </WeatherDetails> Java Client ! ! Now we can define a simple class design that repre- sents the same fields as the documents - . public class WeatherQuery { private String locn; Coding the Java server private Date date; The technologies we used for a Java implementation // .. getters & setters // or properties .. of the service are that of the serialization library } XStream, and any servlet container, as we chose to host public class WeatherDetails { the services inside a Servlet. XStream is open source: the private String locn; servlet container could be any of WebLogic, WebSphere, JBoss, Geronimo, Orion or just Resin, Tomcat or Jetty if private Date date; less of the E in J2EE is required. private int temp; Our servlet should implement the doPost() rather private int pressure; // .. getters & setters .. than doGet() method. We did not use a name/value pair } for the XML: we simply used the entire POST body, which is a little outside of the HTTP specification. It is a The interesting thing about these two documents is matter of preference though - as long as its the same on that they are relatively easy to serialize and deserialize in client and server. both .Net and Java. For .Net, the built-in XML serializa- When a request comes in, we deserialize the XML tion (with some annotations) does the job well. Here is into a command object using XStream and appropri- the C# for the same classes - ately handle it. [XmlRoot("WeatherQuery")] public class WeatherQuery { Coding the .Net server [XmlElement("locn")] private string locn; The server technologies for .Net are simpler - we [XmlElement("date")] just used Internet Information Server (IIS) and .Net’s private DateTime date; built-in XML serialization. The built-in serialization // property: get{}& set{} .. requires C# attributes to mark fields to as XML ele- } ments rather than XML attributes. There is a .Net port of XStream that makes things simpler still, but we have Java is not so lucky. It has no built in tools for XML not experimented with that, and we have heard of an- serialization: however there is an open source tool called other port about to be launched on the open source XStream ( ) that is perfect world. for the job - This paper published in ( 2
  3. 3. Simple Java & .NET Interop May 2006 Coding the Java client documents. An API change, as well as being ‘extra field’ For the Java client in additional to XStream we use level, could also be more far reaching: Apache’s HttpClient library (and its dependencies). See <WeatherQuery2> <locn> The HttpClient library is quite simple to use and <city>chicago</city> allows a POST operation to be programmatically con- <zip>60661</zip> </locn> structed before execution. Remember, the POST body is entirely XML delivered by XStream as either name/ <altitude>22000</altitude> value pairs or the entire request without that HTTP con- <date>2006 02 12 18:52</date> struct. The former may be attractive if you want to cre- </WeatherQuery2> ate a test web form for the service. It may be better to encode the version number into the URL though: Coding the .Net client For the .Net client you’ll need just the framework and this can be either version 1.1 or 2.0. For the POST operation, we can use the built-in Wrapping it in Web Services WebRequest class and and the built-in serialization. There is nothing to stop you from mounting a sec- ond service on the same server to accept formal Web- service requests for the same service. All you would need Making it extensible and compatible is a single WSDL specified method like - The beauty of simply POSTing XML that repre- sents commands is that we can add more commands String weatherCmd(String xmlRe- later without changing our messages implementation. quest) The server can decide whether it can deal with the XML Your tool choices are WSE 2.0 /3.0 for .Net or at runtime - Glue, AXIS, JAX-WS, or <PostWeather> some built-in adapter for <locn>chicago</locn> one of the J2EE contain- <date>2006 02 12 21:00</date> ers for Java. The SOAP <temp>32</temp> encoded method could </PostWeather> simply delegate to the same demarshal-execute- A good solution to the multitude of potential types marshal code developed is to register a handler for each type, helping avoid a for the pure REST im- large if/else or switch/case block - plementation. You may map.register(”WeatherQuery”, be doing this to side-step new WeatherQueryHandler()); the corporate standards When using XML there is a temptation to over-rely police. on the related schema, We have to be careful to under- stand the difference between schema validation and the Extending it to Messaging information a consumer might actually need. Leveraging Tibco Rendezvous, we were able to send Schema validation, if performed at runtime, gives a the same XML representations of requests around for developer a sense of safety that is not appropriate. A execution against an implicitly asynchronous service. We failure may still happen - the wrong XML could be sent. did not try MQ Series but it should work too. But what happens? There would be a schema invalid For our example this means the request for weather exception message raised. Alternatively with the XML details is not going to be immediately satisfied. Instead, mapped to a class’s design, there would either be a cor- some time later, a response may come back. It is a huge rect object, or it would be missing some fields. In that shift that might mean changing or abandoning some of situation, a real exception could be thrown with a real the simple designs you might have for an API. For ex- reason, that could easily be turned into a clear XML ample, the following facade method may have to go : reply message for the consumer. The key difference is WeatherDetails weatherQuery that an exception is raised only if required information is (String locn, Date date) missing – anything else could change. Inherently in this design, there is the possibility that In its place two interfaces, each with a single elements could be added to the XML (fields to the class) method, may be appropriate - that make it possible to move the API notionally forward a notch. With some careful testing, the service could support consumers sending older versions of the request This paper published in ( 3
  4. 4. Simple Java & .NET Interop May 2006 void weatherQuery ... (String locn, Date date) <xs:element name=”WeatherQuery”> void acceptWeather <cs:complexType> (WeatherDetails details) <xs:all> <xs:element name=”locn” There is lots to learn about messaging patterns, type=”xs:string”/> which we’ll not be going <xs:element name=”date” type=”xs:string”/> into here. However, it </xs:all> may be worth noting that </cs:complexType> there are two general </xs:element> designs to consider. The ... first is a queue design, where requests from you Serving both the XSD and the sample XML stati- receive responses directed cally could be a good idea (the authors differ on the only to you. The second XSD as it happens). Served statically means that the API is a multicast concept, can be queried by a human with a web browser - where there are events on the wire that are being sent to many subscribers (pub/sub). Also, implic- Remember, both the XSD and sample document itly, there is the possibility are optional and could easily be generated too. that you could engineer a queue to continue streaming revised details Recap and Key Message over time. If you are The magic here was to use Codehaus’ XStream to familiar with JMS, Ren- participate in a element-normal document exchange dezvous works slightly with .Net via HTTP-POST operation rather than GET. differently in this respect. Just about everything else has been blogged and white- papered before. Choosing XStream meant that the ‘specification’ for the message was in Java and/or C# Whither WSDL and not an XML based design as is usually encountered with WS-* specs. The producer/consumer design we have coded Also, conventional REST wisdom suggests that trades XML in a simple design. But the specification HTTP-GET is better for encoding the command... checking that is inherent in the discovery phase of a formal Web Services design is missing from ours. We suggest it is not really needed. Instead, and ... especially when the result is cacheable by a web server. wholly in line with Agile thinking, have a comprehensive Perhaps our style is best for communication where at- Continuous Integration suite of integration tests. Your tempts at caching are pointless. There are other advan- service incompatibilities will be discovered before you tages to the GET approach that we have lost with ours. deploy to live. So instead of a complex WSDL specifica- It is more elegant and eminently testable by a humans tion you have a series of unit tests that make assertions with a browser by virtue of a complete URL. It lacks, about the service from both a provider and consumer however, the versatility we get with POST which allows point of view. Anyway, WSDL only flags incompatibili- more than just name/value pairs for parameters; the ties at runtime, when recovery is very hard. Thus is it a XML payload can be arbitrarily complex. There is room false god? for GET and POST, of course, in larger solutions. Schematron is one way of creating such tests in a While writing this paper, we made a suggestion to platform independent way. the XStream team (by way of a patch) that would make To aid debugging and documentation, you may it more able to support attributes where appropriate. want to host some sample documents : They implemented the required functionality and future versions of XStream will be able to support XML at- <WeatherDetails> tributes for more seamless introp with .Net. <locn>AAAAAA</locn> <date>CCYY MM DD HH:MM:SS/date> We also suggested that the approach works with </WeatherDetails> async transports like Tibco RV. Current WS-* spec tools have little to no capabilty in this regard. You could also have an XML Schema (XSD) con- In the end, we are not sure whether this is POST- trolling the document format : REST (PREST) or just good old REST without much caching and URL simplicity and no new coined terms. This paper published in ( 4