Created
June 15, 2017 09:38
-
-
Save LindaLawton/92c8536baeeeb30f347b78e7f1c2f74f to your computer and use it in GitHub Desktop.
Sample for the Google Analytics reporting API with java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
group 'gropuid' | |
version '1.0-SNAPSHOT' | |
apply plugin: 'java' | |
sourceCompatibility = 1.5 | |
repositories { | |
mavenCentral() | |
} | |
dependencies { | |
testCompile group: 'junit', name: 'junit', version: '4.11' | |
compile 'com.google.apis:google-api-services-analyticsreporting:v4-rev114-1.22.0' | |
compile group: 'com.google.oauth-client', name: 'google-oauth-client-jetty', version: '1.11.0-beta' | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; | |
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; | |
import com.google.api.client.auth.oauth2.Credential; | |
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; | |
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; | |
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.client.util.store.DataStoreFactory; | |
import com.google.api.client.util.store.FileDataStoreFactory; | |
import com.google.api.services.analyticsreporting.v4.AnalyticsReporting; | |
import com.google.api.services.analyticsreporting.v4.AnalyticsReportingScopes; | |
import com.google.api.services.analyticsreporting.v4.model.DateRangeValues; | |
import com.google.api.services.analyticsreporting.v4.model.DateRange; | |
import com.google.api.services.analyticsreporting.v4.model.Dimension; | |
import com.google.api.services.analyticsreporting.v4.model.Metric; | |
import com.google.api.services.analyticsreporting.v4.model.ReportRequest; | |
import com.google.api.services.analyticsreporting.v4.model.GetReportsRequest; | |
import com.google.api.services.analyticsreporting.v4.model.GetReportsResponse; | |
import com.google.api.services.analyticsreporting.v4.model.ColumnHeader; | |
import com.google.api.services.analyticsreporting.v4.model.Report; | |
import com.google.api.services.analyticsreporting.v4.model.MetricHeaderEntry; | |
import com.google.api.services.analyticsreporting.v4.model.ReportRow; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.List; | |
/** | |
* Sample for the Google Analytics reporting API with java | |
* | |
* @author Linda Lawton | |
*/ | |
public class GoogleAnalyticsReportingSample { | |
/** | |
* Be sure to specify the name of your application. If the application name is {@code null} or | |
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0". | |
*/ | |
private static final String APPLICATION_NAME = "DAIMTO-GoogleAnalyticsReportingSample/1.0"; | |
/** Directory to store user credentials. */ | |
private static final java.io.File DATA_STORE_DIR = | |
new java.io.File(System.getProperty("user.home"), ".store/reporting_sample"); | |
/** | |
* Global instance of the {@link DataStoreFactory}. The best practice is to make it a single | |
* globally shared instance across your application. | |
*/ | |
private static FileDataStoreFactory dataStoreFactory; | |
/** Global instance of the HTTP transport. */ | |
private static HttpTransport httpTransport; | |
/** Global instance of the JSON factory. */ | |
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); | |
private static AnalyticsReporting service ; | |
/** Authorizes the installed application to access user's private data. | |
* client_secrets.json can be downloaded from Google developer console. | |
* | |
* Make sure to enable the Google Analytics reporting api and create Oauth2 credentials. | |
* */ | |
private static Credential authorize() throws Exception { | |
// load client secrets | |
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, | |
new InputStreamReader(GoogleAnalyticsReportingSample.class.getResourceAsStream("/client_secrets.json"))); | |
// set up authorization code flow | |
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( | |
httpTransport, JSON_FACTORY, clientSecrets, | |
Collections.singleton(AnalyticsReportingScopes.ANALYTICS_READONLY)).setDataStoreFactory( | |
dataStoreFactory).build(); | |
// authorize | |
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); | |
} | |
public static void main(String[] args) { | |
try { | |
httpTransport = GoogleNetHttpTransport.newTrustedTransport(); | |
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); | |
// authorization | |
Credential credential = authorize(); | |
// set up global Analytics instance | |
service = new AnalyticsReporting.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName( | |
APPLICATION_NAME).build(); | |
// run commands | |
// Fetch Google Analytics Data | |
GetReportsResponse response = fetchData(service); | |
// Print Results | |
printResults(response.getReports()); | |
// success! | |
return; | |
} catch (IOException e) { | |
System.err.println(e.getMessage()); | |
} catch (Throwable t) { | |
t.printStackTrace(); | |
} | |
System.exit(1); | |
} | |
/** Fetching the data from Google Analytics and returning the response*/ | |
public static GetReportsResponse fetchData(AnalyticsReporting service) throws IOException{ | |
DateRange dateRange = new DateRange(); | |
dateRange.setStartDate("2017-06-11"); | |
dateRange.setEndDate("2017-06-13"); | |
// Create the Metrics object. | |
Metric sessions = new Metric() | |
.setExpression("ga:sessions") | |
.setAlias("sessions"); | |
//Create the Dimensions object. | |
Dimension browser = new Dimension() | |
.setName("ga:browser"); | |
// Create the ReportRequest object. | |
ReportRequest request = new ReportRequest() | |
.setViewId("ga:78110423") | |
.setDateRanges(Arrays.asList(dateRange)) | |
.setDimensions(Arrays.asList(browser)) | |
.setMetrics(Arrays.asList(sessions)); | |
ArrayList<ReportRequest> requests = new ArrayList<ReportRequest>(); | |
requests.add(request); | |
// Create the GetReportsRequest object. | |
GetReportsRequest getReport = new GetReportsRequest() | |
.setReportRequests(requests); | |
// Call the batchGet method. | |
return service.reports().batchGet(getReport).execute(); | |
} | |
/** Printing the results. */ | |
private static void printResults(List<Report> reports) { | |
for (Report report : reports) { | |
ColumnHeader header = report.getColumnHeader(); | |
List<String> dimensionHeaders = header.getDimensions(); | |
List<MetricHeaderEntry> metricHeaders = header.getMetricHeader().getMetricHeaderEntries(); | |
List<ReportRow> rows = report.getData().getRows(); | |
for (ReportRow row : rows) { | |
List<String> dimensions = row.getDimensions(); | |
List<DateRangeValues> metrics = row.getMetrics(); | |
for (int i = 0; i < dimensionHeaders.size() && i < dimensions.size(); i++) { | |
System.out.println(dimensionHeaders.get(i) + ": " + dimensions.get(i)); | |
} | |
for (int j = 0; j < metrics.size(); j++) { | |
System.out.print("Date Range (" + j + "): "); | |
DateRangeValues values = metrics.get(j); | |
for (int k = 0; k < values.getValues().size() && k < metricHeaders.size(); k++) { | |
System.out.println(metricHeaders.get(k).getName() + ": " + values.getValues().get(k)); | |
} | |
} | |
} | |
} | |
} | |
} |
Hello, I have issue NullPointerException cause by cannot found client_secrets.json. Can you please help me how can I fix it? Thank you very much.
Make sure that client_secrets.json is in a place that your script can find it.
Ok, thank you, it's worked
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is show me only PageTitle and Session information ! how to get more data like session info including country ?