Class UniqueCodeGenerator

java.lang.Object
dev.getelements.elements.sdk.util.UniqueCodeGenerator

public class UniqueCodeGenerator extends Object
Generates unique codes based on a set of candidate characters, a random generator, and a rejection predicate. The generator will continue to produce codes until one is found that does not match the rejection predicate.
  • Constructor Details

    • UniqueCodeGenerator

      public UniqueCodeGenerator(UniqueCodeGenerator.Configuration configuration)
      Creates a new UniqueCodeGenerator with the specified configuration.
      Parameters:
      configuration - the configuration for the generator
  • Method Details

    • tryGenerateUniqueCode

      public Optional<String> tryGenerateUniqueCode(int length)
      Generates a unique code of the specified length, ensuring it does not match the rejection predicate.
      Parameters:
      length - the length of the code to generate
    • tryGenerateUniqueCode

      public Optional<String> tryGenerateUniqueCode(int length, int maxAttempts)
      Generates a unique code of the specified length, ensuring it does not match the rejection predicate.
      Parameters:
      length - the length of the code to generate
      maxAttempts - the maximum number of attempts to generate a unique code
    • tryGenerateUniqueCode

      public Optional<String> tryGenerateUniqueCode(int length, int maxAttempts, Predicate<String> accept)
      Generates a unique code of the specified length, ensuring it does not match the rejection predicate.
      Parameters:
      length - the length of the code to generate
      maxAttempts - the maximum number of attempts to generate a unique code
      accept - an additional predicate to accept generated codes after all tests have been attempted. If the predicate returns true, then the code is accepted; otherwise, generation continues until maxAttempts is reached.
    • tryComputeWithUniqueCode

      public <T> Optional<T> tryComputeWithUniqueCode(int length, int maxAttempts, Function<String,Optional<T>> resultFunction)
      Generates a unique code of the specified length allowing for a custom result function to determine acceptance. This is useful if generating a code requires additional processing, such as checking a database for uniqueness and doing so while honoring concurrency concerns (such as atomic inserting or rejecting the code to prevent duplicates).
      Parameters:
      length - the length of the code to generate
      maxAttempts - the maximum number of attempts to generate a unique code
      resultFunction - a function that tests the generated code and returns an Optional result. If the function returns an Optional containing a value, then the code is accepted and the value is returned. If the function returns an empty Optional, then generation continues until maxAttempts is reached or a code is accepted.