Hello all I have been putting a project together to use a google analytics api sample provided by google to extract custom data into a csv file every 24 hrs. I have recieved a lot of help from the community
here is the code that came up with that seems to somewhat work take a look.
public class HelloAnalyticsApiSample {
private static final String APPLICATION_NAME ="Analytics Data Extractor";
private static final java.io.File DATA_STORE_DIR =
new java.io.File(System.getProperty("user.home"), ".store/analytics_sample");
private static FileDataStoreFactory dataStoreFactory;
private static HttpTransport httpTransport;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
public static void main(String[] args) {
{
int delay = 5000;
int period = 86400000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
System.out.println("done");
}
}, delay, period);
}
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
Analytics analytics = initializeAnalytics();
String profileId = getFirstProfileId(analytics);
if (profileId == null) {
System.err.println("No profiles found.");
} else {
GaData gaData = executeDataQuery(analytics, profileId);
printGaData(gaData);
}
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
private static Credential authorize() throws Exception {
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
JSON_FACTORY, new InputStreamReader(
HelloAnalyticsApiSample.class.getResourceAsStream("/client_secrets.json")));
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://code.google.com/apis/console/?api=analytics "
+ "into analytics-cmdline-sample/src/main/resources/client_secrets.json");
System.exit(1);
}
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets,
Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY)).setDataStoreFactory(
dataStoreFactory).build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
private static Analytics initializeAnalytics() throws Exception {
Credential credential = authorize();
return new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(
APPLICATION_NAME).build();
}
private static String getFirstProfileId(Analytics analytics) throws IOException {
String profileId = null;
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();
Webproperties webproperties =
analytics.management().webproperties().list(firstAccountId).execute();
if (webproperties.getItems().isEmpty()) {
System.err.println("No Webproperties found");
} else {
String firstWebpropertyId = webproperties.getItems().get(0).getId();
Profiles profiles =
analytics.management().profiles().list(firstAccountId, firstWebpropertyId).execute();
if (profiles.getItems().isEmpty()) {
System.err.println("No profiles found");
} else {
profileId = profiles.getItems().get(0).getId();
}
}
}
return profileId;
}
private static GaData executeDataQuery(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga().get("ga:" + XXXXXXXX,
"yesterday",
"yesterday",
"ga:pageviews, ga:sessions, ga:uniquePageviews")
.setDimensions("")
.setSort("-ga:sessions")
.setFilters("ga:medium==organic")
.setMaxResults(20)
.execute();
}
private static void printGaData(GaData results) {
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter("data.csv")));
} catch (Exception e) {
System.out.println("I could not open the output csv file, see stacktrace below:");
e.printStackTrace();
}
if (pw==null) {
return;
}
if (results.getRows() == null || results.getRows().isEmpty()) {
pw.println("No results Found.");
System.out.println("No results Found.");
} else {
for (ColumnHeaders header : results.getColumnHeaders()) {
pw.print(header.getName() + ", ");
}
pw.println();
for (List<String> row : results.getRows()) {
for (String column : row) {
pw.print(column + ",");
}
pw.println();
}
pw.close();
}
}
couple things that i am concerned with:
- it does not output the correct info that is on the google analytics website
- i dont know if the timer is properly working
thanks and shout outs to all other users that helped me along the way