com.google.api.services.admin.directory.Directory Java Examples

The following examples show how to use com.google.api.services.admin.directory.Directory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QuickStart.java    From java-samples with Apache License 2.0 6 votes vote down vote up
private static void generateReport(String holdsReportFile) throws Exception {

    Directory directory = MigrationHelper.getDirectoryService();
    DirectoryService directoryService = new DirectoryService(directory);
    Vault vaultService = MigrationHelper.getVaultService();

    System.out.println(
        "--------------------------------------------------------------------------------------");
    System.out.println(
        " Starting Hold report generation. Holds will be exported to: " + holdsReportFile);
    System.out.println();

    CSVPrinter printer = getCSVPrinter(holdsReportFile);
    HoldsReport holdReport = new HoldsReport(vaultService, directoryService, printer);
    int totalHoldsCount = holdReport.buildReport();

    System.out.println();
    System.out.println(
        " Hold report generated successfully. " + totalHoldsCount + " Gmail holds exported.");
    System.out.println(
        "--------------------------------------------------------------------------------------");
  }
 
Example #2
Source File: DirectoryGroupsConnection.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> getMembersOfGroup(String groupKey) throws IOException {
  // Documentation for this API call:
  // https://developers.google.com/admin-sdk/directory/v1/reference/members/list
  try {
    ImmutableSet.Builder<String> allMembers = new ImmutableSet.Builder<>();
    Directory.Members.List listRequest =
        directory.members().list(groupKey).setRoles(Role.MEMBER.toString());
    do {
      Members currentPage = listRequest.execute();
      for (Member member : nullToEmpty(currentPage.getMembers())) {
        allMembers.add(member.getEmail());
      }
      listRequest.setPageToken(currentPage.getNextPageToken());
    } while (!Strings.isNullOrEmpty(listRequest.getPageToken()));
    return allMembers.build();
  } catch (GoogleJsonResponseException e) {
    if (e.getDetails() != null
        && e.getDetails().getCode() == SC_NOT_FOUND
        && e.getDetails().getMessage().equals(GROUP_NOT_FOUND_MSG)) {
      return ImmutableSet.of();
    } else {
      throw e;
    }
  }
}
 
Example #3
Source File: DirectoryModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Provides
static Directory provideDirectory(
    @DelegatedCredential GoogleCredentialsBundle credentialsBundle,
    @Config("projectId") String projectId) {
  return new Directory.Builder(
          credentialsBundle.getHttpTransport(),
          credentialsBundle.getJsonFactory(),
          credentialsBundle.getHttpRequestInitializer())
      .setApplicationName(projectId)
      .build();
}
 
Example #4
Source File: MigrationHelper.java    From java-samples with Apache License 2.0 5 votes vote down vote up
public static Directory getDirectoryService() throws IOException {
  Directory service =
      new Directory.Builder(HTTP_TRANSPORT, JSON_FACTORY, authorize())
          .setApplicationName(APPLICATION_NAME)
          .build();
  return service;
}
 
Example #5
Source File: GoogleProvisioningConnector.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected String createUser(ProvisioningEntity provisioningEntity)
        throws IdentityProvisioningException {
    boolean isDebugEnabled = log.isDebugEnabled();
    if (isDebugEnabled) {
        log.debug("Triggering create operation for Google Provisioning Connector");
    }

    User createdUser = null;
    try {
        User newUser = new User();

        newUser = buildGoogleUser(provisioningEntity);

        Directory.Users.Insert request = getDirectoryService().users().insert(newUser);
        createdUser = request.execute();

    } catch (IOException e) {
        throw new IdentityProvisioningException("Error while creating user : "
                                                + provisioningEntity.getEntityName(), e);
    }

    if (isDebugEnabled) {
        log.debug("Returning created user's email : " + createdUser.getPrimaryEmail());
    }

    if (log.isTraceEnabled()) {
        log.trace("Ending createUser() of " + GoogleProvisioningConnector.class);
    }
    return createdUser.getPrimaryEmail();
}
 
Example #6
Source File: GoogleDirectoryUserRolesProvider.java    From fiat with Apache License 2.0 5 votes vote down vote up
private Directory getDirectoryService() {
  HttpTransport httpTransport = new NetHttpTransport();
  JacksonFactory jacksonFactory = new JacksonFactory();
  GoogleCredential credential = getGoogleCredential();

  PropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(credential);
  accessor.setPropertyValue("serviceAccountUser", config.getAdminUsername());
  accessor.setPropertyValue("serviceAccountScopes", SERVICE_ACCOUNT_SCOPES);

  return new Directory.Builder(httpTransport, jacksonFactory, credential)
      .setApplicationName("Spinnaker-Fiat")
      .build();
}
 
