AD account uniquness

we are planning to generate a unique samaccount name with below logic.
1st letter of firstname + first 3 letters of lastname + some 3 random
can i have code

Hi @nikhi098

Please verify if the solution below aligns with your requirements.

other examples:

IdentityNow transforms - Username generator - Compass

Generate unique samaccountname for AD source

import sailpoint.tools.GeneralException;
import sailpoint.object.Identity;
import sailpoint.api.SailPointContext;
import org.apache.commons.lang.StringUtils;
import java.util.Random;

public class UsernameGenerator {

public static String generateUsername(String firstName, String lastName, SailPointContext context, String applicationName) throws GeneralException {
    firstName = StringUtils.trimToNull(firstName);
    lastName = StringUtils.trimToNull(lastName);

    if (firstName == null || lastName == null || firstName.length() < 3 || lastName.length() < 3) {
        throw new GeneralException("Cannot generate username: first or last name too short or null");
    }

    String pattern = firstName.substring(0, 3).toLowerCase() + lastName.substring(0, 3).toLowerCase();
    String finalUsername = pattern + getRandomNumber(3);

    if (isUnique(finalUsername, context, applicationName)) {
        return finalUsername;
    } else {
        throw new GeneralException("Generated username is not unique.");
    }
}

private static boolean isUnique(String username, SailPointContext context, String applicationName) throws GeneralException {
    
    return !context.getObjectByName(Identity.class, username) != null;
}

private static String getRandomNumber(int length) {
    Random random = new Random();
    StringBuilder randomNumber = new StringBuilder();

    for (int i = 0; i < length; i++) {
        randomNumber.append(random.nextInt(10));
    }

    return randomNumber.toString();
}

}

  • Builds a username pattern from first 3 letters of first and last name + 3 random digits
  • Checks if the username is unique
  • Throws an error if not unique