Thursday, July 1, 2010

How to follow a NatJet site with Google Analytics

Google Analytics is a standard free tool to follow activity on a web site.

This tutorial requires a Google Analytics account which is free.

Create a Google Analytics ID for your site

For a Google Analytics account you can create several profiles : a profile can be linked to a web site.

When you are logged in, you should see a link on the right part : ‘+Add a new profile’ (‘Ajouter un profil’ in french). Click on this link to create a new profile.

In this account you need to add a profile, on a single domain (this is the default)

You enter the URL of your site for example www.mycompany.fr:8080/MyNatJetApp

Google Analytics gives you some HTML to add in your head tag.

 

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', ‘XXXXXXXXXX’]);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

This code is enough for most of the sites. When it comes to a NatJet site this is only a start, because this code is executed only when you load the page : in a NatJet app, you just have one HTML page (corresponding to only one URL).

Hopefully, Google Analytics provides you with several API that will be very useful in our case. I will focus on only two of them :

  • _trackPageview : This function allows you to send to Google Analytics the information  that a page have been loaded. Its parameter is the URL : thus in the case of a NatJet application, you can call this function at the end of the InitFormEvent with a parameter that can be the name of your panel.
  • _trackEvent : this function is dedicated to Ajax site (a NatJet application falls in this category) : It allows to track action from a user on a page. In a NatJet application, a user’s action may not change the page but you may still want to track this action : A simple case may be to know if people Save data or use a Print button.

Basic change to a NatJet project

For the demo, you will create a project MyNatJetApp (this should match the name you declare in Google Analytics).

With this NatJet project we will guide through the steps that will transform your NatJet application in a site that can be followed with Google Analytics : There are 3 mains steps (I do not count the project creation) :

  1. create a javascript file corresponding to the Google Analytics code that we want to add
  2. create a servlet that will upload the content of your javascript file in the main NatJet page
  3. update the web.xml file to use the new servlet

Create the NatJet Project

In NatJet select menu File –> New –> Project Wizard…

Just enter in the dialog, MyNatJetApp in Project Name and push Finish button.

The sample project is created.

Create the Google Analytics Javascript file

In the package fr.natsystem.natjet.app.MyNatJetApp, we are going to create a new js file : GoogleAnalyticsMyNatJetApp.js.

In NatJet select menu File –> New –> Other…

In the New dialog box, select node JavaScript and then JavaScript Source File. Press Next and enter the File name : GoogleAnalyticsMyNatJetApp.js

This creates a new file in . You can now add the Google Analytics code. You will add just the javascript part, without the html SCRIPT tag.

 

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', ‘XXXXXXXXXX’]);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

Notice, the XXXXXXXXX should be replaced by your own Google Analytics User Account.

Create a new servlet

The NatJet servlet needs to be overloaded. For this we will create a new servlet that will inherit from the standard NatJet servlet.

Menu File –> New –> Class

The package : fr.natsystem.natjet.app.MyNatJetApp

The name will be : NatJetAnalyticsServlet

The Superclass : fr.natsystem.natjet.echo2.webcontainer.WebContainerSpringServletNS

Check Constructor from superclass

The class is created. You need to add the following code :

package fr.natsystem.natjet.app.MyNatJetApp;

import nextapp.echo.webcontainer.Service;
import nextapp.echo.webcontainer.service.JavaScriptService;
import fr.natsystem.natjet.echo2.webcontainer.WebContainerSpringServletNS;

public class NatJetAnalyticsServlet extends WebContainerSpringServletNS {
       public static final String GOOGLEANALYTICS_JS_SERVICE_ID = "GoogleAnalytics.Script";
       private static final String GOOGLEANALYTICS_JS_SERVICE_URI = "/fr/natsystem/natjet/app/MyNatJetApp/GoogleAnalyticsMyNatJetApp.js";
       public static final Service GOOGLEANALYTICS_JS_SERVICE = JavaScriptService.forResource(GOOGLEANALYTICS_JS_SERVICE_ID, GOOGLEANALYTICS_JS_SERVICE_URI);

    public NatJetAnalyticsServlet() {
        super();
        addInitScript(GOOGLEANALYTICS_JS_SERVICE);
    }

}

This code indicates to the NatJet runtime, that it need to add the Script tag with the content of the GoogleAnalyticsMyNatJetApp.js file in the header of the NatJet page.

Update web.xml

