Hello Analytics API:Java快速入门错误 [英] Hello Analytics API: Java quickstart errors

查看:74
本文介绍了Hello Analytics API:Java快速入门错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java从Google Analytics(分析)报告API中访问数据.

I'm trying to access data from the Google analytics reporting API using Java.

我正在遵循" Hello Analytics API: Java快速入门(针对已安装的应用程序)"教程,我完成了它告诉您的一切,并且遇到了以下问题:

I was following the "Hello Analytics API: Java quickstart for installed applications" tutorial, and i did everything it tells you, and i get following issues:

com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\<user>\.store\hello_analytics
com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\timst\.store\hello_analytics
java.lang.NullPointerException
          at java.io.Reader.<init>(Reader.java:78)
          at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
          at com.example.demo.HelloAnalytics.initializeAnalytics(HelloAnalytics.java:60)
          at com.example.demo.HelloAnalytics.main(HelloAnalytics.java:44)

我尝试使用client_secret.json的完整路径. 尝试使用我在网上找到的其他方法,但似乎没有任何效果.

I tried using the full path for the client_secret.json. tried using different methods i found online, but none seem to work.

对此错误感到沮丧后,我尝试了" Hello Analytics API:服务帐户的Java快速入门"教程.

After getting frustrated by this error i tried the "Hello Analytics API: Java quickstart for service accounts" tutorial.

但是在这里我有一个问题,我无法将用户添加到我可以访问的帐户,媒体资源或视图中. 我可以访问其他人的分析帐户,并且只能将自己从这些帐户中删除.

But here i have the issue that i can't add users to the account, property or view for the accounts i can access. I have access to other peoples analytics accounts and I can only remove myself from the accounts.

我正在使用的所有代码均来自教程,分别使用Intellijgradle.

All code I'm using is from the tutorials, using Intellij and gradle.

tl;dr;我要做的就是访问我所有的分析数据 帐户,使用报告API,这样我就可以将所有这些数据放在自己的帐户中 数据库,并将此数据库用于其他项目. Google提供的教程对我不起作用. (数据主要是Google Adwords数据.)

tl;dr; All I want to do is access the analytics data for all my accounts, using the reporting API so i can put all this data in my own database and use this database for my other projects. the Tutorials google provides doesn't work for me. (the data is mostly Google Adwords data.)

推荐答案

所以警告不是问题,这是一个已知问题,在Windows上无法正常工作.

So the Warning is not the problem, it's a known issue with it not working properly on windows.

java.lang.NullPointerException是因为我调用的配置文件没有给定指标的数据行.因此调用的返回值没有.getRows()方法,因为没有行值.

The java.lang.NullPointerException is because the profile I call to has no rows of data for the given metric. so the return value of the call doesn't have a .getRows() methode because there isn't a row value.

您应该检查该行的第一个,

you should check for the row's first,

GaData results;
 if (null != results) {
     if(results.get("rows") != null){
          if (!results.getRows().isEmpty()){
               //do something with the rows exp.
               for (List<String> row : results.getRows()) {
                    for (int i=0; i<results.getColumnHeaders().size();i++) {
                        List<GaData.ColumnHeaders> headers = results.getColumnHeaders();
                        System.out.println( headers.get(i).getName()+": " + row.get(i));
                    }
                }
          }
     }
}

在该示例中,我还使用了ColumnHeaders,但也应首先检查.

In the example I also use the ColumnHeaders, wich you should also check first.

检查每个我有权访问的帐户以及每个webProperty和Profile也很容易,而不仅是检查每个帐户的第一个值.

It was also easier to check every single account i had access to and every webProperty and Profile and not just the first value of each of those.

此外,查询浏览器确实很有用.您应该使用它来检查可以使用的指标和尺寸.

Also, the query explorer is really useful. you should use it to check out which metrics you can use and which dimensions.

这是我完整的HelloAnalytics类,我只是打印对控制台可能有用的所有内容,我还使用getResults方法中的多个指标和Google AdWords的维度:

Here is my full HelloAnalytics class i just print everything that might be usefull to the console i also use multiple metrics and a dimension from Google AdWords in the getResults methode:

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.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.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * A simple example of how to access the Google Analytics API.
 */
