# Calling Contacts Api Service Account Authentication



## Illoyon (19. Aug 2016)

Hey,

ich versuche Google Kontakte auszulesen über nen Service Account, wie beschrieben in diesem Guide:

https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority

bin  dem ganzen soweit gefolt und habe meinem Serviceaccount "domain-wide access" delegiert. Wenn ich nun aber mein Programm durchlaufen lasse bekomme ich eine NullPoinnterExeption wie folgt:


Spoiler: NPE





```
Exception in thread "main" java.lang.NullPointerException: No authentication header information
at com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96)
    at com.google.gdata.util.AuthenticationException.<init>(AuthenticationException.java:67)
    at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:608)
    at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
    at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
    at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
    at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
    at com.google.gdata.client.Service.getFeed(Service.java:1135)
    at com.google.gdata.client.Service.getFeed(Service.java:998)
    at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:644)
    at com.google.gdata.client.Service.getFeed(Service.java:1017)
    at net.wunds.google.GoogleContactsAccess.printAllContacts(GoogleContactsAccess.java:280)
    at Main.main(Main.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1
```




Mein Code sieht so aus:


Spoiler: Authentifizierung





```
public class Authentifizierung {
    private static final String APPLICATION_NAME = "APIProjekt";

    private static FileDataStoreFactory dataStoreFactory;
    private static HttpTransport httpTransport;
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static Oauth2 oauth2;

    public static Credential impersonateUser() throws GeneralSecurityException, IOException {
        //System.out.println("Credentials erzeugen start");
        //String emailAddress = "apiprojektdienstkonto@qu....iam.gserviceaccount.com";
        Set<String> scopes = new HashSet<String>();
        scopes.add("https://www.google.com/m8/feeds");
        GoogleCredential credential = null;
            credential = new GoogleCredential.Builder()
                    .setTransport(httpTransport)
                    .setJsonFactory(JSON_FACTORY)
                    .setServiceAccountId("ProjektDienstkontoMail@quixotic-access....iam.gserviceaccount.com")
                    .setServiceAccountPrivateKeyFromP12File(new File("./resource/APIProjekt-x1234567891x.p12"))
                    .setServiceAccountScopes(scopes)
                    .setServiceAccountUser("user@email.com")
                    .build();
        //System.out.println("Credentials erzeugen ende");
        return credential;
    }
```






Spoiler: ContactsService





```
public class GoogleContactsAccess {

    public static ContactsService createService() {
        ContactsService myService = new ContactsService("APIProjekt");
        try {
            myService.setOAuth2Credentials(Authentifizierung.impersonateUser());
            return myService;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return myService;
    }

    public static void printAllContacts()
        throws ServiceException, IOException {
    ContactsService myService = new ContactsService ("APIProjekt");
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
    ContactFeed resultFeed = myService.getFeed(feedUrl, ContactFeed.class);
    // Print the results
    System.out.println(resultFeed.getTitle().getPlainText());
    for (ContactEntry entry : resultFeed.getEntries()) {
        System.out.println("GoogleID?: " + entry.getId());
        System.out.println("self id: " + entry.getSelfLink().getHref());
        if (entry.hasName()) {
            Name name = entry.getName();
            if (name.hasFullName()) {
                String fullNameToDisplay = name.getFullName().getValue();
                if (name.getFullName().hasYomi()) {
                    fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
                }
                System.out.println("\t\t" + fullNameToDisplay);
            } else {
                System.out.println("\t\t (no full name found)");
            }
            if (name.hasNamePrefix()) {
                System.out.println("\t\t" + name.getNamePrefix().getValue());
            } else {
                System.out.println("\t\t (no name prefix found)");
            }
            if (name.hasGivenName()) {
                String givenNameToDisplay = name.getGivenName().getValue();
                if (name.getGivenName().hasYomi()) {
                    givenNameToDisplay += " (" + name.getGivenName().getYomi() + ")";
                }
                System.out.println("\t\t" + givenNameToDisplay);
            } else {
                System.out.println("\t\t (no given name found)");
            }
            if (name.hasAdditionalName()) {
                String additionalNameToDisplay = name.getAdditionalName().getValue();
                if (name.getAdditionalName().hasYomi()) {
                    additionalNameToDisplay += " (" + name.getAdditionalName().getYomi() + ")";
                }
                System.out.println("\t\t" + additionalNameToDisplay);
            } else {
                System.out.println("\t\t (no additional name found)");
            }
            if (name.hasFamilyName()) {
                String familyNameToDisplay = name.getFamilyName().getValue();
                if (name.getFamilyName().hasYomi()) {
                    familyNameToDisplay += " (" + name.getFamilyName().getYomi() + ")";
                }
                System.out.println("\t\t" + familyNameToDisplay);
            } else {
                System.out.println("\t\t (no family name found)");
            }
            if (name.hasNameSuffix()) {
                System.out.println("\t\t" + name.getNameSuffix().getValue());
            } else {
                System.out.println("\t\t (no name suffix found)");
            }
        } else {
            System.out.println("\t (no name found)");
        }
        System.out.println("Email addresses:");
        for (Email email : entry.getEmailAddresses()) {
            System.out.print(" " + email.getAddress());
            if (email.getRel() != null) {
                System.out.print(" rel:" + email.getRel());
            }
            if (email.getLabel() != null) {
                System.out.print(" label:" + email.getLabel());
            }
            if (email.getPrimary()) {
                System.out.print(" (primary) ");
            }
            System.out.print("\n");
        }
        System.out.println("IM addresses:");
        for (Im im : entry.getImAddresses()) {
            System.out.print(" " + im.getAddress());
            if (im.getLabel() != null) {
                System.out.print(" label:" + im.getLabel());
            }
            if (im.getRel() != null) {
                System.out.print(" rel:" + im.getRel());
            }
            if (im.getProtocol() != null) {
                System.out.print(" protocol:" + im.getProtocol());
            }
            if (im.getPrimary()) {
                System.out.print(" (primary) ");
            }
            System.out.print("\n");
        }
        System.out.println("Groups:");
        for (GroupMembershipInfo group : entry.getGroupMembershipInfos()) {
            String groupHref = group.getHref();
            System.out.println("  Id: " + groupHref);
        }
        System.out.println("Extended Properties:");
        for (ExtendedProperty property : entry.getExtendedProperties()) {
            if (property.getValue() != null) {
                System.out.println("  " + property.getName() + "(value) = " +
                        property.getValue());
            } else if (property.getXmlBlob() != null) {
                System.out.println("  " + property.getName() + "(xmlBlob)= " +
                        property.getXmlBlob().getBlob());
            }
        }
        Link photoLink = entry.getContactPhotoLink();
        String photoLinkHref = photoLink.getHref();
        System.out.println("Photo Link: " + photoLinkHref);
        if (photoLink.getEtag() != null) {
            System.out.println("Contact Photo's ETag: " + photoLink.getEtag());
        }
        System.out.println("Contact's ETag: " + entry.getEtag());
    }
}
```






