Pages

Sunday, 25 May 2014

Mapping a Webservice Data (Amazon Product Advertising API) to Database Using Spring and Hibernate


I recently had to device a program to call a webservice, read the response and then map the webservice response to a database using spring and hibernate. For this test I used the Amazon product advertisement API which provides a list of published books as a webservice.

Amazon WebService:
The first step was getting the wsdl which is available here. Once I had the wsdl, the next step was understanding the invocation steps. The API requires signing of the request for which I used a sample program available on the Amazon site itself. 
The sample program contained a SignedRequestsHelper which can be used as is, with just a few changes. The complete source can be taken from here for reference. A Git for the same is also available.

To proceed you will need the access key from the amazon affiliates program which can be obtained by creating an account, and will have to be added to the code invoking the webservice. In the sample code it has been added to AmazonFetchService.
Parameterize or replace the following lines of code:

private static final String AWS_ACCESS_KEY_ID = "<Put your Access Key Id>";
private static final String AWS_SECRET_KEY = "<Put ur Access key>";

Step 1: Fetching the WSDL
Get the wsdl for the Amazon Product advertisement API from this link.

Step 2: Generate the JAXB Classes



Step 3: Configure the Rest Template

<oxm:jaxb2-marshaller id="amazonMarshall"
  contextPath="com.test.amazon.core.xsd" />
<beans:bean id="amazonRestTemplate" class="org.springframework.web.client.RestTemplate"></beans:bean>

The file is also shared here.

Step 4: Configure the Persistance Context

I have used an h2 database and the following files can be referred for configuration:
h2config.xml -- Contains the connection details
spring-persistance-context.xml -- Contains the spring persistance context
orm.xml -- Contains the persistance unit details (needed for audit), code will work without this.
persistance.xml --

Step 5: Write the Program to Call the Service and Update the database

A Simple autowiring of the rest template and a call to its getForObject fetches the response to the webservice.
Now all that is left is to map the response object (ItemSearchResponse) to the entity object (Books_Adt). Use the magic of spring and hibernate to do the rest using a JPA repository (AmazonItemRepository.java) for persistence.

No comments:

Post a Comment