Using Harper Collins with Codenvy

Create a sample project that interacts with Harper Collins API using a Factory button:


This tutorial will explain the details of integrating the Harper Collins API into Codenvy. With the Harper Collins API, you will be able to extract information of various books and publications of Harper Collins into your application. The explanation has been done with a very basic Java servlet project that makes use of the Harper Collins api to explain some basic features provided by the api.

Register at Harper Collins

Before proceeding to the creation of the Java project, make sure you register at http://developer.harpercollins.com/apps/register with your email id and then create a Harper Collins application that will generate keys which will be used for the integration:
harpercollins
On registering the application, you can see your keys at the ‘My Account’ section:
harpercollins1
The OpenBook and OpenBook Content APIs have various methods to integrate with Harper Collins for various different information. You can get more information about the API methods at http://developer.harpercollins.com/docs

To assist the integration with the different methods, the Harper Collins website has a IO Docs section at http://developer.harpercollins.com/io-docs which will give you the HTTP Request URL that will be required to invoke the method from your Codenvy application and the response that you would get. For example, if you want to invoke the Catalog API available under Openbook, you would do the following steps in your Harper Collins account under your registered application –

a) Select the API:
harpercollins2

b) This will list all methods for that API under different versions:
harpercollins3

c) Now expand the Catalog method. This will have the options to decide the return format of the response and the input parameters. We use the Product Id as a parameter and the format of the response as JSON:
harpercollins4

d) On clicking Try it, you will get the Request URL generated that will be used from your application in Codenvy and the request and response headers and response body in JSON format that you will capture in your Codenvy application:
harpercollins5

Create a Project

Now, login to your Codenvy workspace and create a WAR project named as ‘HarperCollinsSample’. This will have the following structure :

project_structure

Create pom.xml File

To make use of the Harper Collins api through HttpClient as a servlet, please update the pom.xml to include the HttpClient and Java EE Web API jars and the servletapi jar into your project as Maven dependencies:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
<groupId>com.codenvy</groupId>
<artifactId>HarperCollinsSample</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>HarperCollinsSample</name>
  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.2.5</version>
    </dependency>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-web-api</artifactId>
      <version>6.0</version>
    </dependency>
  </dependencies>
  <repositories>
     <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Maven Repository Switchboard</name>
      <url>http://repo1.maven.org/maven2</url>
     </repository>
  </repositories>
  <build>
    <finalName>HarperCollinsSample</finalName>
  </build>
</project>

Create Java Class

Now create a Java servlet class named ‘HarperCollinsServlet.java’ that will talk to the Harper Collins website with the Http request URL that was generated above in the Harper Collins IO Docs section and then get a Http response back with the response header and the response body in the JSON format which will be then displayed on the browser through a JSP. All this is done inside the method doGet() in the sample source Java class.

package com.codenvy;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HarperCollinsServlet extends HttpServlet{

  private HttpClient client = new DefaultHttpClient();

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        StringBuffer sb = null;
        try {
            String getURL = "http://api.harpercollins.com/api/v3/hcapim?apiname=catalog&format=JSON&productid=10742&apikey=bxcp6qz83rt8ce9sjd4vh72x";

            HttpGet req = new HttpGet(getURL);
            req.addHeader("X-Originating-Ip", "80.254.147.148");
            HttpResponse res = client.execute(req);
            HttpEntity entity = res.getEntity();
            String responseString = new BasicResponseHandler().handleResponse(res);
            if (entity != null) {
                EntityUtils.consume(entity);
            }

            sb = new StringBuffer("<br/>Simple GET request to url : "+ getURL +"<br/><br/>");
            sb.append("*** Request headers ***").append("<br/>");
            Header[] requestHeaders = req.getAllHeaders();
            for (Header header : requestHeaders) {
                sb.append(header.toString()).append("<br/>");
            }
            sb.append("***********************").append("<br/><br/>");

            sb.append("*** Response headers ***").append("<br/>");
            sb.append(res.getStatusLine()).append("<br/>");
            Header[] headers = res.getAllHeaders();
            for (Header header : headers) {
                sb.append(header.toString()).append("<br/>");
            }
            sb.append("***********************").append("<br/><br/>");

            sb.append("*** Response Body ***").append("<br/>");
            sb.append(responseString).append("<br/>");

        } catch (Exception ex) {
            sb = new StringBuffer(ex.toString());
        }

        request.setAttribute("data", sb.toString());
        RequestDispatcher rd = request.getRequestDispatcher("/success.jsp");
        rd.forward(request, response);
   }

}