We need to use the servlet we’ve just defined. Open web.xml in WebContent/WEB-INF and  replace in the servlet-class tag the existing servlet by the name of your servlet : fr.natsystem.natjet.app.MyNatJetApp.NatJetAnalyticsServlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <display-name>MyNatJetApp</display-name>
    <servlet>
        <servlet-name>WebContainerSpringServletNS</servlet-name>
        <servlet-class>
            fr.natsystem.natjet.app.MyNatJetApp.NatJetAnalyticsServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>WebContainerSpringServletNS</servlet-name>
        <url-pattern>/app</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <session-config>
        <session-timeout>5</session-timeout>
    </session-config>
</web-app>

Now you can deploy your NatJet application on you web site : when somebody reach your application it will count for one visit on one page.

The demo application have only one page, but in the case of your final application you may have more than one panel and you may be interested in tracking which panel are used by visitors.

More tracking of a NatJet Application

Previous steps have allowed you to track visits, but you just know that you’ve got a visit : you don’t know which panel the visitor called and which actions he made.

We are going to use the two Google Analytics functions we introduced sooner but first we are will externalized the GA user account number.

Externalized a property

The GA user account is used every where, as it may changed it is better to extract its value in a configuration file.

NatJet creates for you a file nsUserContext.xml in WebContent/WEB-INF.

In this file you just add a new entry in the map section to get the following :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- <bean/> definitions here -->
<bean id="nsUserSettingsConfiguration" class="fr.natsystem.natjetinternal.application.PvConfigEntry$UserSettingsConfiguration">
    <property name="userSettingsConfigurationMap">
        <map>
            <entry key="googleAnalyticsUA" value="UA-XXXXXXX-X" />
         </map>
    </property>
</bean>
</beans>

Now you can get this value by using the following code :

NsTools.getUserConfigurationParameter("googleAnalyticsUA", "")

 

Tracking Panel Change in a NatJet application

When a new panel is displayed in NatJet, you can trigger a InitFormEvent. This event, will allow us to detect that a panel have been displayed.

We need a function to trigger a Javascript function of the Google Analytics API from your NatJet code.

This is possible by retrieving the Echo3 Application Instance : then you create a JavaScript command with the JSCommand object and you execute it by enqueuing this command. NatJet will trigger this javascript command after its own Javascript functions when all Java code will have been executed and the browser updated with the new panel.

Here is the code you need to add at the end of your InitFormEvent :

    E2AppInstance app = (E2AppInstance) NsAppInstance.getActiveFactoryAppInstance();
    if (app!=null) {
        app.enqueueCommand(new JSCommand("_gat._getTracker('"+NsTools.getUserConfigurationParameter("googleAnalyticsUA", "")+"')._trackPageview('/" + this.getName() + "')"));
    }

We use this.getName() to insert in the JavaScript command the name of the NatJet panel.

Thus before displaying this panel NatJet triggers this event : the code prepares a JavaScript command which is based on Google Analytics API.

When NatJet sends back its XML synchronization message to the browser, the message contains a part that say it will need to execute this Javascript function.

When the NatJet javascript runtime on the browser get the message, it update the display and then trigger the JavaScript code. This code informs Google Analytics that the page with the URL corresponding to the panel name have been loaded.

By repeating this method in each InitFormEvent of the panels you want to track you are now able to follow the visit on your NatJet site.

Tracking Activity in a NatJet Application

In a Ajax application as a NatJet one, activity is not always linked with the display of a new panel : you may be interested to know if a visitor add a record or delete record or save data….

They are actions triggered by a PushButton but they do not display a new panel, you need something different from the previous method.

This is where the Google Analytics function _trackEvent  is interesting.  This function accepts four parameters :

The first two are compulsory but their value is completely free : the way you want to track this actions will bring you to adopt your own naming convention.

The following example uses two parameters to track that a visitor used the Save pushbutton on a Candidat panel.

E2AppInstance app = (E2AppInstance) NsAppInstance.getActiveFactoryAppInstance();
if (app!=null) {
    app.enqueueCommand(new JSCommand("_gat._getTracker('"+NsTools.getUserConfigurationParameter("googleAnalyticsUA", "")+"')._trackEvent('Candidat', 'Save')"));
}

This is the same mechanism as described before, the only change is the Google Analytics function we are using.

To follow this activity on Google Analytics, you need to go in Content (Contenu in french) and then select Suivi des événements.

Conclusion

In this post we show you how to track the activity on a NatJet Application : we’ve tried to introduce you to a richer tracking system where you detect activity of your users.