Spoiler: Main Methode





```
public class Main {

    public static void main(String[] args) {
        try {
            GoogleContactsAccess.printAllContacts();
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
```



Jemand ne Idee was schief läuft? Das Credential Objekt wird erstellt, aber danach kracht es.

Edit: Nutze IntelliJ btw.


----------



## Joose (19. Aug 2016)

In deiner Methode `createService` erstellst du einen Service und fügst Credentials Informationen hinzu.
Das Problem liegt dann daran das du diese Methode nicht verwendest und stattdessen in `printAllContacts` ein Service erstellst ohn diesen Informationen.


----------



## Illoyon (19. Aug 2016)

Joose hat gesagt.:


> In deiner Methode `createService` erstellst du einen Service und fügst Credentials Informationen hinzu.
> Das Problem liegt dann daran das du diese Methode nicht verwendest und stattdessen in `printAllContacts` ein Service erstellst ohn diesen Informationen.


Komisch weiß nicht wie das jetzt passiert ist, habs auf jedenfall geändert, createService habe ich auskommentiert, printAllContacts sieht jetzt so aus:


Spoiler: printAllContacts





```
public static void printAllContacts()
        throws ServiceException, IOException {
    ContactsService myService = new ContactsService ("APIProjekt");

    try {
        myService.setOAuth2Credentials(Authentifizierung.impersonateUser());
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }

    URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
    Query myQuery = new Query(feedUrl);
    ContactFeed resultFeed = myService.query(myQuery, ContactFeed.class);
    // Print the results

    for (ContactEntry entry : resultFeed.getEntries()) {
        System.out.println(entry.getName().getFullName().getValue());
        System.out.println("Updated on: " + entry.getUpdated().toStringRfc822());
    }
    System.out.println(resultFeed.getTitle().getPlainText());
    for (ContactEntry entry : resultFeed.getEntries()) {
        System.out.println("GoogleID?: " + entry.getId());
        System.out.println("self id: " + entry.getSelfLink().getHref());
        if (entry.hasName()) {
            Name name = entry.getName();
            if (name.hasFullName()) {
                String fullNameToDisplay = name.getFullName().getValue();
                if (name.getFullName().hasYomi()) {
                    fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
                }
                System.out.println("\t\t" + fullNameToDisplay);
            } else {
                System.out.println("\t\t (no full name found)");
            }
            if (name.hasNamePrefix()) {
                System.out.println("\t\t" + name.getNamePrefix().getValue());
            } else {
                System.out.println("\t\t (no name prefix found)");
            }
            if (name.hasGivenName()) {
                String givenNameToDisplay = name.getGivenName().getValue();
                if (name.getGivenName().hasYomi()) {
                    givenNameToDisplay += " (" + name.getGivenName().getYomi() + ")";
                }
                System.out.println("\t\t" + givenNameToDisplay);
            } else {
                System.out.println("\t\t (no given name found)");
            }
            if (name.hasAdditionalName()) {
                String additionalNameToDisplay = name.getAdditionalName().getValue();
                if (name.getAdditionalName().hasYomi()) {
                    additionalNameToDisplay += " (" + name.getAdditionalName().getYomi() + ")";
                }
                System.out.println("\t\t" + additionalNameToDisplay);
            } else {
                System.out.println("\t\t (no additional name found)");
            }
            if (name.hasFamilyName()) {
                String familyNameToDisplay = name.getFamilyName().getValue();
                if (name.getFamilyName().hasYomi()) {
                    familyNameToDisplay += " (" + name.getFamilyName().getYomi() + ")";
                }
                System.out.println("\t\t" + familyNameToDisplay);
            } else {
                System.out.println("\t\t (no family name found)");
            }
            if (name.hasNameSuffix()) {
                System.out.println("\t\t" + name.getNameSuffix().getValue());
            } else {
                System.out.println("\t\t (no name suffix found)");
            }
        } else {
            System.out.println("\t (no name found)");
        }
        System.out.println("Email addresses:");
        for (Email email : entry.getEmailAddresses()) {
            System.out.print(" " + email.getAddress());
            if (email.getRel() != null) {
                System.out.print(" rel:" + email.getRel());
            }
            if (email.getLabel() != null) {
                System.out.print(" label:" + email.getLabel());
            }
            if (email.getPrimary()) {
                System.out.print(" (primary) ");
            }
            System.out.print("\n");
        }
        System.out.println("IM addresses:");
        for (Im im : entry.getImAddresses()) {
            System.out.print(" " + im.getAddress());
            if (im.getLabel() != null) {
                System.out.print(" label:" + im.getLabel());
            }
            if (im.getRel() != null) {
                System.out.print(" rel:" + im.getRel());
            }
            if (im.getProtocol() != null) {
                System.out.print(" protocol:" + im.getProtocol());
            }
            if (im.getPrimary()) {
                System.out.print(" (primary) ");
            }
            System.out.print("\n");
        }
        System.out.println("Groups:");
        for (GroupMembershipInfo group : entry.getGroupMembershipInfos()) {
            String groupHref = group.getHref();
            System.out.println("  Id: " + groupHref);
        }
        System.out.println("Extended Properties:");
        for (ExtendedProperty property : entry.getExtendedProperties()) {
            if (property.getValue() != null) {
                System.out.println("  " + property.getName() + "(value) = " +
                        property.getValue());
            } else if (property.getXmlBlob() != null) {
                System.out.println("  " + property.getName() + "(xmlBlob)= " +
                        property.getXmlBlob().getBlob());
            }
        }
        Link photoLink = entry.getContactPhotoLink();
        String photoLinkHref = photoLink.getHref();
        System.out.println("Photo Link: " + photoLinkHref);
        if (photoLink.getEtag() != null) {
            System.out.println("Contact Photo's ETag: " + photoLink.getEtag());
        }
        System.out.println("Contact's ETag: " + entry.getEtag());
    }
}
```