Create index.jsp File

Your Codenvy project will have an index.jsp which will invoke the Servlet class -

<%
    response.sendRedirect("/hello");
%>

Create success.jsp File

Your Codenvy project will have a success.jsp which will be invoked from the HarperCollinsServlet class to display the response on the browser -

<html>
  <body>
    <div>
      <p>Data : <br/><%=request.getAttribute("data") %></p>
      <br/>
    </div>
 </body>
</html>

Create web.xml File

The servlet mapping ‘/hello’ is defined in the web.xml as follows –

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Harper Collins Servlet App</display-name>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.codenvy.HarperCollinsServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

Build and Run Your Project

Now you build and run your Codenvy project and the Http response from the Harper Collins website with the catalog details for the product id will be displayed in the browser:

Data :

Simple GET request to url : http://api.harpercollins.com/api/v3/hcapim?apiname=catalog&format=JSON&productid=10742&apikey=bxcp6qz83rt8ce9sjd4vh72x

*** Request headers ***
X-Originating-Ip: 80.254.147.148
***********************

*** Response headers ***
HTTP/1.1 200 OK
Cache-Control: max-age=86400
Content-Type: application/json
Date: Fri, 09 Aug 2013 08:50:03 GMT
Expires: Sat, 10 Aug 2013 08:50:03 GMT
Server: Apache/2.2.3 (Red Hat)
X-Mashery-Responder: prod-j-worker-us-east-1b-36.mashery.com
transfer-encoding: chunked
Connection: keep-alive
***********************

*** Response Body ***
{ "OpenBook_API" : " ", "Product_Group" : [ { "Product_Group_ID" : "977", "Product_Group_SEO_Copy" : "Not Included in JSON", "Product_Group_Title" : "Mirror Mirror", "Products" : { "On_Sale_Date" : "10\/14\/03 00:00:00.000", "ISBN" : "9780060393847", "Title" : "Mirror Mirror", "Format" : "Hardcover", "Sub_Format" : "", "Imprint" : "William Morrow", "Author1" : "Gregory Maguire", "Author1_Contributor_Persona_ID" : "3510", "Author1_Source_Contributor_ID" : "6173", "Artist" : "", "Artist_Contributor_Persona_ID" : "", "Artist_Source_Contributor_ID" : "", "Author2" : "", "Author2_Contributor_Persona_ID" : "", "Author2_Source_Contributor_ID" : "", "Locale_Desc" : "US Trade", "Product_ID" : "10742", "CoverImageURL_Large" : "http:\/\/www.harpercollins.com\/harperimages\/isbn\/large\/7\/9780060393847.jpg", "CoverImageURL_Medium" : "http:\/\/www.harpercollins.com\/harperimages\/isbn\/medium\/7\/9780060393847.jpg", "CoverImageURL_MediumLarge" : "http:\/\/www.harpercollins.com\/harperimages\/isbn\/medium_large\/7\/9780060393847.jpg", "CoverImageURL_Small" : "http:\/\/www.harpercollins.com\/harperimages\/isbn\/small\/7\/9780060393847.jpg" } } ] }

You can use this JSON format response in a way that you would like to meet your needs for your custom application. The response can be in XML format as well.

The Harper Collins provides more apis that can be used in a similar way as above to perform various functions. More details would be available on their website – http://developer.harpercollins.com/docs and http://developer.harpercollins.com/io-docs