public JiraJdbcDirectoryConfiguration toJiraJdbcConfiguration(Directory directory) {
   JiraJdbcDirectoryConfiguration configuration = new JiraJdbcDirectoryConfiguration();
   configuration.setDirectoryId(directory.getId() != null ? directory.getId() : 0);
   configuration.setActive(directory.isActive());
   configuration.setName(directory.getName());
   configuration.setDatasourceJndiName(
       directory.getAttributes().get(JiraJdbcDirectoryConfiguration.JNDI_NAME_ATTRIBUTE_KEY));
   return configuration;
 }
 private boolean isSynchroniseRunning() {
   for (Directory directory : crowdDirectoryService.findAllDirectories()) {
     if (directory.isActive()
         && crowdDirectoryService.isDirectorySynchronising(directory.getId())) {
       return true;
     }
   }
   return false;
 }
  private Map<String, String> getDirectories() {
    Map<String, String> directories = new LinkedHashMap<String, String>();

    // switch keys and values because the Crowd map is back-to-front
    for (Directory directory : crowdDirectoryService.findAllDirectories()) {
      if (directory.getType() == DirectoryType.INTERNAL
          || directory.getType() == DirectoryType.DELEGATING) {
        directories.put(directory.getId().toString(), directory.getName());
      }
    }
    return directories;
  }
  public InternalDirectoryConfiguration toInternalConfiguration(Directory directory) {
    InternalDirectoryConfiguration configuration = new InternalDirectoryConfiguration();
    configuration.setDirectoryId(directory.getId() != null ? directory.getId() : 0);
    configuration.setActive(directory.isActive());
    configuration.setName(directory.getName());

    Map<String, String> attributes = directory.getAttributes();
    String useNestedGroups = attributes.get(DirectoryImpl.ATTRIBUTE_KEY_USE_NESTED_GROUPS);
    if (useNestedGroups != null) {
      configuration.setNestedGroupsEnabled(Boolean.valueOf(useNestedGroups));
    } else {
      configuration.setNestedGroupsEnabled(false);
    }

    return configuration;
  }
 private Directory validateDirectory(
     final Long directoryId, final BindException errors, String field) {
   if (directoryId == -1) {
     errors.addError(
         new FieldError(
             "migration",
             field,
             i18nResolver.getText(
                 "embedded.crowd.directory.migrate.users.field.directory.required")));
     return null;
   }
   Directory directory = crowdDirectoryService.findDirectoryById(directoryId);
   if (directory == null) {
     errors.addError(
         new FieldError(
             "migration",
             field,
             i18nResolver.getText(
                 "embedded.crowd.directory.migrate.users.field.directory.not.found")));
   } else {
     if (directory.getType() != DirectoryType.INTERNAL
         && directory.getType() != DirectoryType.DELEGATING) {
       errors.addError(
           new FieldError(
               "migration",
               field,
               i18nResolver.getText(
                   "embedded.crowd.directory.migrate.users.field.directory.wrong.type")));
     }
     final Set<OperationType> allowedOperations = directory.getAllowedOperations();
     if (!allowedOperations.contains(OperationType.CREATE_USER)
         || !allowedOperations.contains(OperationType.CREATE_GROUP)
         || !allowedOperations.contains(OperationType.DELETE_USER)
         || !allowedOperations.contains(OperationType.DELETE_GROUP)) {
       errors.addError(
           new FieldError(
               "migration",
               field,
               i18nResolver.getText(
                   "embedded.crowd.directory.migrate.users.field.directory.read.only")));
     }
   }
   return directory;
 }
  @Override
  public void doUpgrade(boolean setupMode) throws Exception {
    // Retrieve all the directories and synchronize them if they are synchronizable.
    for (Directory directory : crowdDirectoryService.findAllDirectories()) {
      if (crowdDirectoryService.isDirectorySynchronisable(directory.getId())) {
        LOG.debug("Reindex all data if indexing is turned on.");
        try {
          crowdDirectoryService.synchroniseDirectory(directory.getId(), false);
        } catch (OperationFailedException e) {
          LOG.warn(
              "Directory - '"
                  + directory.getName()
                  + "' was not successfully synchronised."
                  + "  You might need to shutdown and restart JIRA after the upgrade completes.");
        }
      }
    }

    // Reindex
    super.doUpgrade(setupMode);
  }
  public DelegatingLdapDirectoryConfiguration toDelegatingLdapConfiguration(
      final Directory directory) {
    DelegatingLdapDirectoryConfiguration configuration = new DelegatingLdapDirectoryConfiguration();
    configuration.setDirectoryId(directory.getId() != null ? directory.getId() : 0);
    configuration.setActive(directory.isActive());
    configuration.setName(directory.getName());

    LdapDelegatingDirectoryAttributes attributes =
        LdapDelegatingDirectoryAttributes.fromAttributesMap(directory.getAttributes());
    BeanUtils.copyProperties(attributes, configuration);
    configuration.setType(attributes.getDelegatedToClass());
    final String ldapAutoAddGroups = attributes.getLdapAutoAddGroups();
    if (ldapAutoAddGroups != null) {
      configuration.setLdapAutoAddGroups(
          pipeSeparatedGroupsToCommaSeparatedGroups(ldapAutoAddGroups));
    } else {
      configuration.setLdapAutoAddGroups("");
    }

    return configuration;
  }
  public LdapDirectoryConfiguration toLdapConfiguration(Directory directory) {
    LdapDirectoryConfiguration configuration = new LdapDirectoryConfiguration();
    configuration.setLdapPermissionOption(
        PermissionOption.fromAllowedOperations(directory.getAllowedOperations()));
    configuration.setActive(directory.isActive());
    configuration.setLdapUserEncryption(directory.getEncryptionType());
    configuration.setDirectoryId(directory.getId() != null ? directory.getId() : 0);
    configuration.setType(directory.getImplementationClass());
    configuration.setName(directory.getName());

    LdapDirectoryAttributes attributes =
        LdapDirectoryAttributes.fromAttributesMap(directory.getAttributes());
    BeanUtils.copyProperties(attributes, configuration);
    configuration.setCrowdSyncIncrementalEnabled(attributes.isIncrementalSyncEnabled());

    return configuration;
  }
  public CrowdDirectoryConfiguration toCrowdConfiguration(Directory directory) {
    CrowdDirectoryConfiguration configuration = new CrowdDirectoryConfiguration();
    configuration.setCrowdPermissionOption(
        CrowdPermissionOption.fromAllowedOperations(directory.getAllowedOperations()));
    configuration.setDirectoryId(directory.getId() != null ? directory.getId() : 0);
    configuration.setActive(directory.isActive());
    configuration.setName(directory.getName());

    CrowdDirectoryAttributes attributes =
        CrowdDirectoryAttributes.fromAttributesMap(directory.getAttributes());
    BeanUtils.copyProperties(attributes, configuration);
    // Convert polling interval to minutes to display to user
    configuration.setCrowdServerSynchroniseIntervalInMin(
        NumberUtils.toLong(attributes.getCrowdServerSynchroniseIntervalInSeconds()) / 60);

    return configuration;
  }
  private void migrateUsers(
      final long fromDirectoryId,
      final long toDirectoryId,
      final String remoteUser,
      final MigrateDirectoryUsersCommand migrateUsersCommand,
      final BindException errors) {
    // Check the to & from directories

    Directory from = validateDirectory(fromDirectoryId, errors, "fromDirectoryId");
    Directory to = validateDirectory(toDirectoryId, errors, "toDirectoryId");
    if (to != null && to.equals(from)) {
      errors.addError(
          new FieldError(
              "migration",
              "toDirectoryId",
              i18nResolver.getText("embedded.crowd.directory.migrate.users.field.directory.same")));
    }
    if (errors.hasErrors()) {
      return;
    }

    setDirectoryEnabled(from, false);
    setDirectoryEnabled(to, false);

    // Copy
    SearchRestriction restriction = NullRestrictionImpl.INSTANCE;
    UserQuery<User> query = new UserQuery<User>(User.class, restriction, 0, -1);
    try {
      // TODO: Sucking all users in like this may be problematic for Confluence.  If planning to
      // enable this
      // TODO: feature for other products make sure the performance impacts are understood.
      List<User> users = directoryManager.searchUsers(fromDirectoryId, query);
      final AtomicLong migratedCount = new AtomicLong(0);
      for (Iterator<User> iter = users.iterator(); iter.hasNext(); ) {
        final User user = iter.next();
        transactionTemplate.execute(
            new TransactionCallback() {
              public Object doInTransaction() {
                try {
                  migrateUser(fromDirectoryId, toDirectoryId, remoteUser, user, migratedCount);
                } catch (Exception e) {
                  throw new RuntimeException(e);
                }
                return null;
              }
            });
      }
      migrateUsersCommand.setTestSuccessful(true);
      migrateUsersCommand.setTotalCount(users.size());
      migrateUsersCommand.setMigratedCount(migratedCount.get());
    } catch (Exception e) {
      log.error("User migration failed", e);
      errors.addError(
          new ObjectError(
              "migration",
              i18nResolver.getText(
                  "embedded.crowd.directory.migrate.users.error",
                  htmlEncoder.encode(e.getMessage()))));
    }

    // Enable both directories
    setDirectoryEnabled(from, true);
    setDirectoryEnabled(to, true);
  }