I am trying to implement the google analytics library in a website in order to make my own queries and obtain some kind of data to manage them afterwards.
I have followed the example and everything works fine. However, I am only able to code the example query (visitors in last week). I've read many information and documentation about that and I'm still having the same issue.
I'm sure there must be a way to accomplish that, but actually I'm not able to code anything to make my own queries.
The code is (I'm using maven):
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 test {
private static final String APPLICATION_NAME = "example";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String KEY_FILE_LOCATION = //route to p.12 file;
private static final String SERVICE_ACCOUNT_EMAIL = //mail example;
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");
}
}
}
Note that the code that makes the queries is:
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();
}
The problem is: how I set dimensions of my queries using this code?
This query works (without dimensions):
private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga()
.get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration")
.execute();
}
This one doesn't work (with dimensions):
private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga()
.get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration",**"ga:userType"**)
.execute();
}
I would appreciate any help. Thanks a lot!
Well, seems that I've finally solved my issue. I answer myself in order to help someone with similar problems and hope it works for them too.
The answer is simply, the documentation about Google Analytics is a bit confusing, but if someone wants to add dimensions, metrics (or edit the example query from Google analytics) just need to add the code in the following link:
https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide
Just adding this code just following the query example (if you want to add dimensions):
setDimensions("ga:userType")
So, the final code will be:
private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga()
.get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration").setDimensions("ga:userType")
.execute();
}
Note that in the main code, you need to add the print function, just like this:
public static void main(String[] args) {
try {
Analytics analytics = initializeAnalytics();
printMobileTraffic(getMobileTraffic(analytics, profile));
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I am using a service account to access google doc files of users in my enterprise google account using impersonation.
See:
https://developers.google.com/drive/api/v3/about-auth#OAuth2Authorizing
So far so good.
Then, I need to download contents of Google Docs.
When calling Google Drive API to download the contents of a Google Doc, the documentation says to run the following:
https://developers.google.com/drive/api/v3/manage-downloads
Here is a java program that should reproduce the problem:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.SecurityUtils;
import com.google.api.services.drive.Drive;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
public class FetchGoogleDocContentsWithServiceAccount {
static int readTimeout = 60000;
static int connectTimeout = 60000;
static String serviceAccountId = "";
static String serviceAccountEmail = "";
static String serviceAccountPrivateKeyFile = "";
static String serviceAccountPrivateKeyFilePassword = "";
static String fileId = "";
static JacksonFactory jacksonFactory = new JacksonFactory();
static NetHttpTransport httpTransport = new NetHttpTransport();
static List<String> googleScopeList = Arrays.asList("https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/admin.directory.group.readonly",
"https://www.googleapis.com/auth/admin.directory.user.alias.readonly",
"https://www.googleapis.com/auth/admin.directory.group", "https://www.googleapis.com/auth/admin.directory.user",
"https://www.googleapis.com/auth/drive");
public static void main(String[] args) throws Exception {
Drive drive = (new Drive.Builder(httpTransport,
jacksonFactory,
getRequestInitializer(getGoogleCredentials())))
.setApplicationName("Sample app").build();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
drive.files().export(fileId, "application/vnd.google-apps.document")
.executeMediaAndDownloadTo(baos);
System.out.println(baos.toString("UTF-8"));
}
public static HttpRequestInitializer getRequestInitializer(final GoogleCredential requestInitializer) {
return httpRequest -> {
requestInitializer.initialize(httpRequest);
httpRequest.setConnectTimeout(readTimeout);
httpRequest.setReadTimeout(connectTimeout);
};
}
public static GoogleCredential getGoogleCredentials() {
GoogleCredential credential;
try {
GoogleCredential.Builder b = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jacksonFactory).setServiceAccountId(serviceAccountId)
.setServiceAccountPrivateKey(SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(),
new FileInputStream(new File(serviceAccountPrivateKeyFile)), serviceAccountPrivateKeyFilePassword,
"privatekey", serviceAccountPrivateKeyFilePassword))
.setServiceAccountScopes(googleScopeList);
if (serviceAccountEmail != null) {
b = b.setServiceAccountUser(serviceAccountEmail);
}
credential = b.build();
} catch (IOException | GeneralSecurityException e1) {
throw new RuntimeException("Could not build client secrets", e1);
}
return credential;
}
}
When I have performed this operation, we are seeing that the viewedByMeTime field is actually being updated as the impersonated user.
This is not good, because now people think someone might have stolen access to their account. They are going to open tickets with the security team.
Is this expected? How can I make this stop? Is there another method in the API I can call to download the google docs without updating this timestamp?
Also opened a ticket on the github for the google drive java sdk: https://github.com/googleapis/google-api-java-client-services/issues/3160
Updating the viewedByMeTime field upon calling the endpoint is indeed intended behaviour. Any action performed through the API is considered the same way as if the user did that action manually (i.e. that field would be updated too when the user visits the document through the UI).
By using domain-wise delegation (or "user impersonation"), you have no way to avoid this issue.
The only workaround would be to give the service account access to this file, and let it export the file without domain-wide delegation. The viewedByMeTime field will be updated only for the service account itself, but not for the original owner of that file (or any other user having access to it).
In the QuickStart.java example on Java Quickstart they use OAuth client ID to identify the application, and this pops up a windows asking for Google credentials to use the application. You have to download a client_secret.json to modify a Google Sheet.
My question is: Can you evade the popping up window asking for Google credentials using an API Key or something else? And, if it's possible, how do you change the Java code in order to do that?
An API key could only work when accessing the resources owned by the project that created the key.
For resources like spreadsheets, you're typically accessing resources owned by a user. It would be pretty awful if you got access to my private sheets simply by having an API key.
So no, I wouldn't expect there to be any way to avoid getting authorization to work with a user's documents. However, you should be able to use the Java OAuth library to retain the auth token so you can avoid needing to ask for it more than once. (Unless the user revokes access, of course.)
As DalmTo says, you can use service account credentials if you're trying to access resources owned by the project (or which the project can be granted access to). Note that if you're running on AppEngine, Google Kubernetes Engine or Google Compute Engine, the service account credentials for that environment should be available automatically.
The popup window you are seeing is the Oauth2 consent screen. In order to access private user data you need to have consent of the user in order to access their data.
There is another option its called a service account. If the sheet you are trying to access is one that you as the developer have control of then you can create service account credeitals take the service account email address and grant the service account access to the sheet.
The best example for service account access with java that i am aware of is the one for Google Analytics you will have to alter it for Google sheets i may be able to help with that if you have any issues. hello analytics service account.
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.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
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 = "<REPLACE_WITH_JSON_FILE>";
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();
}
}
/**
* Initializes an Analytics service object.
*
* #return An authorized Analytics service object.
* #throws IOException
* #throws GeneralSecurityException
*/
private static AnalyticsReporting initializeAnalytic() throws GeneralSecurityException, IOException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = GoogleCredential
.fromStream(new FileInputStream(KEY_FILE_LOCATION))
.createScoped(AnalyticsScopes.all());
// 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");
}
}
}
I am using Google Analytics to get the data for my website. I have tested the queries on query explorer. But I am unable to implement it in the code with OAuth. I need a access token to run my query, but my problem is I am unable to get the access token. Can anyone guide me through this.
Can anyone explain the relation between google developer console's to analytics account.
Please refer to some implementation documents.
Assuming this is your own data that you want to access and you have access to the Google Analytics account website. I recommend you use a service account. Hello Analytics API Java
The Google Developer console is where you register your application with Google it has no relation to your Google Analytics account what so ever.
Again I recommend you go with a service account and create service account credentials on the Google Developer console. Take the service account email address add it as a user on your google analytics admin section at the account level give it read access it must be at the account level. This will allow the service account to read your google analytics data.
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");
}
}
}
Code ripped directly from Hello Analytics API: Java quickstart for service accounts
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm trying to figure out how to use the Google OAuth Client Library for Java to authenticate against multiple OpenID connect providers. The example they have here works with Daily Motion. I'd like to see how it works with other providers so I can abstract the differences.
Are there any other examples around that authenticate against say Google perhaps?
At this repo, is an example of how to do this using their library. Here's the code from the main sample:
package com.google.api.services.samples.dailymotion.cmdline;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
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.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
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 java.io.IOException;
import java.util.Arrays;
/**
* A sample application that demonstrates how the Google OAuth2 library can be used to authenticate
* against Google.
*
* #author Brad Parks
*/
public class GoogleAuthExample {
// **********************************************************************
// CHANGE THE FOLLOWING values to the keys you get after following the steps at the following page:
// https://developers.google.com/accounts/docs/OAuth2Login#appsetup
// This should be all you need to do to get this sample to work.
// **********************************************************************
public static final String API_KEY = "Enter your key here";
public static final String API_SECRET = "Enter your key here";
/** Directory to store user credentials. */
private static final java.io.File DATA_STORE_DIR =
new java.io.File(System.getProperty("user.home"), ".store/google_oauth_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 DATA_STORE_FACTORY;
/** OAuth 2 scope. */
private static final String SCOPE = "openid email profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
/** Global instance of the JSON factory. */
static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String TOKEN_SERVER_URL = "https://accounts.google.com/o/oauth2/token";
private static final String AUTHORIZATION_SERVER_URL = "https://accounts.google.com/o/oauth2/auth";
public static final int PORT = 8080;
public static final String DOMAIN = "127.0.0.1";
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
errorIfNotSpecified();
AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken
.queryParameterAccessMethod(),
HTTP_TRANSPORT,
JSON_FACTORY,
new GenericUrl(TOKEN_SERVER_URL),
new ClientParametersAuthentication(
API_KEY, API_SECRET),
API_KEY,
AUTHORIZATION_SERVER_URL).setScopes(Arrays.asList(SCOPE))
.setDataStoreFactory(DATA_STORE_FACTORY).build();
// authorize
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost(DOMAIN).setPort(PORT).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void errorIfNotSpecified() {
if (API_KEY.startsWith("Enter ") || API_SECRET.startsWith("Enter ")) {
System.out.println(
"Enter API Key and API Secret from https://developers.google.com/accounts/docs/OAuth2Login#appsetup"
+ " into API_KEY and API_SECRET in " + GoogleAuthExample.class);
System.exit(1);
}
}
private static void run(HttpRequestFactory requestFactory) throws IOException {
GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/tokeninfo");
HttpRequest request = requestFactory.buildGetRequest(url);
UserInfo userInfo = request.execute().parseAs(UserInfo.class);
System.out.println("Got user info from API after authorization:");
System.out.println("-----------------------------------------------");
System.out.println("issued_to: " + userInfo.issued_to);
System.out.println("audience: " + userInfo.audience);
System.out.println("user_id: " + userInfo.user_id);
System.out.println("scope: " + userInfo.scope);
System.out.println("expires_in: " + userInfo.expires_in);
System.out.println("email: " + userInfo.email);
System.out.println("verified_email: " + userInfo.verified_email);
System.out.println("access_type: " + userInfo.access_type);
}
public static void main(String[] args) {
try {
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
final Credential credential = authorize();
HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
credential.initialize(request);
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
run(requestFactory);
// Success!
return;
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
}
UserInfo.java
package com.google.api.services.samples.dailymotion.cmdline;
import com.google.api.client.util.Key;
public class UserInfo {
#Key
public String issued_to;
#Key
public String audience;
#Key
public String user_id;
#Key
public String scope;
#Key
public Integer expires_in;
#Key
public String email;
#Key
public Boolean verified_email;
#Key
public String access_type;
}
You may consider using oxProx, and openid connect proxy. http://ox.gluu.org/doku.php?id=oxprox:home
Its just being released now, but it solves a few problems: discovery and enabling clients behind the proxy to see the correct 'aud' (i.e. because the proxy issues a new id_token, the correct aud is set for the respective client).
The source code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.Analytics.Data.Ga.Get;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.GaData.ColumnHeaders;
import com.google.api.services.analytics.model.Profile;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Segment;
import com.google.api.services.analytics.model.Segments;
/**
* This class displays an example of a client application using the Google API
* to access the Google Analytics data
*
*
*
*/
#SuppressWarnings("deprecation")
public class GoogleAnalyticsExample {
private static final String SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
private static final String REDIRECT_URL = "urn:ietf:wg:oauth:2.0:oob";
private static final HttpTransport netHttpTransport = new NetHttpTransport();
private static final JacksonFactory jacksonFactory = new JacksonFactory();
private static final String APPLICATION_NAME = "familys";
// FILL THESE IN WITH YOUR VALUES FROM THE API CONSOLE
private static final String CLIENT_ID = "XXXXXX";
private static final String CLIENT_SECRET = "XXXXXX";
public static void main(String args[]) throws HttpResponseException,
IOException {
// Generate the URL to send the user to grant access.
GoogleCredential credential = null;
String authorizationUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID,
REDIRECT_URL, SCOPE).build();
System.out.println("Go to the following link in your browser:");
System.out.println(authorizationUrl);
// Get authorization code from user.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is the authorization code?");
String authorizationCode = null;
try {
authorizationCode = in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
// Use the authorisation code to get an access token
AccessTokenResponse response = null;
try {
response = new GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant(
netHttpTransport, jacksonFactory, CLIENT_ID, CLIENT_SECRET,
authorizationCode, REDIRECT_URL).execute();
} catch (IOException ioe) {
ioe.printStackTrace();
}
// Use the access token to get a new GoogleAccessProtectedResource.
GoogleAccessProtectedResource googleAccessProtectedResource = new GoogleAccessProtectedResource(
response.accessToken, netHttpTransport, jacksonFactory,
CLIENT_ID, CLIENT_SECRET, response.refreshToken);
// Instantiating a Service Object
// Analytics analytics = Analytics
// .Builder(netHttpTransport, jacksonFactory)
// .setHttpRequestInitializer(googleAccessProtectedResource)
// .setApplicationName(APPLICATION_NAME).build();
Analytics analytics = new Analytics.Builder(netHttpTransport, jacksonFactory, credential)
.setHttpRequestInitializer(googleAccessProtectedResource).setApplicationName(APPLICATION_NAME).build();
analytics.getApplicationName();
System.out.println("Application Name: "
+ analytics.getApplicationName());
// Get profile details
Profiles profiles = analytics.management().profiles()
.list("~all", "~all").execute();
displayProfiles(profiles, analytics);
// Get the segment details
Segments segments = analytics.management().segments().list().execute();
displaySegments(segments);
}
/**
* displayProfiles gives all the profile info for this property
* #param profiles
* #param analytics
*/
public static void displayProfiles(Profiles profiles, Analytics analytics) {
for (Profile profile : profiles.getItems()) {
System.out.println("Account ID: " + profile.getAccountId());
System.out
.println("Web Property ID: " + profile.getWebPropertyId());
System.out.println("Web Property Internal ID: "
+ profile.getInternalWebPropertyId());
System.out.println("Profile ID: " + profile.getId());
System.out.println("Profile Name: " + profile.getName());
System.out.println("Profile defaultPage: "
+ profile.getDefaultPage());
System.out.println("Profile Exclude Query Parameters: "
+ profile.getExcludeQueryParameters());
System.out.println("Profile Site Search Query Parameters: "
+ profile.getSiteSearchQueryParameters());
System.out.println("Profile Site Search Category Parameters: "
+ profile.getSiteSearchCategoryParameters());
System.out.println("Profile Currency: " + profile.getCurrency());
System.out.println("Profile Timezone: " + profile.getTimezone());
System.out.println("Profile Updated: " + profile.getUpdated());
System.out.println("Profile Created: " + profile.getCreated());
try {
/**
* The get method follows the builder pattern, where all
* required parameters are passed to the get method and all
* optional parameters can be set through specific setter
* methods.
*/
// Possible to Build API Query with various criteria as below
Get apiQuery = analytics.data().ga()
.get("ga:" + profile.getId(), // Table ID =
// "ga"+ProfileID
"2013-03-21", // Start date
"2013-05-04", // End date
"ga:visits"); // Metrics
apiQuery.setDimensions("ga:source,ga:medium");
apiQuery.setFilters("ga:medium==referral");
apiQuery.setSort("-ga:visits");
apiQuery.setSegment("gaid::-11");
apiQuery.setMaxResults(100);
// Make Data Request
GaData gaData = apiQuery.execute();
if (profile.getId() != null) {
retrieveData(gaData);
}
} catch (IOException e) {
System.out.println("Inside displayProfile method");
e.printStackTrace();
}
}
}
/**
* retrieveData() gets the Google Analytics user data
* #param gaData
*/
public static void retrieveData(GaData gaData) {
// Get Row Data
if (gaData.getTotalResults() > 0) {
// Get the column headers
for (ColumnHeaders header : gaData.getColumnHeaders()) {
System.out.format("%-20s",
header.getName() + '(' + header.getDataType() + ')');
}
System.out.println();
// Print the rows of data.
for (List<String> rowValues : gaData.getRows()) {
for (String value : rowValues) {
System.out.format("%-20s", value);
}
System.out.println();
}
} else {
System.out.println("No data");
}
}
/**
* displaySegments provides Segment details of the account
* #param segments
*/
public static void displaySegments(Segments segments) {
for (Segment segment : segments.getItems()) {
System.out.println("Advanced Segment ID: " + segment.getId());
System.out.println("Advanced Segment Name: " + segment.getName());
System.out.println("Advanced Segment Definition: "
+ segment.getDefinition());
}
}
}
When i run this code it works correctly it gives a link for authorization and i get the authorization code but when the enter the authorization code in the console, it gives this error:
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/api/client/http/HttpParser
at GoogleAnalyticsExample.main(GoogleAnalyticsExample.java:64)
Caused by: java.lang.ClassNotFoundException: com.google.api.client.http.HttpParser
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
Include following jar in your class path ... google-http-client-1.5.0-beta.jar . Also please make sure exact number of jars are included while running and compiling your code.
I have used following jars in my class path . Around 2-3 jars can be excluded from them
jdk1.6.0_21/lib/tools.jar
google-api-client-1.15.0-rc.jar
mysql-connector-java-3.1.7-bin.jar
google-api-services-analytics-v3-rev50-1.15.0-rc.jar
google-api-services-analytics-v3-rev50-1.15.0-rc-javadoc.jar
google-api-services-analytics-v3-rev50-1.15.0-rc-sources.jar
google-http-client-1.15.0-rc.jar
google-http-client-jackson2-1.15.0-rc.jar
jackson-core-2.0.5.jar
google-oauth-client-1.15.0-rc.jar