Using CassandraIO with Codenvy

Use Codenvy Factory to instantly start working with the below sample CassandraIO API projects:

This tutorial will explain the details of integrating the CassandraIO API into Codenvy. CassandraIO is a cloud platform providing a hosted Cassandra solution with its API methods. The explanation has been done with 2 very basic Java servlet projects that makes use of the CassandraIO API to explain some basic features provided by the API.

Register With CassandraIO

Before proceeding to the creation of the Java project, please register at http://app.m2m.io/signup with your email id to create your CassandraIO account:

cassandra-signup

After registering, you can login to your account dashboard which will provide details of your account and your default domain that you can use to store and retrieve data and things :

cassandra-dashboard

You can get more information about the CassandraIO API at
http://www.cassandra.io/api. There are different API methods such as methods to create new data domains, store and retrieve data and getting your account details.

To assist in the integration with the different API methods, the API methods in the documentation section can be expanded to try out the methods yourselves which will then give you the HTTP Request URL that will be required to invoke the method from your Codenvy application, the input parameters required in the method call and the response that you would get. For example, if you want to try out the /account related API methods, you would do the following steps:

a) Type in your username and password and click ‘Explore’ in the section provided as shown below. This will enable the method calls to be authenticated:

cassandra-authenticate

b) Now expand the /account section and then expand any API method within the section such as ‘Get Account Model’ :

cassandra-accountmodel

c) This method does not require any input parameters and so click the ‘Try it out!’ button and you will be able to see the request URL and the response coming back from the method call and this request URL can then be used within your Codenvy application to invoke the API method :

cassandra-tryitout

The first factory workspace source code is to explain the process of retrieving your domain details using the CassandraIO API.

Create the first Project

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

Create pom.xml File

To make use of the CassandraIO 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 and the google json jar into your project as Maven dependencies:

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

This will include these jars in your project as follows:
cassandra-dependencies

Create Java Class

Now create a Java servlet class named CassandraIOServlet.java that will talk to the CassandraIO API with the Http request URL(obtained from the API documentation) to retrieve your domain details and then get a Http response back with the response header and the response body 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.

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
        StringBuffer sb = null;
        try {
            String getURL = "http://api.m2m.io/2/account/domain";
            HttpGet req = new HttpGet(getURL);
            req.addHeader("AUTHORIZATION", "abc@pq.com:abc");
            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);
   }

The request header will have your username and password for authorisation when making the API call.

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 CassandraIOServlet 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>CassandraIO Servlet App</display-name>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.codenvy.CassandraIOServlet</servlet-class>
  </servlet>

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

Build and Run Your first Project

Now you build and run your Codenvy project and the Http response will be displayed in the browser:

cassandra-output

The second factory workspace source code is to explain the process of storing data as attributes(key-value pairs) into your domain using the CassandraIO API.

Create the second Project

Login to your Codenvy workspace and create a WAR project named as ‘CassandraSample1’. This will have the same structure as the first project and the pom.xml will define the same dependencies as the first project.

Create Java Class

Now create a Java servlet class named CassandraIOServlet.java that will talk to the CassandraIO API with the Http request URL(obtained from the API documentation) to store data into your domain and then get a Http response back with the response header and the response body which will be then displayed on the browser through a JSP. All this is done inside the doPost() method which is invoked by the method doGet() in the sample source Java class:

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
           doPost(request, response);
   }
   
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
        StringBuffer sb = null;
        try {
            
            String postURL = "http://api.m2m.io/2/account/domain/6234676328hjgasdhjkjdashk/store/wdhsdjkhjksdhjh78634783847874?protect=false&keyValue=Name%3DCassandraIO";
            HttpPost req = new HttpPost(postURL);
            req.setHeader("AUTHORIZATION", "abc@pqr.com:abc");
            
            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 POST request to url : "+ postURL +"<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) {
            ex.printStackTrace();
            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 CassandraIOServlet class to display the response on the browser -

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

The web.xml will be same as the first project.

Build and Run Your second Project

Now you build and run your Codenvy project and the Http response will be displayed in the browser similar to the first project:

cassandra-output1

In a similar way, you can use other available API methods and integrate the CassandraIO API into your application to meet your application needs with regards to usage of Cassandra as a database.