Saturday, August 29, 2009

Spring Web Services - How to - Article contributed to Javalobby - http://java.dzone.com/articles/spring-ws-how

Spring Webservices encourages a contract first, message oriented approach to creating Webservices. The underlying details are completely under developer control starting from the contract to the marshalling/unmarshalling details to the endpoint handling the request.

Let us start by an example of a simple service to expose as a webservice - call it the MemberService. MemberService exposes one operation “Get Member Details” which returns the details of a member/person, given an identifier.

Creating the contract:

The Contract/WSDL for this service is fairly simple. Let us start by defining the messages and type :

01.<xsd:schema targetNamespace="http://bk.org/memberservice/" elementFormDefault="qualified">
02. <xsd:complexType name="MemberDetailType">
03. <xsd:sequence>
04. <xsd:element name="name" type="xsd:string" />
05. <xsd:element name="phone" type="xsd:string" />
06. <xsd:element name="city" type="xsd:string" />
07. <xsd:element name="state" type="xsd:string" />
08. xsd:sequence>
09. xsd:complexType>
10. <xsd:element name="MemberDetailsRequest">
11. <xsd:complexType>
12. <xsd:sequence>
13. <xsd:element name="id" type="xsd:string" />
14. xsd:sequence>
15. xsd:complexType>
16. xsd:element>
17. <xsd:element name="MemberDetailsResponse">
18. <xsd:complexType>
19. <xsd:sequence>
20. <xsd:element name="memberdetail" type="ms:MemberDetailType" />
21. xsd:sequence>
22. xsd:complexType>
23. xsd:element>
24.xsd:schema>

MemberRequest message comprises of an id to represent the requested members identifier

MemberResponse message comprises of MemberDetail type to represent the details of a member.

A sample payload over the wire would look like this:

1.xml version="1.0"?>
2.<ms:MemberDetailsRequest xmlns:ms="http://bk.org/memberservice/">
3. <ms:id>SAMPLEms:id>
4.ms:MemberDetailsRequest>

and a sample response:

1.<ms:MemberDetailsResponse xmlns:ms="http://bk.org/memberservice/">
2. <ms:memberdetail>
3. <ms:name>testnamems:name>
4. <ms:city>testcityms:city>
5. <ms:phone>testphonems:phone>
6. <ms:state>teststatems:state>
7. ms:memberdetail>
8.ms:MemberDetailsResponse>

The sample request and response can be easily generated by using a tool like SOAP UI –

SOAP UI

Creating an Endpoint:

A Spring-WS endpoint processes the XML message and produces the XML response. Spring provides different Endpoints based on how the XML is to be handled. If you wish to handle raw xml you have the option of implementing AbstractDom4jPayloadEndpoint, AbstractDomPayloadEndpoint, AbstractJDomPayloadEndpoint etc, based on how the raw xml needs to be handled. If you wish to handle the XML message as an object representation then you can implement the AbstractMarshallingPayloadEndpoint, which is what I will be using for this example along with JIBX as the XML binding framework for its ease of use and performance.

01.package org.bk.memberservice.endpoint;
02.
03.import org.bk.memberservice.message.MemberDetailsRequest;
04.import org.bk.memberservice.message.MemberDetailsResponse;
05.import org.bk.memberservice.service.MemberManager;
06.import org.bk.memberservice.types.MemberDetail;
07.import org.springframework.ws.server.endpoint.AbstractMarshallingPayloadEndpoint;
08.
09.public class GetMemberDetailsEndpoint extends
10. AbstractMarshallingPayloadEndpoint {
11.
12. private MemberManager memberManager;
13.
14. protected Object invokeInternal(Object requestObject) throws Exception {
15. MemberDetailsRequest request = (MemberDetailsRequest) requestObject;
16. MemberDetail memberDetail = memberManager.getMemberDetails(request
17. .getId());
18. MemberDetailsResponse response = new MemberDetailsResponse(memberDetail);
19. return response;
20.
21. }
22.
23. public void setMemberManager(MemberManager memberManager) {
24. this.memberManager = memberManager;
25. }
26.}
The structure of the Endpoint is very simple, it takes an Object which can be cast to MemberDetailsRequest a holder for the request, and the response is returned as an instance of MemberDetailsResponse, a holder for the response details.

