Categories
Development

Google analytics report parsing in Java 8

Google has deprecated Google Analytics API v3 in favor of its new reporting API (V4). New API is quite universal and easy to use and its java library gets the job done well with one exception: mapping result to Java types. It returns everything in strings and you have to parse the Reports yourself and map the values to your object. I recently had to load quite a lot of daily statistics from google analytics so I wrote a simple class which does this dirty work for me.

For a class with fields annotated with metric annotation. You can find all allowed metric values here. Note that it always uses ga:date as dimension.

[sourcecode language=”java”]
public class SessionStats extends BaseDailyStats {
@GoogleAnalyticsMetric("ga:sessions")
private Long sessions = 0L;

@GoogleAnalyticsMetric("ga:bounces")
private Long bounces = 0L;

@GoogleAnalyticsMetric("ga:bounceRate")
private Double bounceRatePercent = 0d;

@GoogleAnalyticsMetric("ga:avgSessionDuration")
private Double avgSessionDuration = 0d;

@GoogleAnalyticsMetric("ga:hits")
private Long hits = 0L;
}
[/sourcecode]

The code is invoked by calling:

[sourcecode language=”java”]
Client client = new Client(analyticsReporting, VIEW_ID, MAX_NUMBER_OF_DAYS);
List<SessionStats> dailyStats = client.getDailyStats(SessionStats.class);
dailyStats.forEach(System.out::println);
[/sourcecode]

It requests statistics for number of days until present day and automatically binds them to the Stats class.

Easy and quick. You can find the source code on github.
https://github.com/MavoCz/googleAnalyticsEasyReport