Username { public static Username of(String username) { Preconditions.checkArgument(username != null, "username should not be null or empty"); Preconditions.checkArgument(!username.trim().isEmpty(), "username should not be null or empty after being trimmed"); Preconditions.checkArgument(username.length() <= MAXIMUM_MAIL_ADDRESS_LENGTH, "username length should not be longer than %s characters", MAXIMUM_MAIL_ADDRESS_LENGTH); List<String> parts = ImmutableList.copyOf(Splitter.on('@').split(username)); switch (parts.size()) { case 1: return fromLocalPartWithoutDomain(username); case 2: return fromLocalPartWithDomain(parts.get(0), parts.get(1)); } throw new IllegalArgumentException("The username should not contain multiple domain delimiter. Value: " + username); } private  Username(String localPart, Optional<Domain> domainPart); static Username of(String username); static Username fromLocalPartWithDomain(String localPart, String domain); static Username fromLocalPartWithDomain(String localPart, Domain domain); static Username fromMailAddress(MailAddress address); static Username fromLocalPartWithoutDomain(String localPart); static Username from(String localPart, Optional<String> domain); String getLocalPart(); Optional<Domain> getDomainPart(); Username withOtherDomain(Optional<Domain> domain); Username withOtherDomain(Domain domain); boolean hasDomainPart(); Username withDefaultDomain(Optional<Domain> defaultDomain); Username withDefaultDomain(Domain defaultDomain); Username withDefaultDomainFromUser(Username other); String asString(); MailAddress asMailAddress(); @Override final boolean equals(Object o); @Override final int hashCode(); @Override String toString(); static final int MAXIMUM_MAIL_ADDRESS_LENGTH; }
@Test void fromUsernameShouldThrowOnNull() { assertThatThrownBy(() -> Username.of(null)) .isInstanceOf(IllegalArgumentException.class); }
@Test void fromUsernameShouldThrowOnEmpty() { assertThatThrownBy(() -> Username.of("")) .isInstanceOf(IllegalArgumentException.class); }
@Test void fromUsernameShouldThrowWhenTooLong() { String tail = "@a"; assertThatThrownBy(() -> Username.of(StringUtils.repeat('j', 255 - tail.length() + 1) + tail)) .isInstanceOf(IllegalArgumentException.class); }
@Test void fromUsernameShouldThrowWhenMultipleDomainDelimiter() { assertThatThrownBy(() -> Username.of("aa@aa@aa")) .isInstanceOf(IllegalArgumentException.class); }
@Test void fromUsernameShouldThrowWhenEndsWithDomainDelimiter() { assertThatThrownBy(() -> Username.of("aa@")) .isInstanceOf(IllegalArgumentException.class); }
@Test void fromUsernameShouldThrowWhenStartsWithDomainDelimiter() { assertThatThrownBy(() -> Username.of("@aa")) .isInstanceOf(IllegalArgumentException.class); }
@Test void fromUsernameShouldThrowWhenBlank() { assertThatThrownBy(() -> Username.of(" ")) .isInstanceOf(IllegalArgumentException.class); }