public class HelloAnalytics {
    // Path to client_secrets.json file downloaded from the Developer's Console.
    // The path is relative to HelloAnalytics.java.
    private static final String CLIENT_SECRET_JSON_RESOURCE = "/client_secret.json";
    // The directory where the user's credentials will be stored.
    private static final File DATA_STORE_DIR = new File("out/DataStore/hello_analytics");
    private static final File OUTPUT_FILE = new File("out/DataStore/output.text");

    private static final String APPLICATION_NAME = "Online Marketing Buddy";
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static NetHttpTransport httpTransport;
    private static FileDataStoreFactory dataStoreFactory;

    public static void main(String[] args) {
        try {

            Analytics analytics = initializeAnalytics();
            getProfileIds(analytics);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Analytics initializeAnalytics() throws Exception {

        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

        // Load client secrets.
        InputStream in =
                HelloAnalytics.class.getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE);
        GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Set up authorization code flow for all auth scopes.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
                .Builder(httpTransport, JSON_FACTORY, clientSecrets,AnalyticsScopes.all())
                .setDataStoreFactory(dataStoreFactory)
                .build();

        // Authorize.
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
                .authorize("user");

        // Construct the Analytics service object.
        Analytics response = new Analytics
                .Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();

        return response;
    }

    private static void getProfileIds(Analytics analytics) throws IOException {
        // Get the all view (profile) IDs for the authorized user.
        List<String> profileIds = new ArrayList<>();

        // 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 {
            for (Account account : accounts.getItems()) {
                System.out.println("account: " + account.getName());
                String accountId = account.getId();

                // Query for the list of properties associated with the each account.
                Webproperties properties = analytics.management().webproperties()
                        .list(accountId).execute();

                if (properties.getItems().isEmpty()) {
                    System.err.println("No properties found for accountId: " + accountId);
                } else {
                    for (Webproperty webproperty : properties.getItems()) {
                        System.out.println("\nwebproperty: " + webproperty.getName());
                        String webpropertyId = webproperty.getId();

                        // Query for the list views (profiles) associated with the property.
                        Profiles profiles = analytics.management().profiles()
                                .list(accountId, webpropertyId).execute();

                        if (profiles.getItems().isEmpty()) {
                            System.err.println("No views (profiles) found for accoundId: " + accountId + "and webpropertyId: " + webpropertyId);
                        } else {
                            // Return the first (view) profile associated with the property.
                            for (Profile profile : profiles.getItems()) {
                                System.out.println("\nprofileId added for profile: " + profile.getName());
                                profileIds.add(profile.getId());
                                printResults(getResults(analytics,profile.getId()), profile.getId());
                            }
                        }
                        System.out.println("---------- ---------- end webproperty: " + webproperty.getName() + "---------- ----------");
                    }
                }
                System.out.println("---------- ---------- end account: " + account.getName() + "---------- ----------");
            }
        }
    }

    private static GaData getResults(Analytics analytics, String profileId) throws IOException {
        // Query the Core Reporting API for the number of sessions
        // in the past 30 days.
        GaData data = analytics.data().ga()
                .get("ga:" + profileId, "30daysAgo", "yesterday", "ga:adClicks, ga:adCost, ga:transactions, ga:transactionRevenue, ga:users, ga:sessions")
                .setDimensions("ga:adwordsCampaignID")
                .execute();
        return data;
    }

    private static void printResults(GaData results, String profile) {
        // Parse the response from the Core Reporting API for
        // the profile name and number of sessions.
        if (null != results) {
            System.out.println("View (Profile: " + profile + ") Name: "
                    + results.getProfileInfo().getProfileName() + "\n");
            if (results.get("rows") != null && results.get("columnHeaders") != null) {
                if (!results.getRows().isEmpty() && !results.getColumnHeaders().isEmpty()) {
                    for (List<String> row : results.getRows()) {
                        for (int i=0; i<results.getColumnHeaders().size();i++) {
                            List<GaData.ColumnHeaders> headers = results.getColumnHeaders();
                            System.out.println( headers.get(i).getName()+": " + row.get(i) + "\n");
                        }
                        System.out.println("---------- ---------- ----------\n");
                    }
                } else {
                    System.out.println("No rows or columHeaders empty\n");
                }
            } else {
                System.out.println("No rows or columHeaders\n");
            }
        }
    }
}

这篇关于Hello Analytics API:Java快速入门错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