您的位置:首页 > 编程语言 > Java开发

JAVA 下载Google Analytics 数据简单Demo

2013-02-19 17:15 225 查看
采用JAVA 获取google analytics产生的流量检测数据。

配置:JDK5.0及以上

GoogleAnalytics.java
package com.cms.util;

//	 Copyright 2010 Google Inc. All Rights Reserved.
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0 *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.gdata.client.analytics.AnalyticsService;
import com.google.gdata.client.analytics.DataQuery;
import com.google.gdata.data.analytics.DataFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
* This application demos the "AnalyticsCsvPrinter" class, which converts a
* response from the Data Export API into CSV format.
*
* @author api.alexl@google.com (Alexander Lucas)
*/
public class GoogleAnalytics {

private static final String CLIENT_USERNAME = "test.ga@gmail.com";//邮箱帐号
private static final String CLIENT_PASS = "123456";//PASSWORD
private static final String TABLE_ID = "ga:67972528";//配置ID

private static AnalyticsCsvPrinter printer = new AnalyticsCsvPrinter();
/**
* Grabs the response feed and prints it in CSV format
* to standard output.
* @param args Command Line Arguments.
*/
public static void main(String[] args) {
System.out.println("come...");
DataFeed feed = getDataFeed(getAnalyticsService("cvs_printing_demo"), getDataQuery());

if(args.length > 0) {

printFeedToFile(feed, args[0]);
} else {
// If no output stream is set, the default is to print to stdout.
printer.printFeedAsCsv(feed);
}
}

/**
* Opens a write stream to a file, and sets that as the output stream for the
* printer object that prints the feed.
* @param feed The DataFeed to convert to CSV format.
* @param filename The filename to be written to.
*/
private static void printFeedToFile(DataFeed feed, String filename) {
PrintStream stream = null;
try {
FileOutputStream fstream = new FileOutputStream(filename);
stream = new PrintStream(fstream);
printer.setPrintStream(stream);
printer.printFeedAsCsv(feed);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} finally {
if (stream != null) {
stream.flush();
stream.close();
}
}
}

/**
* Creates and returns a new AnalyticsService object and authorizes the user using
* Client Login.
* @return AnalyticsService to be used
*/
private static AnalyticsService getAnalyticsService(String clientName) {
try {
AnalyticsService analyticsService = new AnalyticsService(clientName);
analyticsService.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
System.out.println("login ok...");
return analyticsService;
} catch (AuthenticationException e) {
System.err.println("Authentication failed : " + e.getMessage());
System.exit(-1);
}
return null;
}

/**
* Creates and returns the default DataQuery.
*
* @return AnalyticsService to be used
*/
private static DataQuery getDataQuery() {
DataQuery query = null;
try {
// Create a query using the DataQuery Object.
query = new DataQuery(new URL(
"https://www.google.com/analytics/feeds/data"));
query.setStartDate("2012-01-01");
query.setEndDate("2013-04-30");
query.setDimensions("ga:pageTitle,ga:pagePath");
query.setMetrics("ga:visits,ga:pageviews");
query.setSort("-ga:pageviews");
query.setMaxResults(10);
query.setIds(TABLE_ID);
System.out.println("Query...");
} catch (MalformedURLException e) {
System.err.println("Error, malformed URL: " + e.getMessage());
System.exit(-1);
}
return query;
}

/**
* Makes the actual request to the server.
*
* @param analyticsService Google Analytics service object that
*     is authorized through Client Login.
* @param query the query being sent to the Data Export API.
* @returns the responds from the Data Export API.
*/
private static DataFeed getDataFeed(AnalyticsService analyticsService, DataQuery query) {
DataFeed dataFeed = null;
try {
// Make a request to the API.
dataFeed = analyticsService.getFeed(query.getUrl(), DataFeed.class);
} catch (IOException e) {
System.err.println("Network error trying to retrieve feed: " + e.getMessage());
System.exit(-1);
} catch (ServiceException e) {
System.err.println("Analytics API responded with an error message: " + e.getMessage());
System.exit(-1);
}
return dataFeed;

}

}

AnalyticsCsvPrinter.java

package com.cms.util;

//Copyright 2010 Google Inc. All Rights Reserved.
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0 *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import com.google.gdata.data.analytics.DataEntry;
import com.google.gdata.data.analytics.DataFeed;
import com.google.gdata.data.analytics.Dimension;
import com.google.gdata.data.analytics.Metric;

