Using Sports Data with Codenvy

This tutorial will explain the details of integrating the Sports Data API into Codenvy. With the Sports Data API, you will be able to extract information of various sports events such as information of game schedules, team details, player details, etc. into your application. The explanation has been done with a very basic Java servlet project that makes use of the Sports Data api to explain some basic features provided by the API.

Register at Sports Data

Before proceeding to the creation of the Java project, register at http://developer.sportsdatallc.com/member/register with your email id and then create a Sports Data application that will generate keys which will be used for the integration:
sportsdata
On registering the application, you can see your keys at the ‘My Account’ section:
sportsdata_1

There are different type of APIs that have various methods to integrate with Sports Data for various different information. You can get more information about the API methods at http://developer.sportsdatallc.com/docs

To assist the integration with the different methods, the Sports Data website has a IO Docs section at http://developer.sportsdatallc.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 Player Profiles API available under MLB category, you would do the following steps in your Sports Data account under your registered application:
a) Select the API
sportsdata_2
b) This will list all methods for that API:
sportsdata_3
c) Now expand the Player Profiles method. This will have the options to decide the input parameters. We use player_id as a input parameter and the format of the response is always XML. This method will return back details of the player’s profile based on the player_id supplied as input parameter:
sportsdata_4

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 XML format that you will capture in your Codenvy application:
sportsdata_5

Now, login to your Codenvy workspace and create a WAR project named as ‘SportsDataSample’. This will have the following structure :
project_structure
To make use of the Sports Data 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>SportsDataSample</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SportsDataSample</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>SportsDataSample</finalName>
  </build>
</project>

Create a Java Class

Now create a Java servlet class named ‘SportsDataServlet.java’ that will talk to the Sports Data website with the Http request URL that was generated above in the Sports Data IO Docs section and then get a Http response back with the response header and the response body in the XML 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.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 SportsDataServlet 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.sportsdatallc.org/mlb-t3/player/profile/63909aed-f094-4154-859f-bf45d81a5ebe.xml?api_key=ded3ejkx57ymq565c6bxp9md";

            HttpGet req = new HttpGet(getURL);
            req.addHeader("X-Originating-Ip", "80.254.147.148");
            HttpResponse res = client.execute(req);
            HttpEntity entity = res.getEntity();
            String content = EntityUtils.toString(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(content).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 SportsDataServlet class to display the response on the browser:

<html xmlns="http://www.w3.org/1999/xhtml">
  <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>Sports Data Servlet App</display-name>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.codenvy.SportsDataServlet</servlet-class>
  </servlet>

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

Build and Run Your App

Now you build and run your Codenvy project and the Http response from the Sports Data website with the player profile details based on the input parameter will be displayed in the browser:

Data :

Simple GET request to url : http://api.sportsdatallc.org/mlb-t3/player/profile/63909aed-f094-4154-859f-bf45d81a5ebe.xml?api_key=ded3ejkx57ymq565c6bxp9md

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

*** Response headers ***
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: public, must-revalidate, max-age=33
Content-Type: text/xml;charset=utf-8
Date: Fri, 09 Aug 2013 07:36:27 GMT
Expires: Fri, 09 Aug 2013 07:37:00 -0000
Server: nginx/1.0.14
X-Content-Type-Options: nosniff
X-Mashery-Responder: prod-p-worker-us-east-1c-36.mashery.com
Content-Length: 766
Connection: keep-alive
***********************

*** Response Body ***
Asdrubal Asdrubal Cabrera B R 205 600 1985-11-13 Puerto La Cruz Venezuela Placida Maneiro, VZ 2007-08-08 

You can use this XML format response and parse it in a way that you would like to meet your needs for your custom application. For parsing the XML, the node names can be referred from the response body of this method in the Sports Data IO Docs section

The Sports Data 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.sportsdatallc.com/docs and http://developer.sportsdatallc.com/io-docs