Example #7
Source File: Utils.java    From cloud-search-samples with Apache License 2.0 5 votes vote down vote up
static Directory buildDirectoryService() throws IOException, GeneralSecurityException {
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(Collections.singletonList(
        "https://www.googleapis.com/auth/admin.directory.user"
    ));
  }
  return new Directory.Builder(GoogleNetHttpTransport.newTrustedTransport(),
          JacksonFactory.getDefaultInstance(),
          credential)
      .setApplicationName("Cloud identity samples")
      .build();

}
 
Example #8
Source File: MapUserIdentityCommand.java    From cloud-search-samples with Apache License 2.0 5 votes vote down vote up
public void run() {
  try {
    Directory service = Utils.buildDirectoryService();
    Map<String, Object> properties = Collections.singletonMap(
        idSource + "_identifier", externalId);
    User user = new User().setCustomSchemas(
        Collections.singletonMap(idSource, properties));
    User updatedUser = service.users().update(userEmail, user).execute();
    System.out.printf("Updated user %s", updatedUser.toPrettyString());
  } catch (Exception e) {
    System.err.printf("Unable to map user identity: %s\n", e);
    e.printStackTrace(System.err);
  }
}
 
Example #9
Source File: UnmapUserIdentityCommand.java    From cloud-search-samples with Apache License 2.0 5 votes vote down vote up
public void run() {
  try {
    Directory service = Utils.buildDirectoryService();
    Map<String, Object> properties = Collections.singletonMap(
        idSource + "_identifier", "");
    User user = new User().setCustomSchemas(
        Collections.singletonMap(idSource, properties));
    User updatedUser = service.users().update(userEmail, user).execute();
    System.out.printf("Updated user: %s", updatedUser.toPrettyString());
  } catch (Exception e) {
    System.err.printf("Unable to unmap user identity: %s\n", e);
    e.printStackTrace(System.err);
  }
}
 
Example #10
Source File: GetUserCommand.java    From cloud-search-samples with Apache License 2.0 5 votes vote down vote up
public void run() {
  try {
    Directory service = Utils.buildDirectoryService();
    User user = service.users().get(userEmail)
        .setProjection("full")
        .execute();
    System.out.printf("User: %s\n", user.toPrettyString());
  } catch (Exception e) {
    System.err.printf("Unable to retrieve user: %s\n", e);
    e.printStackTrace(System.err);
  }
}
 
Example #11
Source File: UsersServiceImpl.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an instance of {@link com.google.api.services.admin.directory.Directory.Builder} for
 * creating an instance of {@link Directory} to make Google Admin SDK API requests.
 */
@Override
public Directory.Builder getServiceBuilder(
    HttpTransport transport,
    JsonFactory jsonFactory,
    HttpRequestInitializer requestInitializer) {
  return new Directory.Builder(transport, jsonFactory, requestInitializer);
}
 
Example #12
Source File: DirectoryFacade.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Builder for DirectoryFacade objects.
 *
 * @param serviceKeyStream {@link InputStream} for the JSON file containing the service account
 *   key to authenticate with the Cloud Identity service.
 * @param adminEmail the email of the domain's admin account
 * @param domain the organization's domain
 */

static DirectoryFacade create(
    InputStream serviceKeyStream, String adminEmail, String domain)
    throws IOException, GeneralSecurityException {
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  GoogleCredential credential = GoogleCredential
      .fromStream(serviceKeyStream)
      .createScoped(ADMIN_SCOPES);
  Credential adminCredential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(credential.getServiceAccountId())
      .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
      .setServiceAccountScopes(ADMIN_SCOPES)
      .setServiceAccountUser(adminEmail)
      .build();
  // Google services are rate-limited. The RetryPolicy allows to rety when a
  // 429 HTTP status response (Too Many Requests) is received.
  RetryPolicy retryPolicy = new RetryPolicy.Builder().build();
  RetryRequestInitializer requestInitializer = new RetryRequestInitializer(retryPolicy);
  Directory.Builder directoryBuilder = new Directory.Builder(
      httpTransport, jsonFactory, request -> {
    adminCredential.initialize(request);
    requestInitializer.initialize(request);
  });
  Directory directory = directoryBuilder.build();
  return new DirectoryFacade(directory, domain);
}
 
Example #13
Source File: GoogleDirectoryUserRolesProvider.java    From fiat with Apache License 2.0 4 votes vote down vote up
protected Groups getGroupsFromEmail(String email) throws IOException {
  Directory service = getDirectoryService();
  return service.groups().list().setDomain(config.getDomain()).setUserKey(email).execute();
}
 
Example #14
Source File: DirectoryFacade.java    From connector-sdk with Apache License 2.0 4 votes vote down vote up
private DirectoryFacade(Directory directory, String domain) {
  this.directory = directory;
  this.domain = domain;
}
 