...bekomme aber immer noch den selben Fehler.


----------



## Joose (19. Aug 2016)

Vielleicht helfen dir diese beiden Links weiter:
http://stackoverflow.com/questions/...ing-to-refresh-access-token/26466985#26466985
http://stackoverflow.com/questions/...g-nullpointerexception-no-authentication-head


----------



## Illoyon (19. Aug 2016)

Joose hat gesagt.:


> Vielleicht helfen dir diese beiden Links weiter:
> http://stackoverflow.com/questions/...ing-to-refresh-access-token/26466985#26466985
> http://stackoverflow.com/questions/...g-nullpointerexception-no-authentication-head


Hat mich tatsächlich ein wenig weiter gebracht, habe

```
credential.refreshToken();
```
eingefügt gleich nachdem mein Objekt gebaut wird, allerdings nur um dann die nächste NPE zu bekommen:

```
Exception in thread "main" java.lang.NullPointerException
    at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:213)
    at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
    at com.google.api.client.auth.oauth2.TokenRequest.<init>(TokenRequest.java:94)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:380)
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
    at net.wunds.google.Authentifizierung.impersonateUser(Authentifizierung.java:88)
    at net.wunds.google.GoogleContactsAccess.printAllContacts(GoogleContactsAccess.java:265)
    at Main.main(Main.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1
```


----------



## Joose (19. Aug 2016)

http://stackoverflow.com/questions/...-have-setserviceaccountuser-for-googlecredent


----------



## Illoyon (19. Aug 2016)

Joose hat gesagt.:


> http://stackoverflow.com/questions/...-have-setserviceaccountuser-for-googlecredent


Verstehe jetzt nicht so ganz wie mir der Link helfen soll, das hier habe ich ja schon getan:


> "If you have delegated domain-wide access to the service account and you want to impersonate a user account, specify the email address of the user account with the setServiceAccountUser method of the GoogleCredential factory..."


----------



## Illoyon (22. Aug 2016)

Ok hat sich erledigt, ich Idiot hatte die Variable httpTransport nicht richtig deklariert, jetzt funktionierts.


----------