Writing the Object/XML binding:

So we now have the endpoint to process the take in the request Message, process it and respond. The only missing piece is how to transform the raw request xml over the wire to the MemberDetailsRequest object, and on the way back to transform the MemberDetailsResponse object back to XML. This is where Springs Object/XML mapping support comes in. Spring Object/XML mapper provides a simple abstraction over the popular Java XML binding stacks like JAXB, Castor, JiBX, Xstream. In the current example, we will start by defining the binding file for JiBX:

01.xml version="1.0" encoding="UTF-8"?>
02.<binding>
03. <mapping name="MemberDetailsRequest"
04. class="org.bk.memberservice.message.MemberDetailsRequest">
05. <namespace prefix="ms" uri="http://bk.org/memberservice/" default="all"/>
06. <value name="id" field="id" />
07. mapping>
08.
09. <mapping name="MemberDetailsResponse"
10. class="org.bk.memberservice.message.MemberDetailsResponse">
11. <namespace prefix="ms" uri="http://bk.org/memberservice/" default="all"/>
12. <structure name="memberdetail" field="memberDetail"
13. class="org.bk.memberservice.types.MemberDetail">
14. <value name="name" field="name" />
15. <value name="city" field="city" />
16. <value name="phone" field="phone" />
17. <value name="state" field="state" />
18. structure>
19. mapping>
20.binding>

JiBX requires a compile step with the above binding file, this is very easily wired using Maven as the build tool.

Putting it together:

So now all the pieces are in place -

To direct the request to the appropriate endpoint, Spring-WS requires a custom servlet to be set up:

