Using Bookshare with Codenvy

Use Codenvy Factory to instantly start working with a sample BookShare API project:


This tutorial will explain the details of integrating the Bookshare API into Codenvy. Bookshare is a very large online library for people with print disabilities that provides access to various books, textbooks, newspapers and magazines. With the Bookshare API, you will have programmatic access to Bookshare’s data allowing you to retrieve information about various books, textbooks, newspapers and magazines. The explanation has been done with a very basic Java servlet project that makes use of the Bookshare API to explain some basic features provided by the API.

Register With BookShare

Before proceeding to the creation of the Java project, please register at http://developer.bookshare.org/member/register with your email id and then create a Bookshare application that will generate keys which will be used for the integration:
register

On registering the application, you can see your keys at the ‘My Account’ section:
keys

At the moment, only the Bookshare API key is being used. The Bookshare API has various methods to integrate with Bookshare for various information. You can get more information about the API methods at
http://developer.bookshare.org/docs

To assist the integration with the different methods, the Bookshare API website has a IO Docs section at http://developer.bookshare.org/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 Bookshare API, you would do the following steps in your Bookshare account under your registered application –

a) Navigating to this section will list all methods for the Bookshare API:

api

b) Now expand any one method such as the Title Search method. This will have the option to enter different input parameters such as Titile of the book that you want to search, pagination parameters and the output response format which is by default XML but can be changed to JSON and this will return books containing the title name entered as input:
bookshare

c) 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:
request_url

Create a Project

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

Create pom.xml File

To make use of the Bookshare 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>BookshareSample</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>BookshareSample</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>BookshareSample</finalName>
  </build>
</project>

Create Java Class

Now create a Java servlet class named BookshareServlet.java’ that will talk to the Bookshare website with the Http request URL that was generated above in the Bookshare 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 BookshareServlet extends HttpServlet {

  private HttpClient client = new DefaultHttpClient();

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

        StringBuffer sb = null;
        try {
            String getURL = "https://api.bookshare.org/book/search/title/Harry+Potter/page/1/limit/5/format/json?api_key=frxxkxvwcef9p3n4eaxan6q4";

            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 BookshareServlet 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 –

<web-app>
<display-name>Bookshare Servlet App</display-name>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.codenvy.BookshareServlet</servlet-class>
</servlet>

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

Now you build and run your Codenvy project and the Http response from the Bookshare website with the information about the books with the title name supplied in the input parameter will be displayed in the browser:

app

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

The Bookshare API provides more methods that can be used in a similar way as above to retrieve various types of information on books and newspapers. More details would be available on their website – http://developer.bookshare.org/docs and http://developer.bookshare.org/io-docs