11. October 2009

Google Analytics and Maven Project Sites

I recently looked for a way to integrate the Google Analytics tracking code into the project site of my current spare time project Criteria4JPA. I'm using the Maven Site Plugin to automatically build the project page because it makes the process of creating a site very easy.

After some time I realized that there seems to be no easy way to do this. Somebody on the maven-user list proposed to create a copy of the original site template and modify it to include the necessary JavaScript in the page header. But I think that this solution is much to complicated for such a simple job. I also found an existing JIRA issue describing the problem but it is still unresolved.

But after much more searching I discovered a very simple and elegant way to get the Google Analytics tracking code into the maven site. I found the hint on the doxia-dev mailing list. Someone talked about a mysterious <head> element that can be used in the site.xml descriptor. The JIRA issue DOXIA-150 seemed to prove the existence of this feature.

I tried it and it worked. See the site.xml file of Criteria4JPA for an example:

<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="Criteria4JPA">

  <body>

    <head>
      <!-- Google Analytics - Start -->
      <script type="text/javascript">
      var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
      document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
      </script>
      <script type="text/javascript">
      try {
      var pageTracker = _gat._getTracker("UA-1234567-8");
      pageTracker._trackPageview();
      } catch(err) {}</script>      
      <!-- Google Analytics - End -->
    </head>

    <!-- more stuff -->

  </body>
</project>

As you can see adding the tracking code is very easy. Just place a <head> element inside the body and copy the Google Analytics code in there. The default JavaScript code you get from Google Analytics is already correctly escaped so you can copy and paste it into the XML descriptor without problems.

I don't know for sure which versions of Maven, Doxia and the Site Plugin are required for this but I can confirm that Maven 2.2.0 together with the Maven Site Plugin 2.0-beta-7 works.

Happy tracking... :-)