Example #15
Source File: GoogleProvisioningConnector.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Delete provisioned user from google account
 *
 * @param provisioningEntity
 * @throws IdentityProvisioningException
 */
protected void deleteUser(ProvisioningEntity provisioningEntity)
        throws IdentityProvisioningException {
    boolean isDebugEnabled = log.isDebugEnabled();
    if (isDebugEnabled) {
        log.debug("Triggering delete operation for Google Provisioning Connector");
    }

    ProvisionedIdentifier provisionedIdentifier = provisioningEntity.getIdentifier();
    if (provisionedIdentifier != null && provisionedIdentifier.getIdentifier() != null) {
        User deletingUser = new User();
        deletingUser.setPrimaryEmail(provisionedIdentifier.getIdentifier());

        Directory.Users.Delete request;
        try {
            request = getDirectoryService().users().delete(
                    provisionedIdentifier.getIdentifier());
            request.execute();

        } catch (IOException e) {
            if (((GoogleJsonResponseException) e).getStatusCode() == 404) {
                log.warn("Exception while deleting user from google. User may be already deleted from google");
                if (log.isDebugEnabled()) {
                    log.debug("Exception while deleting user from google. User may be already deleted from google", e);
                }
            } else {
                throw new IdentityProvisioningException("Error while deleting Google user : "
                                                        + provisioningEntity.getEntityName(), e);
            }
        }

        if (isDebugEnabled) {
            log.debug("Deleted user :" + provisioningEntity.getEntityName()
                      + " with the primaryEmail : " + provisionedIdentifier.getIdentifier());
        }
    } else {
        throw new IdentityProvisioningException(
                "Cannot delete Google user, provisionedIdentifier is invalide.");
    }

    if (log.isTraceEnabled()) {
        log.trace("Ending deleteUser() of " + GoogleProvisioningConnector.class);
    }
}
 
Example #16
Source File: GoogleProvisioningConnector.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Build and returns a Directory service object authorized with the service accounts that act on
 * behalf of the given user.
 *
 * @return Directory service object that is ready to make requests.
 * @throws IdentityProvisioningException
 */
protected Directory getDirectoryService() throws IdentityProvisioningException {
    boolean isDebugEnabled = log.isDebugEnabled();
    if (isDebugEnabled) {
        log.debug("Starting getDirectoryService() of " + GoogleProvisioningConnector.class);
    }

    String serviceAccountEmailKey = "google_prov_service_acc_email";
    String adminEmailKey = "google_prov_admin_email";
    String privateKeyKey = "google_prov_private_key";
    String applicationNameKey = "google_prov_application_name";

    /** Email of the Service Account */
    String serviceAccountId = this.configHolder.getValue(serviceAccountEmailKey);
    /** Admin email */
    String serviceAccountUser = this.configHolder.getValue(adminEmailKey);
    /** Path to the Service Account's Private Key file */
    String serviceAccountPrivateKeyString = this.configHolder.getValue(privateKeyKey);
    /** Application name */
    String applicationName = this.configHolder.getValue(applicationNameKey);

    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    if (isDebugEnabled) {
        log.debug("serviceAccountId" + serviceAccountId);
        log.debug("setServiceAccountScopes"
                  + Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER));
        log.debug("setServiceAccountUser" + serviceAccountUser);
    }

    Directory service = null;
    try {
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport).setJsonFactory(jsonFactory)
                .setServiceAccountId(serviceAccountId)
                .setServiceAccountScopes(Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER))
                .setServiceAccountUser(serviceAccountUser)
                .setServiceAccountPrivateKeyFromP12File(googlePrvKey).build();

        service = new Directory.Builder(httpTransport, jsonFactory, credential)
                .setHttpRequestInitializer(credential).setApplicationName(applicationName)
                .build();

    } catch (GeneralSecurityException | IOException e) {
        throw new IdentityProvisioningException("Error while obtaining connection from google",
                                                e);
    }

    if (log.isDebugEnabled()) {
        log.debug("Ending getDirectoryService() of " + GoogleProvisioningConnector.class);
    }
    return service;
}
 
Example #17
Source File: DirectoryService.java    From java-samples with Apache License 2.0 4 votes vote down vote up
public DirectoryService(Directory directoryService) {
  this.directoryService = directoryService;
  getOrgUnits();
}
 
Example #18
Source File: GoogleClient.java    From account-provisioning-for-google-apps with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new authorized Google API client.
 *
 * @param projectName The project name that is displayed in the Google
 *        Developer Console.
 * @param credential The GoogleCredential object.
 * @return The Admin SDK client object
 */
protected Directory createAuthorizedClient(String projectName, GoogleCredential credential) {
  return new Directory.Builder(httpTransport, jsonFactory, credential).setApplicationName(
      projectName).build();
}