Genaration of unique samaccountname

Here you go , this built on your logic . This is cloud rule of type : AttributeGenerator

  • Build’s a pattern of your logic
  • Checks if it is unique
  • If not unique the rule throws error
  • you can modify the code accordingly to resolve uniqueness by adding multiple patterns.
 import sailpoint.tools.GeneralException;
 import sailpoint.object.Identity;
 import sailpoint.api.SailPointContext;
 import org.apache.commons.lang.StringUtils;
 import java.util.Random;

 public String generateUsername(String firstName, String lastName) throws GeneralException {
         firstName = StringUtils.trimToNull(firstName);
         lastName = StringUtils.trimToNull(lastName);
         String pattern = "";


         if (lastName != null && firstName != null) {
             if (lastName.length() >= 3 && firstName.length() >= 3) {
                 String lastNameThree = lastName.substring(0, 3);
                 String firstNameThree = firstName.substring(0, 3; 
pattern = firstNameThree.concat(lastNameThree);
String randomNum = getRandomNumber(3);
 pattern = pattern + getRandomNumber;
                 }


                 if (!pattern.isEmpty() && isUnique(pattern)) {
                     return pattern1;
                 }

             } else {
                 throw new GeneralException("cannot generate unique samAccoutName");
             }
         }

         public boolean isUnique(String username) throws GeneralException {
             return !idn.accountExistsByDisplayName(application.getName(), username);
         }

         private String getRandomNumber(int length) throws GeneralException {
             if (length <= 0) {
                 throw new GeneralException("Length must be a positive integer.");
             }

             Random random = new Random();
             StringBuilder randomNumber = new StringBuilder(length); // Specify initial capacity

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

             return randomNumber.toString();
         }



         return generateUsername(identity.getFirstname(), identity.getLastname());

This should resolve your issue.

2 Likes