01.<servlet>
02. <servlet-name>memberserviceservlet-name>
03. <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServletservlet-class>
04. <init-param>
05. <param-name>contextConfigLocationparam-name>
06. <param-value>classpath:/applicationContext-memberservice.xmlparam-value>
07. init-param>
08.servlet>
09.
10.<servlet-mapping>
11. <servlet-name>memberserviceservlet-name>
12. <url-pattern>/services/*url-pattern>
13.servlet-mapping>

This would direct all requests starting with serivces/* to be handled by Spring-WS.

The MessageDispatcherServlet would look for a Spring bean with id of “payloadMapping” to direct the incoming XML to an appropriate endpoint, for the example the bean entry is the following:

01.<bean id="payloadMapping"
02. class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
03. <property name="endpointMap">
04. <map>
05. <entry key="{http://bk.org/memberservice/}MemberDetailsRequest"
06. value-ref="getMemberDetailsEndpoint" />
07. map>
08. property>
09.bean>

Essentially a request with MemberDetailsRequest as the element will be directed to getMemberDetailsEndpoint which is :

1. <bean id="getMemberDetailsEndpoint" class="org.bk.memberservice.endpoint.GetMemberDetailsEndpoint">
2. <property name="marshaller" ref="marshaller" />
3. <property name="unmarshaller" ref="unmarshaller" />
4. <property name="memberManager" ref="memberManager" />
5.bean>

The Endpoint needs the marshaller and unmarshaller to be injected to transform the request XML to request object and the response object to response XML. These are created as follows:

01. "marshaller" class="org.springframework.oxm.jibx.JibxMarshaller">
02. name="targetClass"
03. value="org.bk.memberservice.message.MemberDetailsResponse" />
04.
05.
06. "unmarshaller" class="org.springframework.oxm.jibx.JibxMarshaller">
07. name="targetClass"
08. value="org.bk.memberservice.message.MemberDetailsRequest" />
09.

Exposing the Webservice WSDL:

Since the WSDL was created from scratch, to expose this pre-canned wsdl requires a bit more configuration with Spring:

1.<bean id="MemberDetailsRequest"
2. class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">
3. <property name="wsdl" value="classpath:/memberservice.wsdl" />
4.bean>

Now, when the request comes in for the URI /memberservice/MemberDetailsRequest.wsdl, Spring-WS would serve out the static memberservice.wsdl.

This completes the Webservice implementation. It can be further enhanced to handle the Exception scenarios, Security etc which is an exercise for another day.

The complete example can be run using the attached maven enabled code, which will download all dependencies, and can be run using the following command:

mvn jetty:run

Conclusion:

Spring-WS provides a compelling way to create a webservice with a contract first approach. The amount of code appears extensive, however there is clean separation of the contract defined by the WSDL and the implementation, thus being able to change underlying implementation without affecting the contract.

Tuesday, May 19, 2009

Font configuration in Ubuntu Jaunty Jackalope

This is the font configuration that has worked extremely well for me in my Dell Inspiron laptop:

1. Font size of 9 across the board


2. Entries in ~/.fonts.conf file, based on the recommendations from the following post -
http://www.kilobitspersecond.com/2009/04/17/ubuntu-font-hinting-you-a-cautionary-tale/:

<fontconfig>
<match target="font">
<edit mode="assign" name="antialias">
<bool>true</bool>
</edit>
<edit mode="assign" name="hinting">
<bool>true</bool>
</edit>
<edit mode="assign" name="hintstyle">
<const>hintslight</const>
</edit>
<edit mode="assign" name="lcdfilter">
<const>lcdlegacy</const>
</edit>
<edit mode="assign" name="rgba">
<const>none</const>
</edit>
</match>
</fontconfig>

3. The fonts within firefox looked extremely tiny at the end of this exercise. This was improved by installing Microsoft Core fonts :
sudo apt-get install msttcorefonts gsfonts-x11

Thursday, January 1, 2009

Grails - Musings

I have long observed Grails passively, rejoiced that there is now a web framework in Java that does not require jumping through hoops to get a basic setup working. Free time has been a bit of a constraint through 2008, so I never got enough time to spend exploring Grails.
When I heard about the release of Grails 1.1 Beta 2, around Christmas time, I decided I had enough of a free time during the holidays to actually start learning Grails.

A good tutorial that I started following is a Grails Web Album tutorial by John Leach - It is a fairly complex application about creating an online photo album. I was easily able to follow the tutorial and at the end was amazed by how simple it was to create a working application. A great thing about the tutorial is that an equivalent Rails version is also available at John Leach's site, that allowed me to compare and contrast Rails with Grails. I am already fairly proficient in Rails, so one thing that stood out in Grails for me was that specifically for the Web Album application, all the image manipulation libraries were available right within Java, whereas the Rails version required using RMagick, which is fairly difficult to configure on a Windows XP box.
 
My conclusion is fairly simple - Both Grails and Rails are compelling Web frameworks, both have a fairly flat learning curve and the underlying languages(Groovy, Ruby) are delightful and fun to learn and use. I very much intend to continue exploring both Grails and Rails.
 

Wednesday, June 11, 2008

My Java "Aha" moments - Article that I posted on Javalobby http://java.dzone.com/news/my-java-aha-moments

The flood of technology choices in the Java world is overwhelming. I have an analogy that always comes to my mind for the developers who are faced with this flood of information - a python trying to gorge an elephant!!

Technologies like J2EE, JBI/SCA are massive and have a very steep learning curve. I attempted getting through the J2EE specification once and promptly lost my appetite for J2EE. I ended up using the simpler parts for the projects that I have worked on – the web application frameworks, the design blueprints etc and basically became proficient on the job.

There are technologies that have come up in the Java world that have helped manage the bloat considerably and have provided an aha moment for me - when something just clicks in the mind and has simplified the development process considerably for me. Here are my top 5:

1. Spring Framework: http://www.springframework.org

Understanding the principles behind Dependency injection and its implementation in Spring Framework has been a great aha moment for me. Spring has helped me break out of the J2EE hell and has massively simplified the fundamental way in which I have considered projects by forcing some simple conventions like programming to interfaces, business logic as POJO’s.

2. Appfuse: http://appfuse.org/display/APF/Home

I have attempted developing web applications from scratch and have found it difficult to put a good structure in place with all the different myriad Java libraries integrated and working smoothly. Putting a modular structure from scratch also has been extremely.

And then came Matt Raible’s Appfuse and its successor Appfuse 2. Appfuse has been a Godsend. It made the initial ramp up time very smooth by providing a canned structure or a template based on good design and blueprints that any project can start from and move forward.

3. JRuby and JRuby on Rails: http://jruby.codehaus.org

When Rails first came out it was an aha moment for me. I loved the Ruby language before rails was released – I was a smalltalk developer and Ruby as a language was the closest that I had seen to Smalltalk. Rails for the first time enabled me to quickly get up and running with developing a web application, no messing around with a mountain of libraries, everything just worked beautifully. I quickly picked it up, learned enough to create some small applications for myself. I was very pleased to see that the excellent JRuby contributors finally got the Rails framework working on JRuby and promptly now use it for all my internal work.

4. OSGi, Equinox, Apache Felix : http://www.osgi.org/Main/HomePage

OSGi promises modularization for Java – components can be developed as independent modules, and then put together in the OSGi runtime – like Equinox or Apache Felix, which takes care of hosting the component, resolving dependencies, versioning of the components etc.

OSGi was initially a bit of a difficult concept to get my head around, but then once I had tried a few examples, it quickly became an aha moment and see great promise for it in the Java world.

5. Google Web Toolkit: http://code.google.com/webtoolkit/

Google Web Toolkit is amazing; it lets developers create, develop and test the UI with a Java Swing like constructs, and then internally does magic to convert the Java code to cross browser compatible Javascript for web application deployment. Getting a UI working with GWT was indeed an aha moment for me.

In conclusion, the developers in the Java and the broader software technology world are extremely innovative and I am indebted to these simpler technologies that finally present simpler meal options to the python in my analogy.

Sunday, February 10, 2008

JRuby on Rails - First project

I have been wanting to explore jruby on rails for sometime, I finally managed to scramble together a small working project and like what I am seeing.

So this is what I did on my Windows box:

1. Install JRuby. I have installed the latest RC available at this time - 1.1RC1

2. Set the Environment variables -
JRUBY_HOME
PATH - to the bin directory of JRUBY_HOME

3. Install Rails:
jruby -S gem install rails --include-dependencies --no-ri --no-rdoc

4. Install jdbc adapter:
jruby -S gem install activerecord-jdbc-adapter

5. Install Derby adapters:
jruby -S gem install activerecord-jdbcderby-adapter

6. Install Mongrel - To use Mongrel as the webserver instead of the default, download http://rubyforge.org/frs/download.php/20097/mongrel-1.0.1-jruby.gem and,
jruby -S gem install gem_plugin --no-ri --no-rdoc
jruby -S gem install cgi_multipart_eof_fix --no-ri --no-rdoc
jruby -S gem install mongrel-1.0.1-jruby --no-ri --no-rdoc

Now start up on the rails project - my project is to simply record my vehicle mileage:
7. jruby -S rails mileage

8. Modify config/database.yml to use derby:
development:
adapter: jdbcderby
database: db/development
timeout: 5000


9. That's it, the rest of the steps are same as for rails. Once the application is ready, it can be run with the following command:
jruby script/server

Thursday, November 15, 2007

Split 2 million records into 5000 groups of random lists

Problem:
A list of 2 million names.
Create 5000 groups of names with 51%(or 2550) having 100 names from the list, 29%(or 1450) with 500, 8%(400) with 1000, 6%(300) with 25000, 3%(150) with 50000, 3%(150) with 100000. The added complexity is that items in each group should have random set of names from the master list.

My Solution:
I used Ruby to create a simple script:
1. I dumped the list of 2 million names into sqlite db.
2. Created a script along the following lines:
....
db.execute("select duns, name from subject order by random() limit 100") do |row|
file.puts "#{row[0]}"
end
....

This solution took about 10 hours to execute for my entire list. I wonder if there is a much simpler way to do this.

BTB, my Ruby editor of choice is now Netbeans, it has neat features - code completion is my favourite and the ability to edit ad-hoc files is another. My previous editor of choice was Eclipse with ruby plugins