import java.io.PrintStream;
import java.util.Iterator;

/**
* A class which converts a DataFeed object into a series of data rows in the
* CSV format.
*
* @author api.alexl@google.com (Alexander Lucas)
*/
public class AnalyticsCsvPrinter {

private PrintStream printStream = System.out;

/**
* Returns the output stream this object will write output to.
*
* @return The output stream this object will write output to.
*/
public PrintStream getPrintStream() {
return printStream;
}

/**
* Sets the output stream this object will write output to.
*
* @param printStream The output stream this object will write output to.
*/
public void setPrintStream(PrintStream printStream) {
this.printStream = printStream;
}

/**
* Prints the contents of a Data Feed in CSV format, to the output stream
* specified using "setPrintStream".  Uses System.out by default.  This
* method prints row headers.  To print multiple queries to one output, one
* can also use "printEntries", which does not print row headers.
*
* @param feed The feed whose contents are printed in CSV format.
*/
public void printFeedAsCsv(DataFeed feed) {
printRowHeaders(feed);
printBody(feed);
}

/**
* Prints all the entries in a feed in CSV format.  Does *not* print
* row headers.
*
* @param feed The feed whose contents are printed in CSV format.
*/
public void printBody(DataFeed feed) {
if(feed.getEntries().size() == 0) {
return;
}

for (DataEntry entry : feed.getEntries()) {
printEntry(entry);
}
}

/**
* Prints all the values in a data feed entry in CSV format.
*
* @param entry The data entry whose contents are printed in CSV format.
*/
public void printEntry(DataEntry entry) {
Iterator<Dimension> dimensions = entry.getDimensions().iterator();
while (dimensions.hasNext()) {
printStream.print(sanitizeForCsv(dimensions.next().getValue()));
printStream.print(",");
}

Iterator<Metric> metrics = entry.getMetrics().iterator();
while (metrics.hasNext()) {
printStream.print(sanitizeForCsv(metrics.next().getValue()));
if (metrics.hasNext()) {
printStream.print(",");
}
}
printStream.println();
}

/**
* Prints the row headers (column names) of a feed.
*
* @param feed The feed whose row headers are to be printed.
*/
public void printRowHeaders(DataFeed feed) {
if(feed.getEntries().size() == 0) {
return;
}

DataEntry firstEntry = feed.getEntries().get(0);

Iterator<Dimension> dimensions = firstEntry.getDimensions().iterator();
while (dimensions.hasNext()) {
printStream.print(sanitizeForCsv(dimensions.next().getName()));
printStream.print(",");
}

Iterator<Metric> metrics = firstEntry.getMetrics().iterator();
while (metrics.hasNext()) {
printStream.print(sanitizeForCsv(metrics.next().getName()));
if (metrics.hasNext()) {
printStream.print(",");
}
}
printStream.println();

}

/**
* Modifies a string so that it is a valid cell in a CSV document.
* Note that this method works on a single value, not a whole row of data.
*
* @param cellData The string to be made CSV-compatible.
* @return a version of the string which works as a single CSV cell.
*/
private String sanitizeForCsv(String cellData) {
// Since most sanitizing will involve wrapping the string in double quotes,
// check and see if double quotes that are part of the string value already exist.
// If they do, escape them.  Escaping a double quote is done by placing an
// extra one right next to it, so " becomes "".
StringBuilder resultBuilder = new StringBuilder(cellData);
int lastIndex = 0;
while (resultBuilder.indexOf("\"", lastIndex) >= 0) {
int quoteIndex = resultBuilder.indexOf("\"", lastIndex);
resultBuilder.replace(quoteIndex, quoteIndex + 1, "\"\"");
lastIndex = quoteIndex + 2;
}

// Several conditions are solved by wrapping the value in double quotes.
// Since this should only happen once per escaped string, we can check
// for all conditions simultaneously.  The conditions are:
// -Comma in the cellData value
// -Line break in the cellData value
// -Leading or trailing whitespace in the celldata value

char firstChar = cellData.charAt(0);
char lastChar = cellData.charAt(cellData.length() - 1);

if (cellData.contains(",") ||
cellData.contains("\n") ||
Character.isWhitespace(firstChar) ||
Character.isWhitespace(lastChar)) {
resultBuilder.insert(0, "\"").append("\"");
}
return resultBuilder.toString();
}
}


提供一个Demo下载地址:http://download.csdn.net/detail/thl331860203/5072926
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: