1

The UUID input defined in an JAVA API is padding 0's when tried with invalid UUID.

For example f185d2ab-50-4fd0-bbb3-af04543b6f05 is being converted to f185d2ab-0050-4fd0-bbb3-af04543b6f05. Observe the second part of the UUID. Is there any way we can stop this padding and respond back with Bad Input or something

Te Jas
  • 45
  • 9
  • Test it with a regex? – shmosel Nov 16 '21 at 06:56
  • Yes, we can. It would be great if there is any solution provided by Java for this. Instead we write a Utility and apply across all places where this UUID is being accepted – Te Jas Nov 16 '21 at 07:04

1 Answers1

1

If you look at the Java implementation for UUID.fromString() which I assume is what you are using:

public static UUID fromString(String name) {
    String[] components = name.split("-");
    if (components.length != 5)
        throw new IllegalArgumentException("Invalid UUID string: "+name);
    for (int i=0; i<5; i++)
        components[i] = "0x"+components[i];

    long mostSigBits = Long.decode(components[0]).longValue();
    mostSigBits <<= 16;
    mostSigBits |= Long.decode(components[1]).longValue();
    mostSigBits <<= 16;
    mostSigBits |= Long.decode(components[2]).longValue();

    long leastSigBits = Long.decode(components[3]).longValue();
    leastSigBits <<= 48;
    leastSigBits |= Long.decode(components[4]).longValue();

    return new UUID(mostSigBits, leastSigBits);
}

https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/UUID.java

It is padding with 0X, and the only failure it would throw is if it does not have 5 sections in a String, however if you do not like this, and wanted your own, you could create a Wrapper

public static UUID fromStringValidates(String inputUUID){

   //Apply pattern from StackOverflow to validate inputUUID
   //https://stackoverflow.com/questions/37615731/java-regex-for-uuid
   //Fail with error message you want
   
   return UUID.fromString(inputUUID);
}
JCompetence
  • 6,997
  • 3
  • 19
  • 26