Skip to Content
Technical Articles
Author's profile photo DUSHYANT GARG

Generating Alpha-numeric String using Groovy

Generating Alpha-numeric String using Groovy

Steps to generate an alphanumeric string of length 8 using groovy.

  1. Create a basic Iflow.
  2. Add Groovy to generate alphanumeric string of length 8.
    import com.sap.gateway.ip.core.customdev.util.Message
    import java.security.SecureRandom
    def Message processData(Message message)
    {
    def UniqueString = generateRnadomKey()
    message.setBody(UniqueString)
    return message
    }
    
    def generateRnadomKey()
    {
    def chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    def random = new SecureRandom()
    def key = ''
    for(int i = 0; i<8; i++)
    {
    int index = random.nextInt(chars.length())
    key += chars[index]
    }
    return key
    }‚Äč
  3. Suppose we have generate a reference id of length 25 consist of 8 random alphanumeric string and current date with timezone.

Example:

Suppose we have random string is 8yu78H1e and current date with timezone value 10112023144952324.

The final output will be 8yu78H1e10112023144952324.

  1. In Content modifier use this syntax to print custom timezone date and time.

${in.body}${date-with-timezone:now:IST:ddMMyyyyHHmmssS}

  1. Add Start point and end point in the iflow for simulation.
  2. Click on simulation tab to run the simulation.
  3. Once the simulation done click on the end message box to check the reference id.
  4. We are getting the reference id of length 25 which consist of 8 random alphanumeric string and current date with timezone.

Thanks

Dushyant

Assigned Tags

      5 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Vadim Klimov
      Vadim Klimov
      Hello Dushyant,
      May I propose an alternative implementation that uses an Apache Commons Lang library (it doesn't need to be imported to the iFlow, it is already a part of SAP Cloud Integration runtime) and can make the script more compact.
      Here is an example of the script that leverages the mentioned library and generates a string of 8 random alphanumeric characters:
      import com.sap.gateway.ip.core.customdev.util.Message
      import org.apache.commons.lang3.RandomStringUtils
      
      Message processData(Message message) {
      def length = 8
      def output = RandomStringUtils.random(length, true, true)
      message.setBody(output)
      return message
      }
      The code snippet is simplified and is provided for illustration purposes. For example, the length of a string to be generated can be externalized and passed to a script using an exchange property rather than making it hard-coded in the script.
      Further, the script can be enhanced to generate strings with subsets of characters / specific characters - for example, only upper-case or lower-case letters, or even specific sets of letters, etc.
      Regards,
      Vadim
      Author's profile photo DUSHYANT GARG
      DUSHYANT GARG
      Blog Post Author

      Hello Vadim,

      Thanks for sharing this script. Yes we can use that but to specify alpha-numeric more, I have used that. I am glad that you have shared this script. This script also helps people to learn more import functions also.

      Regards

      Dushyant

      Author's profile photo vinay mittal
      vinay mittal

      Vadims solution is a better and cleaner approach. Random function from apache has far more customizable options available.

       

      Also your code doesn't always gurantee that the string will have numbers in it.

       

      What if all 8 random numbers are between 0 and 41? You get just alphabets in that case.

       

      Also Dushyant are you sure that this content qualifies as a blog? This is already covered on sites like stackoverflow 100s of times.

       

      Regards

      Vinay

      Author's profile photo DUSHYANT GARG
      DUSHYANT GARG
      Blog Post Author

      Hello Vinay
      This apache random function also doesn't guarantee to return string that have numbers all time. I am attaching the screenshot for the same.

      The script I have given is more to specify we have to find the random string only from the given string, we can change the input strings also like we have some other string from which we have to find the random string. That's why I have used this approach.

      Regards

      Dushyant

      Author's profile photo Vadim Klimov
      Vadim Klimov

      Hi Dushyant,

      That's a fair observation - my question is, would you expect it to always generate strings that contain both alphabetic and numeric characters? It is always a good idea to first reach out to the documentation of the API (of SDK or any 3rd party library) that you are considering using, it would commonly provide information about intended use cases and also restrictions that apply.

      In the documentation for RandomStringUtils, for example, for method implementations that generate alphanumeric strings, it is written that if corresponding arguments are set to true, generating strings may include respective character sets. Note that this is may, not must. The idea behind this is as follows: when calling a method, the one provides a set of characters that can be used for string generation (as well as some other parameters - for example, the desired length of a string), and the method implementation makes sure that the generated string only includes those characters and doesn't contain any characters that are outside of the boundaries of the specified set of characters. The implementation doesn't mandate that specific characters from the set always appear in the generated string.

      So, if the requirement is not to generate an alphanumeric string, but to ensure that the generated string is alphanumeric and contains at least one digit, then you can combine the mentioned RandomStringUtils with other string utility classes that can make a check of the generated string.

      For example, after the string gets generated (note that I now wrap a random string generation call into a closure, since we will need to reuse it later):

      def generate = { int l -> RandomStringUtils.randomAlphanumeric(l) }
      
      def length = 8
      def output = generate(length)

      we can check if the string is alphanumeric or alphabetic-only (here, I use another utility class from an Apache Commons Lang library, but indeed the implementation can leverage a plethora of other approaches - regular expressions is another flexible and powerful tool that can be considered) and re-generate it until we get the desired string:

      while (StringUtils.isAlpha(output)) { output = generate(length) }

      You can further enhance and advance the implementation based on your further requirements - for example, you can check if the string starts or ends with a digit, or if it starts with a capital letter, or if the string doesn't use the same letter more than one time (especially relevant for short strings), etc. In my view, implementing all such requirements as cases in the random string generator is overkill and shall be taken care of outside of the core string generator function using additional checks. that are specific to your requirements.

      I would echo comments from Vinay and challenge a decision to dedicate the entire blog post to such compact code snippets - especially given they are not SAP Cloud Integration specific (but are rather about general Java) and can be optimized using relevant libraries, making code snippets even more compact and expressive.

      Regards,

      Vadim