Display Google Analytics Real time Users in Console Using Java

This is a step by step tutorial on accessing Google Analytics Real time API from Java. The sample code below prints the real time users on a Website using Google analytics real time API. This display is updated every minute on the console. This code is useful if you are building any kind of real time dashboard for analytics data.

Before our application can access Google API, we also need to define a corresponding application on the Google developer console. These are linked using a client id and client secret. In addition, programmatic access to any Google API with user data requires oAuth2 authentication. This requires a user to login to his Google account from the browser  and then give consent to the API client application requesting access to his data. Follow the detailed instructions below to configure access to Google analytics real time API. Note that these steps are similar for any Google API which requires access to user data.

Step 1: Create a New Google Cloud Project and Enable Google Analytics Real time API

Before we can access any Google API programmatically, we need to create a cloud project. We need the cloud project and its credentials before we can even access the oAuth2 APIs.

Login to your Google account. This needs to be same account from which we are going to access the Google analytics real time data. After login, click on this link to Google API dashboard. From dashboard click on Enable API and then select Analytics API.

google-enable-api 

You will be asked to create a new project (if your account already has a project you need to do this manually from the top project menu). Enter the name of the project as GARealtime.

create-google-cloud-project

 new-google-cloud-project-2

New project creation may take a while to complete. Then click Enable button on the top to enable Analytics API for this project. Go back to the dashboard to verify that the selected project (GARealtime) has access to Google analytics API.

From the API Manager on the left, click on credentials. On the right side click on create credentials and select oAuth Client ID.

create-credentials-google-cloud-project

If this is your first project, you need to setup a consent screen. This screen is displayed to the user when an application tries to authenticate a Google user.

create-user-consent-screen

Click on configure consent screen. In the next screen enter the product name as GARealtime and click on Save.

google-oauth2-save-consent-screen

In the next screen, enter the following to create client id and secret,

 google-create-client-id

The authorized redirect URI is important since we will be using Google oAuth2 playground for creating refresh token. Click on create to get client id and client secret. Save this somewhere safe. This will be used by our code to authenticate as GARealtime project. We will also use the same to get the refresh token from Google oAuth2 playground.

google-oauth2-client-id

Step 2: Activate Google Analytics Real time API

Google analytics real time API is still in beta. To enable real time API access to your Google cloud project, you need to first find the project number. To find project number, click on this link. Select GARealtime project from the list. You will find the project number as the last option. Copy this number.

Now fill this form with project number copied above to request for access to Analytics Real time API. It may take up to 24 hours for approval.

Step 3: Get Refresh Token from Google oAuth2 Playground

We will now use the client id and client secret to generate a refresh token from Google oAuth2 playground. Our application will use the refresh token along with client id and client secret to generate access token. This refresh token has long term validity and hence you should keep this safe.

Click here to access Google oAuth2 playground. Click on settings icon and then check use your own oAuth credentials option. Enter the client id and client secret as shown below and then click close.

google-oauth2-playground-configure-client-id

Then click on Step 1: Select & authorize APIs option on the left. Click on Google Analytics API V3. Just select one scope – https://www.googleapis.com/auth/analytics.readonly. We only need readonly access for real time data. Click on Authorize APIs button below.

google-authorize-api-oauth2

This will display the authorization screen for your client id. Click on Allow.

google-oauth2-allow-access-analytics

Authorization code will be displayed on the left window. Click on exchange authorization code for tokens. This will display refresh token and access token. We are not interested in access token since it will expire in an hour. Save the refresh token for later use.

oauth-tokens-google-playground

Now we have everything ready to programmatically access Google analytics real time API. We now have client id, client secret and refresh token ready.

Step 4: Create a Gradle Java Project

You can create the following gradle project from command line or from eclipse IDE. The following instructions assume that you have gradle installed on your system.

Create a simple Java project using gradle,

gradle init --type java-application

Replace the default build.gradle with the following file,

apply plugin: 'java'
apply plugin: 'application'

mainClassName = 'GARealTimeDisplay'


repositories {
    jcenter()
}

dependencies {
    compile 'com.google.apis:google-api-services-analytics:v3-rev136-1.22.0'
    compile 'com.google.oauth-client:google-oauth-client-jetty:1.22.0'

}

Create the following Java class in the default package (src/main/java subfolder).

import java.text.DateFormat;
import java.util.Date;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.Analytics.Data.Realtime.Get;
import com.google.api.services.analytics.model.RealtimeData;

// Displays Google analytics real time users on console using Java.
// Uses refresh token generated from oAuth2 playground
// See http://www.quickprogrammingtips.com for more details.
public class GARealTimeDisplay {
    private static final String APPLICATION_NAME="GARealTimeDisplay";
    private static final String GA_PROPERTY_ID = "REPLACE THIS";
    private static final String GAPI_CLIENT_ID = "REPLACE THIS";
    private static final String GAPI_CLIENT_SECRET = "REPLACE THIS";
    private static final String GAPI_OAUTH_USER_REFRESH_TOKEN="REPLACE THIS";

    public static void main(String[] args) throws Exception {
        try {
            Analytics analytics = initializeAnalytics();
            System.out.println("The following display is refreshed every minute");
            while(true) {
                printRealTimeDisplay(analytics);
                Thread.sleep(60*1000); // wait for a minute!
            }
        } catch (Throwable e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    // Initialize google analytics api using client id/secret and user refresh token
    // client id/secret generated from developer API console
    // refresh token generated from google oauth 2 playground
    private static Analytics initializeAnalytics() throws Exception {
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        Credential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                .setClientSecrets(GAPI_CLIENT_ID, GAPI_CLIENT_SECRET).build();

        credential.setRefreshToken(GAPI_OAUTH_USER_REFRESH_TOKEN);

        return new Analytics.Builder(httpTransport, jsonFactory, credential).setApplicationName(APPLICATION_NAME)
                .build();
    }

    // Display only the real time users to a site as reported by google analytics
    private static void printRealTimeDisplay(Analytics analytics) throws Exception {
        Get realtimeRequest = analytics.data().realtime().get("ga:" + GA_PROPERTY_ID, "rt:activeUsers");

        RealtimeData realtimeData = realtimeRequest.execute();
        String property = realtimeData.getProfileInfo().getProfileName();
        String time = DateFormat.getDateTimeInstance().format(new Date());       
        if (realtimeData.getTotalResults() > 0) {
            for (List<String> row : realtimeData.getRows()) {
                for (String element : row) {
                    System.out.println(time+":"+property+":Active Users:"+element);
                }
            }
        } else {
            System.out.println("No data received");
        }
    }
}

Replace the following constants in the Java class with actual values for your account.

  • GA_PROPERTY_ID – Google Analytics Property Number
  • GAPI_CLIENT_ID – Google Cloud Project Client ID
  • GAPI_CLIENT_SECRET – Google Cloud Project Client Secret
  • GAPI_OAUTH_USER_REFRESH_TOKEN – oAuth2 Refresh Token from Playground

Step 5: Run the Java Application

Using your IDE or from command line execute the gradle run task.

For linux/mac,

./gradlew run

For windows,

gradlew.bat

If everything goes well, real time visitors to your website will be displayed on the console every minute.

google-analytics-realtime-java-console

References

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply