Using Keen IO with Codenvy

Get started with Keen.IO using Codenvy Factory:

 

Pre Requisites : The user has a basic understanding of KeenIO and Codenvy from the URLs : https://keen.io/ and https://codenvy.com/

This document will explain the details of integrating the Keen IO API into Codenvy. The explanation has been done with a very basic Java web project that makes use of the KeenIO api to explain some basic features provided by the api.

Register with Keen.io

Before proceeding to the creation of the Java project, please register at https://keen.io/ with your email id and then create a KeenIO project that will be used for the integration –

keenio

The Show API Keys will provide a Write key and a Read key which along with the Project Id will be required for the integration. The Event Explorer will have the Event Collection details such as the events that are part of the event collection.

Create a project in Codenvy

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

project_structure

Specify dependencies in pom.xml

To make use of the Keen IO api, please update the pom.xml to include the Keen API client and its dependencies 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>KeenIOSample</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>KeenIOSample</name>

  <dependencies>
    <dependency>
      <groupId>io.keen</groupId>
      <artifactId>keen-client-api-java</artifactId>
      <version>1.0.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.8</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.1</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>KeenIOSample</finalName>
  </build>
</project>

This will include these jars in your project as follows:

dependencies

Create Java classes

Now create a Java class named ‘KeenIO.java’ that will first register the KeenClient api with your project id and read/write keys and then add an event that you want to track into an event collection. If the event collection does not exist, the KeenIO api will create that event collection for the first time and then subsequently use that event collection to store similar events. All this is done inside a method onInitialize() in the sample source Java class.

For an example, the event collection used in the sample source is ‘purchaseitems’ which will be filled with a ‘item’ event to track the purchases.

package com.codenvy;

import java.util.Map;
import java.util.HashMap;
import io.keen.client.java.KeenClient;
import io.keen.client.java.exceptions.KeenException;

public class KeenIO {

    public void onInitialize() {

String keenProjectId = "51e6875038433153ff000002";
String writeKey = "f3097eaa409601a1fd08b6e7647dec2eae48982c5076e7e04adb63a0541d4223ffad8fa5c255034ab3a266f0ab5a86171ecdfb0b328011d81";
String readKey = "250145b2d3da98e640a5b4860ee7222c1625ac9d17913a5bc6b8740ee8aba5ebbd7abcf5c0d747cc52c50f551bee73160d5dbc73fc76c48e868";

      // initialize the Keen Client with your Project ID.
      KeenClient.initialize(keenProjectId,writeKey,readKey);

      // add an event "item"
      Map<String, Object> event = new HashMap<String, Object>();
      event.put("item", "Item2");

      // add it to the "purchases" collection in your Keen Project
      try {
         KeenClient.client().addEvent("purchaseitems", event, null, new MyCallback());
      } catch (KeenException e) {
         e.printStackTrace();
      }
    }
}

There is a MyCallback() class which implements a KeenIO api and tells whether the adding of the event to your collection was successfull or not.

This is the MyCallback() class –

package com.codenvy;

import io.keen.client.java.AddEventCallback;

public class MyCallback implements AddEventCallback {
    @Override
    public void onSuccess() {
        System.out.println("It worked!");
    }

    @Override
    public void onError(String responseBody) {
        System.out.println("It failed! Reason: " + responseBody);
    }
}

Create index.jsp

Your Codenvy project will have an index.jsp which will invoke the KeenIO class and call the onInitialise() method to add the events to the event collection -

<%
com.codenvy.KeenIO keenIO = new com.codenvy.KeenIO();
keenIO.onInitialize();
%>

Now you build and run your Codenvy project and if you check the logs, it will show the message as “It worked” if the events have been successfully added to the purchaseitems event collection :

If you now check your KeenIO project, you will see the “purchaseitems” event collection with 1 event added to it – Item1 as per our KeenIO java class.

event_explorer

If you click on the event, you will see the properties of that event:

event_properties

Now we will enhance this sample application to analyse your events by counting the number of occurrences of an event and creating a visualisation data of the analysis such as a pie chart.

For this we will add code to our index.jsp. We will use Keen IO’s data analysis and data visualisation apis and embed them within a simple HTML code to generate a pie chart showing the count of event in the purchaseitems event collection.

We will now add Javascript code to the index.jsp. The code will create a Keen api object and register the object to the Keen Project Id and read/write keys. The following code does that –

 var Keen=Keen || {configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],
       this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e)
                      {this._ocrq=this._ocrq||[],this._ocrq.push(e)}};(function(){var e=document.createElement("script");
       e.type="text/javascript",e.async=!0,e.src=("https:"==document.location.protocol?"https://":"http://")
         +"dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js";var t=document.getElementsByTagName("script")[0];
    t.parentNode.insertBefore(e,t)})();
     
     Keen.configure({
        projectId: "51e6875038433153ff000002",
        readKey: "250145b2d3da98e640a5b4860ee7222c1625ac9d17913a5bc6b8740ee8aba5ebbd7abcf5c0d747cc52c50f551bee73160d5dbc73fc76c48",
        writeKey: "f3097eaa409601a1fd08b6e7647dec2eae48982c5076e7e04adb63a0541d4223ffad8fa5c255034ab3a266f0ab5a86171ecdfb0b328011d81"
     });

The next function will be the function where the data analysis and data visualisation code will be placed using the apis –

Keen.onChartsReady(function() {
var myMetric = new Keen.Metric("purchaseitems", {
analysisType: "count",
targetProperty: "item",
groupBy: "item"
});
var myPieChart = new Keen.PieChart(myMetric, {
height: 300,
width: 600,
minimumSlicePercentage: 5,
colors: ["red", "green", "#fef584"],
backgroundColor: "transparent",
title: "count of items",
});

//Draw the visualization into a div
myPieChart.draw(document.getElementById("visualization-test"));
});

Here the Keen.Metric is a data analysis api object detailing event collection , the analysis function and the event type that needs to be analysed.

The Keen.PieChart is the data visualisation api object to create the pie chart. The “visualisation-test” id will be used for the HTML element which will contain the pie chart such as

-

<div id="visualization-test"></div>

On building and running this code, the index.jsp will again create an event Item1 and will also generate a pie chart with the count of items in the event collection “purchaseitems”. The output will be as follows –

pie_chart

Now, to do a comparison between different ”purchaseitems”, build and run the same project again but with a small update in the KeenIO.java by changing the event to Item2 –

Map<String, Object> event = new HashMap<String, Object>();
event.put("item", "Item2");

This will then generate the Pie Chart as follows –

pie_chart1

pie_chart2

The Keen IO provides more apis that can be used in a similar way as above to perform data analysis and data visualisation. More details would be available on their website – https://keen.io/docs/