1

I am having problems getting the Hello Analytics program to work with Google Analytics API v3. I have gone to the google developers website and went through the steps to setup the user and get the credentials and add the user to analytics. I downloaded the code from the webpage https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-java

I am added the jar files to the classpath and none of them are given me errors in the java code. However on lines 71,80, and 90 there is an error that says "The method getId() is undefined for the type Object"

I understand that this method is not defined in type object. I have looked at the hierarchy of the calls and noticed that it does not exist at the Object, List, or Account levels in the .jar files supplied by Google.

I am running java version 1.8.0_73 from my java control panel. Can you tell me what is wrong or how to fix this problem?

Here is the code from Google:

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.gson.GsonFactory;

import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.Accounts;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Webproperties;

import java.io.File;
import java.io.IOException;


/**
 * A simple example of how to access the Google Analytics API using a service
 * account.
 */
public class HelloAnalytics {


  private static final String APPLICATION_NAME = "Hello Analytics";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static final String KEY_FILE_LOCATION = "/path/to/your.p12";
  private static final String SERVICE_ACCOUNT_EMAIL = "<SERVICE_ACCOUNT_EMAIL>@developer.gserviceaccount.com";
  public static void main(String[] args) {
    try {
      Analytics analytics = initializeAnalytics();

      String profile = getFirstProfileId(analytics);
      System.out.println("First Profile Id: "+ profile);
      printResults(getResults(analytics, profile));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static Analytics initializeAnalytics() throws Exception {
    // Initializes an authorized analytics service object.

    // Construct a GoogleCredential object with the service account email
    // and p12 file downloaded from the developer console.
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
        .setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
        .setServiceAccountScopes(AnalyticsScopes.all())
        .build();

    // Construct the Analytics service object.
    return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }


  private static String getFirstProfileId(Analytics analytics) throws IOException {
    // Get the first view (profile) ID for the authorized user.
    String profileId = null;

    // Query for the list of all accounts associated with the service account.
    Accounts accounts = analytics.management().accounts().list().execute();

    if (accounts.getItems().isEmpty()) {
      System.err.println("No accounts found");
    } else {
      String firstAccountId = accounts.getItems().get(0).getId();

      // Query for the list of properties associated with the first account.
      Webproperties properties = analytics.management().webproperties()
          .list(firstAccountId).execute();

      if (properties.getItems().isEmpty()) {
        System.err.println("No Webproperties found");
      } else {
        String firstWebpropertyId = properties.getItems().get(0).getId();

        // Query for the list views (profiles) associated with the property.
        Profiles profiles = analytics.management().profiles()
            .list(firstAccountId, firstWebpropertyId).execute();

        if (profiles.getItems().isEmpty()) {
          System.err.println("No views (profiles) found");
        } else {
          // Return the first (view) profile associated with the property.
          profileId = profiles.getItems().get(0).getId();
        }
      }
    }
    return profileId;
  }

  private static GaData getResults(Analytics analytics, String profileId) throws IOException {
    // Query the Core Reporting API for the number of sessions
    // in the past seven days.
    return analytics.data().ga()
        .get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
        .execute();
  }

  private static void printResults(GaData results) {
    // Parse the response from the Core Reporting API for
    // the profile name and number of sessions.
    if (results != null && !results.getRows().isEmpty()) {
      System.out.println("View (Profile) Name: "
        + results.getProfileInfo().getProfileName());
      System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
    } else {
      System.out.println("No results found");
    }
  }
}
  • Perhaps it's because your response does not have any accounts? The [Source Code](https://developers.google.com/resources/api-libraries/documentation/analytics/v3/java/latest/com/google/api/services/analytics/model/Account.html#getId()) clearly has `getId()` defined. Remember that you need to add your service account email address to the Analytics View (Profile) you wish to query. – Matt Mar 15 '16 at 16:56
  • I have added the email address and the path to the .p12 file. However I get the error before I even run the code. It shows up as errors. So I am not even getting a run time error. – user3622312 Mar 15 '16 at 17:22
  • 1
    I figured out the problem with the code. The example has Accounts, Webproperties, and Profiles imported. However they are lists of the Account, Webproperty, and Profile object. I had to import those objects into the code and then type cast the appropriate line to make it work. Here is an example. String firstWebpropertyId = ((Webproperty) properties.getItems().get(0)).getId(); – user3622312 Mar 15 '16 at 19:22

1 Answers1

0

The value you are providing for variable SERVICE_ACCOUNT_EMAIL i.e "@developer.gserviceaccount.com" you need to add it to your Google Analytics 'User Management'. You will find it in Admin > User Management. Add SERVICE_ACCOUNT_EMAIL of yours there and it will start working.