ソースコード:
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());
}
}
}
このコードを実行すると正しく動作し、認証用のリンクが表示され、認証コードを取得できますが、コンソールに認証コードを入力すると、次のエラーが発生します。
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