使用不同凭据访问Google Analytics报告数据时出现空指针异常

时间:2015-03-11 05:56:15

标签: java nullpointerexception google-oauth google-analytics-api google-api-java-client

我正在关注tutorial,通过使用Google Developers控制台执行简单的GA查询来访问GA帐户报告数据。 我按照教程中提到的所有步骤操作,代码工作正常。

我已经包含了以下代码。

public class GoogleAnalyticsAccess {

    private static final String APPLICATION_NAME = "GAAccess/1.0";
    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".store/analytics_sample");
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static FileDataStoreFactory dataStoreFactory;
    private static HttpTransport httpTransport;

    public static Credential authorizeUser() throws IOException {

        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(
                GoogleAnalyticsAccess.class.getResourceAsStream("/client_secrets.json")));
        if (clientSecrets.getDetails().getClientId().startsWith("Enter") ||
            clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
            System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/?api=analytics " +
                               "into Dashboard/src/main/resources/client_secrets.json");
            System.exit(1);
        }
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
                                                                                   clientSecrets, Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY))
                .setDataStoreFactory(dataStoreFactory).build();

        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

    public static Analytics getAnalyticsServiceObject(Credential credential){

        return new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                                                                             .build();
    }

    public static String getGAAccountId(Analytics analytics) throws IOException {

        String accountId =null;

        Accounts accounts = analytics.management().accounts().list().execute();
        List<Account> accountsList = accounts.getItems();

        if(accountsList.isEmpty()){
            System.err.println("No accounts found");
        }
        else{

            for(int i=0; i<accountsList.size();i++){
                if(accountsList.get(i).getName().equals("XXXX")){
                    accountId = accountsList.get(i).getId();
                    break;
                }
            }
        }

        return accountId;
    }

    public static String getGAWebPropertyId(Analytics analytics,String accountId) throws IOException {

        String webPropertyId = null;

        Webproperties webProperties = null;

        webProperties = analytics.management().webproperties().list(accountId).execute();
        List<Webproperty> webPropertiesList = webProperties.getItems();

        if (webPropertiesList.isEmpty()) {
            System.err.println("No Web Properties found");
        } else {

            for (int i=0; i<webPropertiesList.size();i++){
                if(webPropertiesList.get(i).getName().equals("XXXX")){
                    webPropertyId = webPropertiesList.get(i).getId();
                }
            }
        }

        return webPropertyId;
    }

    public static String getGAViewId(Analytics analytics, String accountId, String webPropertyId) throws IOException {

        String viewId = null;

        Profiles views = analytics.management().profiles().list(accountId, webPropertyId).execute();
        List<Profile> viewsList = views.getItems();

        if (viewsList.isEmpty()) {
            System.err.println("No profiles found");
        } else {
            for(int i=0; i<viewsList.size();i++){
                if(viewsList.get(i).getName().equals("XXXX")){
                    viewId = viewsList.get(i).getId();
                }
            }
        }

        return viewId;

    }

    public static List<GoogleAnalyticsData> executeGAQuery(Analytics analytics, String viewId, String dimension) throws IOException {

        List<GoogleAnalyticsData> dataList = new ArrayList<GoogleAnalyticsData>();

        if (viewId == null) {
            System.err.println("No profiles found.");
        } else {
            GaData gaData = analytics.data().ga().get("ga:" + viewId, "2015-02-13", "2015-02-27", "ga:users")
                                     .setDimensions("ga:" + dimension)
                                     .setMaxResults(200).execute();

            if (gaData.getRows() == null || gaData.getRows().isEmpty()) {
                System.out.println("No results Found.");
            } else {
                GoogleAnalyticsData data;
                for (List<String> row : gaData.getRows()) {
                    data = new GoogleAnalyticsData();
                    data.setName(row.get(0));
                    data.setValue(Integer.parseInt(row.get(1)));

                    dataList.add(data);
                }
            }
        }

        return dataList;
    }

    public static void main(String[] args) throws GeneralSecurityException, IOException {

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

        Credential credential = authorizeUser();
        Analytics analytics = getAnalyticsServiceObject(credential);
        String accountId = getGAAccountId(analytics);
        String webPropertyId = getGAWebPropertyId(analytics,accountId);
        String viewId = getGAViewId(analytics,accountId,webPropertyId);

        List<GoogleAnalyticsData> continentDataList = executeGAQuery(analytics, viewId, "continent");
        List<GoogleAnalyticsData> countryDataList = executeGAQuery(analytics, viewId, "country");

        for(int i =0; i <continentDataList.size();i++){
            System.out.println(continentDataList.get(i).getName() + " " + continentDataList.get(i).getValue());

        }

        for(int i=0; i< countryDataList.size();i++){
            System.out.println(countryDataList.get(i).getName() + " " + countryDataList.get(i).getValue());
        }

    }

}

当我通过提供对该报告数据也具有共享访问权限的其他用户的凭据(客户端机密和ID)来访问相同的GA帐户报告数据时,我收到错误。 我已成功使用其他用户凭据访问报告数据如果我已经使用我的凭据首先运行了Java应用程序。但是如果我首先使用其他用户凭据运行应用程序,那么我会收到以下错误。

堆栈跟踪如下所示。

Exception in thread "main" java.lang.NullPointerException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:92)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at org.dashboard.access.data.GoogleAnalyticsAccess.getGAAccountId(GoogleAnalyticsAccess.java:266)
at org.dashboard.access.data.GoogleAnalyticsAccess.main(GoogleAnalyticsAccess.java:364)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

特定异常发生在getGAAccountId方法的以下行中。

Accounts accounts = analytics.management().accounts().list().execute();

此问题是否有解决方法?

1 个答案:

答案 0 :(得分:3)

如果你的client_secrets.json配置得很好,你只需要删除文件.store / analytics_sample并再次运行它。