I am trying following code to check data retrieval from Google Analytics using OAuth service account authorization. I want to retrieve data from GA and import it into PostgreSql database. I started learning this retrieval and I am working with following code.
public class ServiceAccountTest1 {
private static final String APPLICATION_NAME = "JasperPlusGoogleAnalytics";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static FileDataStoreFactory dataStoreFactory;
private static HttpTransport httpTransport;
private static final String emailAddress = "
XXXXX...@developer.gserviceaccount.com";
private static final String profileId = "ga:XXXXXX";
public static void main(String[] args){
try{
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
/*GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAddress)
.setServiceAccountPrivateKeyFromP12File(new File("D:\\test\\JasperPlusGoogleAnalytics-140cd2242390.p12"))
.setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN))
.build();*/
GoogleCredential credential =
new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAddress)
.setServiceAccountScopes(Collections.singleton(AnalyticsScopes.ANALYTICS_EDIT))
.setServiceAccountPrivateKeyFromP12File(new File("D:\\test\\XXXXX.p12"))
.build();
Analytics analytics = initializeAnalytics(credential);
/*
SQLAdmin sqladmin =
new SQLAdmin.Builder(httpTransport, JSON_FACTORY, credential).build();*/
GaData gaData = executeDataQuery(analytics, profileId);
printGaData(gaData);
}
catch(Exception e){
System.out.println(e);
}
}
private static Analytics initializeAnalytics(Credential c) throws Exception {
// Set up and return Google Analytics API client.
return new Analytics.Builder(httpTransport, JSON_FACTORY, c).setApplicationName(
APPLICATION_NAME).build();
}
private static GaData executeDataQuery(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga().get( profileId, // Table Id. ga: + profile id.
"2012-01-01", // Start date.
"2015-04-10", // End date.
"ga:visits") // Metrics.
.setDimensions("ga:source,ga:keyword")
.setSort("-ga:visits,ga:source")
.setFilters("ga:medium==organic")
.setMaxResults(25)
.execute();
}
// Print column headers.
for (ColumnHeaders header : results.getColumnHeaders()) {
System.out.printf("%30s", header.getName());
}
System.out.println();
// Print actual data.
for (List<String> row : results.getRows()) {
for (String column : row) {
System.out.printf("%30s", column);
}
System.out.println();
}