UuidUtil { Optional<Uuid> newUuidIfValidPattern(String possibleUuid) { Preconditions.checkNotNull(possibleUuid, "possibleUuid == null"); if (uuidPattern == null) { if (Uuid.PATTERN_CONSTANTS.size() != 1) { throw new IllegalStateException("Uuid.PATTERN_CONSTANTS.size() != 1"); } uuidPattern = Pattern.compile(Uuid.PATTERN_CONSTANTS.get(0)); } if (uuidPattern.matcher(possibleUuid).matches()) { return Optional.of(new Uuid(possibleUuid)); } else { return Optional.empty(); } }    }
@Test public void valid() { assertThat(uuidUtil.newUuidIfValidPattern("f81d4fae-7dec-11d0-a765-00a0c91e6bf6").get()) .isEqualTo(new Uuid("f81d4fae-7dec-11d0-a765-00a0c91e6bf6")); }
@Test public void invalid() { assertThat(uuidUtil.newUuidIfValidPattern("tap61d7aec1-2c")) .isNotEqualTo("tap61d7aec1-11"); }
@Test public void empty() { assertThat(uuidUtil.newUuidIfValidPattern("")).isNotNull(); }
@Test(expected = NullPointerException.class) public void isNull() { assertThat(uuidUtil.newUuidIfValidPattern(null)); }