ServiceAccounts { static String serviceAccountEmail(GoogleCredentials credentials) { if (credentials instanceof ImpersonatedCredentials) { return ((ImpersonatedCredentials) credentials).toBuilder().getTargetPrincipal(); } else if (credentials instanceof ServiceAccountSigner) { return ((ServiceAccountSigner) credentials).getAccount(); } else { throw new IllegalArgumentException("Credential is not a service account"); } } private  ServiceAccounts();   }
@Test public void serviceAccountEmailImpersonatedCredentials() { var credentials = ImpersonatedCredentials.create( sourceCredentials, SERVICE_ACCOUNT, List.of(), List.of(), 300); assertThat(ServiceAccounts.serviceAccountEmail(credentials), is(SERVICE_ACCOUNT)); }
@Test public void serviceAccountEmailServiceAccountCredentials() { var credentials = ServiceAccountCredentials.newBuilder() .setClientEmail(SERVICE_ACCOUNT) .setPrivateKey(privateKey) .build(); assertThat(ServiceAccounts.serviceAccountEmail(credentials), is(SERVICE_ACCOUNT)); }
@Test public void serviceAccountEmailShouldFailIfNotServiceAccount() { var credentials = GoogleCredentials.newBuilder().build(); exception.expect(IllegalArgumentException.class); exception.expectMessage("Credential is not a service account"); ServiceAccounts.serviceAccountEmail(credentials); }