Saturday 2 June 2007

JSR 181 Web Service

In the last post I have used simple Web Service to test Spring-WS. Now I'm going to explain the implementation of this service.
The service is based in XFire and JSR 181 annotations.

First, the Book class, that represent the model.

package net.dahernan.model;

public class Book {

protected String title;
protected String isbn;
protected String author;
protected Double price;

// ... getters and setters
}


Next, the BookService class (yeah a class not an interface).

package net.dahernan.service;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

import net.dahernan.model.Book;

@WebService
public class BookService {

protected Book getMockBook(){
Book book = new Book();
book.setAuthor("Matt Raible");
book.setTitle("Spring Live");
book.setIsbn("12345");
book.setPrice(12.22);
return book;
}

protected List getMockBooks(){
List result = new ArrayList();
Book book = new Book();
book.setAuthor("Matt Raible");
book.setTitle("Spring Live");
book.setIsbn("12345");
book.setPrice(12.22);
result.add(book);

book = new Book();
book.setAuthor("Martin Fowler");
book.setTitle("Planning Extreme Programming");
book.setIsbn("12346");
book.setPrice(18.00);
result.add(book);
return result;
}

@WebMethod
@WebResult(name="Book")
public Book findBook(@WebParam(name="isbn")String isbn) {
Book book = this.getMockBook();
book.setIsbn(isbn);
return book;
}

@WebMethod
@WebResult(name="Books")
public List getBooks() {
return getMockBooks();
}

}


The class is annotated with @WebService. The first two methods are Mocks, and "getBooks" and "findBooks" are the methods exposed in service.

It's good practice annotate the result with @WebResult and the parameters with @WebParams to obtain an human readable WSDL.

Finally, the services.xml to configure my POJO.

<beans>
<service xmlns="http://xfire.codehaus.org/config/1.0">
<name>BookService</name>
<namespace>http://dahernan.net/BookService</namespace>
<serviceClass>net.dahernan.service.BookService</serviceClass>
<serviceFactory>#jsr181ServiceFactory</serviceFactory>
</service>

<bean id="config"
class="org.codehaus.xfire.aegis.type.Configuration">
<property name="defaultExtensibleElements" value="false" />
<property name="defaultExtensibleAttributes" value="false" />
<property name="defaultNillable" value="false" />
<property name="defaultMinOccurs" value="1" />
</bean>

<bean name="jsr181ServiceFactory"
class="org.codehaus.xfire.annotations.AnnotationServiceFactory">
<constructor-arg ref="xfire.transportManager" index="0" />
<constructor-arg ref="config" index="1"
type="org.codehaus.xfire.aegis.type.Configuration" />
</bean>

</beans>


The generated WSDL looks like a contract-first WSDL ;)

No comments: